最简单Struts2实例

来源:互联网 发布:查看linux版本号 编辑:程序博客网 时间:2024/05/02 16:59

以下用登录功能,实现一个最简单的 struts2 可运行的实例。

 

一、新建项目 TEST

二、添加 STRUTS2 的包,共加5个, 复制到WEB-INF/lib 下就可以了。

三、login.jsp

<%@ page language="java" contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
  <title>--------login--------</title>

  <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->

 </head>

 <body>
  <form action="Login" method="post">
   <%--
   用户名:
   <input type="text" name="username" />
   </br>
   密码:
   <input type="text" name="password" />
   </br>
   <input type="submit" value="登录" />
   <input type="reset" value="重填" />
  --%>

   <s:textfield name="username" label="用户名" />
   <s:password name="password" label="密码" />
   <s:submit value="登录" />
  </form>
 </body>
</html>
四、业务ACTION:LoginAction.java

package src;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ActionContext;

public class LoginAction extends ActionSupport {
 private String username;
 private String password;

 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 public String getUsername() {
  return username;
 }
 public void setUsername(String username) {
  this.username = username;
 }

 public String execute() throws Exception
 {
  if (this.getUsername().equals("1") &&
    this.getPassword().equals("1"))
  {
   ActionContext.getContext().getSession().put("user", this.getUsername());
   return SUCCESS;
  }
  else
  {
   return ERROR;
  } 
 }

 public void validate()
 {
  if (this.getUsername()==null || this.getUsername().trim().equals(""))
  {
   addFieldError("username", "用户名错误!");
  }
  
  if (this.getPassword()==null || this.getPassword().trim().equals(""))
  {
   addFieldError("password", "password 错误!");
  }
 }

}

 

五、配置struts.xml

<?xml version="1.0" encoding="GBK" ?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd" >
<struts>
 <package name="test" extends="struts-default">
  <action name="Login" class="src.LoginAction">
   <result name="input">/login.jsp</result>
   <result name="error">/error.jsp</result>
   <result name="success">/Welcome.jsp</result>
  </action>

 </package>
</struts>

完成后,发布,http://localhost:9090/test/login.jsp就可以运行了。

 

原创粉丝点击