Struts 2 下載與安裝######
- 在 struts.apache.org 下載Struts 2
- 將Struts 2的lib文件夾下的.jar文件復制到應用的WEB-INF/lib目錄下
- 在web.xml中配置Struts 2的核心Filter
<web-app>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts.dispatcher.ng.filter.StrutsPreparaAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
- 解壓Struts 2中app目錄下的struts2-blank.war,在WEB-INF/classes中找到struts.xml,將其復制到web應用的src目錄下(編譯后會自動復制到classes目錄下)
經(jīng)過以上步驟,已經(jīng)可以使用Struts 2的基本功能了,下面做一個簡單登陸驗證demo
/*
*登錄頁面 loginForm.jsp
*其中<s:xxxx>是Struts 2提供的標簽庫,先不管,后面再細看
*/
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>loginForm</title>
</head>
<body>
<s:form action="login">
<s:textfield name="username" key="uesr"/>
<s:testfield name="password" key="pass"/>
<s:submit key="login"/>
</s:form>
</body>
</html>
登陸成功后跳轉(zhuǎn)到welcom.jsp
略...
登陸失敗跳轉(zhuǎn)到error.jsp
略...
在struts.xml中添加兩個<constant>元素用于加載國際化資源文件(shenmegui?)
<struts>
<constant name="struts.custom.il8n.resourrces" value="mess"/>
<constant name="struts.enable.DynamicMethodInvocation" value="false"/>
</struts>
上面第一個<constan/>用到的mess.properties配置文件如下
loginPage=登錄頁面
errorpage=錯誤頁面
succPage=成功頁面
failTip=登陸失敗,蛋疼!
succTip={0},歡迎回來!
user=用戶名
pass=密碼
login=登錄
在struts.xml中添加一個name="*"的action,收到請求后將直接呈現(xiàn)WEB-INF/content下的同名JSP頁面
<struts>
<package name=”crazyit" namespace="/" extends="struts-default">
<action name="*">
<result>/WEB-INF/content/{1}.jsp</result>
</action>
</package>
</struts>
前面loginForm.jsp中表單指定的action為login,因此需定義一個Struts 2的Action,繼承ActionSupport基類
/*
*LoginAction.java
*一個Action,用于接收登錄請求并返回SUCCESS或ERROR狀態(tài)
*/
public class LoginAction extends ActionSupport {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
//定義處理用戶請求的exexute方法
public String exexute(){
//當username為zhaosi,password為666666時,登錄成功
if (getUsername().equals("zhaosi") && getPassword().equals("666666")){
ActionContext.getContext().getSession().put("user",getUsername());
return SUCCESS;
}
return ERROR;
}
}
在struts.xml中添加name="login"的<action>,當上面的Action返回SUCCESS或ERROR后,將用戶導向?qū)腏SP頁面
<struts>
<constant name="struts.custom.il8n.resourrces" value="mess"/>
<constant name="struts.enable.DynamicMethodInvocation" value="false"/>
<package name="crazyit" namespace="/" extends="struts-default">
<action name="*">
<result>/WEB-INF/content/{1}.jsp</result>
</action>
<action name="login" class="LoginAction">
<result name="error">/WEB-INF/content/error.jsp</result>
<result name="success">/WEB-INF/content/welcome.jsp</result>
</action>
</package>
</struts>