1、访问或添加request/session/application属性
public String scope() throws Exception{
ActionContext ctx = ActionContext.getContext();
ctx.getApplication().put("app", "应用范围");//往ServletContext里放入app
ctx.getSession().put("ses", "session范围");//往session里放入ses
ctx.put("req", "request范围");//往request里放入req
return "scope";
}
JSP:
${applicationScope.app}
${sessionScope.ses}
${requestScope.req}
2、获取HttpServletRequest/HttpSession/ServletContext/HttpServletResponse对象
方法一、通过ServletActionContext类直接获取:
public String rsa() throws Exception{
HttpServletRequest request = ServletActionContext.getRequest();
ServletContext servletContext = ServletActionContext.getServletContext();
request.getSession();
HttpServletResponse response = ServletActionContext.getResponse();
return "scope";
}
方法二、实现指定接口,由struts框架运行时注入:
public class HelloWorldAction implements ServletRequestAware, ServletResponseAware, ServletContextAware{
private HttpServletRequest request;
private ServletContext servletContext;
private HttpServletResponse response;
public void setServletRequest(HttpServletRequest req) {
this.request=req;
}
public void setServletResponse(HttpServletResponse res) {
this.response=res;
}
public void setServletContext(ServletContext ser) {
this.servletContext=ser;
}
}
代码
package
com.ljq.action;
import
java.util.Arrays;
import
javax.servlet.ServletContext;
import
javax.servlet.http.HttpServletRequest;
import
org.apache.struts2.ServletActionContext;
import
com.opensymphony.xwork2.ActionContext;
public
class
HelloWorldAction {
//
在页面中采用以下el表达式输出
//
第一种
//
${applicationScope.app}
//
${sessionScope.ses}
//
${requestScope.req}
//
第二种
//
${app}
//
${ses}
//
${req}
public
String list() {
ActionContext ctx
=
ActionContext.getContext();
ctx.getApplication().put(
"
app
"
,
"
应用范围
"
);
//
往ServletContext里放入application
ctx.getSession().put(
"
ses
"
,
"
session范围
"
);
//
往session里放入session
ctx.put(
"
req
"
,
"
request范围
"
);
//
往request里放入request
ctx.put(
"
names
"
, Arrays.asList(
"
张三
"
,
"
李四
"
,
"
王五
"
));
return
"
message
"
;
}
//
在页面中采用以下el表达式输出
//
第一种
//
${applicationScope.app}
//
${sessionScope.ses}
//
${requestScope.req}
//
第二种
//
${app}
//
${ses}
//
${req}
public
String get()
throws
Exception {
HttpServletRequest request
=
ServletActionContext.getRequest();
ServletContext servletContext
=
ServletActionContext.getServletContext();
request.setAttribute(
"
req
"
,
"
请求范围属性
"
);
request.getSession().setAttribute(
"
ses
"
,
"
会话范围属性
"
);
servletContext.setAttribute(
"
app
"
,
"
应用范围属性
"
);
//
HttpServletResponse response = ServletActionContext.getResponse();
return
"
message
"
;
}
}
jsp代码
${applicationScope.app}
<
br
>
${sessionScope.ses}
<
br
>
${requestScope.req}
<
br
>
===========<
br
/>
${app}
<
br
>
${ses}
<
br
>
${req}
<
br
>
===========<
br
/>
<
c:forEach items
=
"
${names}
"
var
=
"
name
"
>
${name }
<
br
/>
c:forEach
>
点击链接加入群【农产品一体化解决方案】:https://jq.qq.com/?_wv=1027&k=49BAREK