struts框架可以提供对前端请求的封装和重定向,提高开发效率,对程序代码进行解耦
使用struts2的步骤.
1首先引入struts2核心包,
2在web,xml中配置filter
struts2
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
struts2
/*
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;
}
}
}