struts框架可以提供對前端請求的封裝和重定向,提高開發效率,對程序代碼進行解耦
使用struts2的步驟.
1首先引入struts2核心包,
2在web,xml中配置filter
<?xml version="1.0" encoding="UTF-8"?>
struts2org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilterstruts2/*index.jsp
<url-pattern>/*</url-pattern>表示攔截所有請求。
在src根目錄下添加strutsx.ml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!-- 指定全局國際化資源文件 -->
<constant name="struts.custom.i18n.resources" value="mess" />
<!-- 指定全局字符集 -->
<constant name="struts.i18n.encoding" value="utf-8"></constant>
<!-- 創建package包,繼承struts 命名空間爲根路徑 -->
<package name="struts2" namespace="/" extends="struts-default">
<!-- 創建loginaction 使用actiong.LoginActiong文件 返回結果success 歡迎頁面 erro 錯誤頁面 input輸入頁面 -->
<action name="login" class="action.LogionAction">
<result name="error">/error.jsp</result>
<result name="input">/login.jsp</result>
<result name="success">/welcome.jsp</result>
</action>
<action name="sum" class="action.FirstAction">
<result name="positive">/positive.jsp</result>
<result name="negative">/negative.jsp</result>
</action>
</package>
<!-- 引入其他struts配置文件 -->
<include file="moresubmit.xml"></include>
<include file="validate.xml"></include>
</struts>
3創建actiong/LoginAction文件。
package action;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletResponseAware;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
public class LogionAction implements Action, ServletResponseAware{
private static final String SUCCESS = "success";
private static final String ERROR = "error";
private String username;
private String password;
private String tip;
private HttpServletResponse response;
public void setServletResponse(HttpServletResponse response) {
this.response = response;
}
public String getTip() {
return tip;
}
public void setTip(String tip) {
this.tip = tip;
}
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;
}
public String execute() throws Exception {
ActionContext ctx = ActionContext.getContext();
Integer counter = (Integer) ctx.getApplication().get("counter");
if (counter == null) {
counter = 1;
} else {
counter += 1;
}
ctx.getApplication().put("counter", counter);
ctx.getSession().put("user", getUsername());
if (getUsername().equals("admin") && getPassword().equals("admin")) {
Cookie c = new Cookie("user", getUsername());
c.setMaxAge(60 * 60);
ServletActionContext.getResponse().addCookie(c);
// response.addCookie(c);
ctx.put("tip", "login success");
return SUCCESS;
} else {
ctx.put("tip", "login failed");
return ERROR;
}
}
}