Struts2访问servlet分享

时间:2021-05-26

一:访问或添加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;

}

}

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章