目标:使用Struts2作为控制器,写一个demo处理请求。
/hello.action-->StrutsPrepareAndExecuteFilter-->Action -->Result-->/hello.jsp
- 搭建Struts2环境:在maven工程中添加jar包定义
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.5.13</version>
</dependency>
- 实现过程
<filter>
<filter-name>strutsmvc</filter-name>
<filter-class>
org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter
</filter-class>
<!-- 默认加载struts.xml配置文件 -->
</filter>
<filter-mapping>
<filter-name>strutsmvc</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
2.
引入struts.xml文件(处理具体请求)
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
</struts>
3. 编写Action和jsp
public class HelloAction {
//方法名默认execute,无参
public String execute(){
System.out.println("执行HelloAction处理");
return "success";//与<result name="success">定义的name属性一致
}
}
4. 在struts.xml中添加处理具体请求的配置
<!-- 必须继承struts-default,否则不能使用Result -->
<package name="demo1" extends="struts-default">
<!-- name指定请求名、class指定Action类名、method指定Action方法名 -->
<action name="hello" class="cn.xdl.action.HelloAction" method="execute">
<!--name指定Action方法返回值、type指定Result组件类型 -->
<result name="success" type="dispatcher">/hello.jsp</result>
</action>
</package>
补充:
- 通过属性接收页面传值和向页面传值
- 更改默认的.action扩展名;在struts.xml中定义
<constant name="struts.action.extension" value="do,,"/>
- 获取使用request、session、application等对象
- 通过ActionContext对象获取,返回Map类型对象(Struts2提供了RequestMap、SessionMap、ApplicationMap封装,封装了Servlet中的HttpServletRequest、HttpSession、ServletContext)
ActionContext ac = ActionContext.getContext();
Map<String,Object> sessionMap = ac.getSession();
sessionMap.put("user", username);
2. 通过ServletActionContext对象获取原有Servlet类型
HttpServletRequest httpRequest = ServletActionContext.getRequest();
HttpSession httpSession = httpRequest.getSession();
httpSession.setAttribute("user", username);
3. 使用Aware接口注入对象
public class BaseAction implements SessionAware,RequestAware,ApplicationAware
,ServletRequestAware,ServletResponseAware,ServletContextAware{
Map<String,Object> session;
Map<String,Object> request;
Map<String,Object> application;
HttpServletRequest httpRequest;
HttpServletResponse response;
ServletContext httpApplication;
//创建Action对象时会自动执行setSession
public void setSession(Map<String, Object> session) {
this.session = session;
}
public void setRequest(Map<String, Object> request) {
this.request = request;
}
public void setApplication(Map<String, Object> application) {
this.application = application;
}
public void setServletRequest(HttpServletRequest request) {
this.httpRequest = request;
}
public void setServletResponse(HttpServletResponse response) {
this.response = response;
}
public void setServletContext(ServletContext context) {
this.httpApplication = context;
}
}