Struts2访问servlet分享
一:访问或添加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:
<body>
${applicationscope.app} <br>
${sessionscope.ses}<br>
${requestscope.req}<br>
</body>
二:获取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;
}
}