现在的位置: 首页 > 综合 > 正文

How to get the HttpServletRequest in Struts 2

2013年08月18日 ⁄ 综合 ⁄ 共 1494字 ⁄ 字号 评论关闭

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 logic
	public 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 the
ServletRequestAware interface, it will pass a HttpServletRequest reference to the requested Action class via the
setServletRequest() method.

import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ServletRequestAware;
 
public class LocaleAction implements ServletRequestAware{
 
	HttpServletRequest request;
 
	//business logic
	public 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 of
ServletActionContext.

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/

抱歉!评论已关闭.