以下用登入功能,實現一個最簡單的 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就可以運行了。