本文共 2424 字,大约阅读时间需要 8 分钟。
在Struts2开发中,除了将请求参数自动设置到Action的字段中,我们还需要在Action中直接获取请求(Request)或会话(Session)的一些信息,甚至需要对JavaServlet Http的请求(HttpServletRequest)和响应(HttpServletResponse)进行操作。以下是获取request、response和session的详细说明。
在Struts2中,ActionContext是一个非常重要的概念。它可以看作是一个容器,存储了Action执行时所需的各种对象。最常用的方式是通过以下代码获取ActionContext:
ActionContext context = ActionContext.getContext();Map params = context.getParameters();String username = (String) params.get("username"); ActionContext通过ThreadLocal实现了线程安全,每个线程都会有自己的独立副本,避免了多线程环境下的数据冲突。
ServletActionContext是ActionContext的扩展版本,直接继承了它,并提供了与Servlet相关的对象访问功能。其常见用途包括:
获取HttpServletRequest对象:
HttpServletRequest request = ServletActionContext.getRequest();
获取HttpSession对象:
HttpSession session = ServletActionContext.getRequest().getSession();
在实际开发中,ActionContext和ServletActionContext的功能有一定的重叠。建议优先使用ActionContext,如果它能够满足需求,则无需使用ServletActionContext。以下原则可以帮助我们做出选择:
ActionContext ctx = ActionContext.getContext();ctx.put("liuwei", "andy"); // 等同于request.setAttribute("liuwei", "andy");Map session = ctx.getSession(); // 获取session对象HttpServletRequest request = ctx.get(StrutsStatics.HTTP_REQUEST);HttpServletResponse response = ctx.get(StrutsStatics.HTTP_RESPONSE); public class UserAction extends ActionSupport { // 不推荐直接在类中声明request private HttpServletRequest req; public String login() { req = ServletActionContext.getRequest(); // 业务逻辑... req.getSession().setAttribute("user", user); return SUCCESS; }} 如果需要使用IoC,可以实现相应的Aware接口:
public class UserAction extends ActionSupport implements SessionAware, ServletRequestAware, ServletResponseAware { private HttpServletRequest request; private HttpServletResponse response; public void setServletRequest(HttpServletRequest request) { this.request = request; } public void setServletResponse(HttpServletResponse response) { this.response = response; } public String execute() { HttpSession session = request.getSession(); return SUCCESS; }} 通过上述方式,我们可以在不同的场景中灵活获取request、response和session对象,确保代码的可维护性和可扩展性。
转载地址:http://hoqfk.baihongyu.com/