How to get the HttpServletRequest in Struts 2

来源:互联网 发布:java斗牛算法 编辑:程序博客网 时间:2024/06/05 15:22

In Struts 2 , you can use the following two methods to get the HttpServletRequest object.

1. ServletActionContext

Get the HttpServletRequest object directly from org.apache.struts2.ServletActionContext.

import javax.servlet.http.HttpServletRequest;import org.apache.struts2.ServletActionContext; public class LocaleAction{//business logicpublic String execute() {HttpServletRequest request = ServletActionContext.getRequest();return "SUCCESS";}}

2. ServletRequestAware

Make your class implements the org.apache.struts2.interceptor.ServletRequestAware.

When Struts 2 ‘servlet-config‘ interceptor is seeing that an Action class is implemented theServletRequestAware interface, it will pass a HttpServletRequest reference to the requested Action class via thesetServletRequest() method.

import javax.servlet.http.HttpServletRequest;import org.apache.struts2.interceptor.ServletRequestAware; public class LocaleAction implements ServletRequestAware{ HttpServletRequest request; //business logicpublic String execute() {String param = getServletRequest().getParameter("param");return "SUCCESS"; } public void setServletRequest(HttpServletRequest request) {this.request = request;} public HttpServletRequest getServletRequest() {return this.request;}}

Struts 2 documentation is recommended ServletRequestAware instead ofServletActionContext.

Reference

  1. http://struts.apache.org/2.x/docs/how-can-we-access-the-httpservletrequest.html
  2. http://struts.apache.org/2.0.6/struts2-core/apidocs/org/apache/struts2/interceptor/ServletRequestAware.html
转自:http://www.mkyong.com/struts2/how-to-get-the-httpservletrequest-in-struts-2/

原创粉丝点击