struts2 用action操作域对象
2018-05-08 本文已影响0人
DouDouZH
- 操作request,session,ServletContext 对象
- 用ServletActionContext 操作
1、代码
Action.java
package work.doudou.Action;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class action extends ActionSupport{
@Override
public String execute() throws Exception {
//1.操作request域
HttpServletRequest request=ServletActionContext.getRequest();
request.setAttribute("request", "request");
//2.操作session
HttpSession session=request.getSession();
session.setAttribute("session", "session");
//3.操作ServletContext域
ServletContext context=ServletActionContext.getServletContext();
context.setAttribute("context", "context");
String aa=(String)request.getAttribute("request");
String bb=(String)session.getAttribute("session");
String cc=(String)context.getAttribute("context");
System.out.println(aa+" "+bb+" "+cc);
return "ok";
}
}
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
<action name="action" class="work.doudou.Action.action" method="execute">
<result name="ok" type="dispatcher">/index.jsp</result>
</action>
</package>
</struts>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>abc</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
2、运行结果
控制台
image.png
浏览器显示结果
image.png