一个公用的struts2基础action类

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/yanning1314/article/details/25039651
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.opensymphony.xwork2.ActionSupport;

public class BaseAction extends ActionSupport implements ServletRequestAware, ServletResponseAware {
	private static final long serialVersionUID = 5014983309483272188L;

	private HttpServletRequest request;
	private HttpServletResponse response;

	public String resJSON = "{success:%%result%%,msg:{info:\"%%message%%\",session:true}}";

	protected void responseStringStream(String s) { 
		try {
			response.setContentType("text/html;charset=utf-8");
			response.setContentLength((s.getBytes("utf-8")).length);
			response.getWriter().write(s);
			response.flushBuffer();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	/**
	 * 获得项目根目录
	 * 
	 * @return
	 */
	public String getBasePath() {
		return getRequest().getSession().getServletContext().getRealPath("/");
	}

	/**
	 * 获得HttpSession
	 * 
	 * @return
	 */
	public HttpSession getSession() {
		return getRequest().getSession();
	}

	/**
	 * 检查用户Session
	 * 
	 * @return
	 */
	protected boolean checkUserSession() {
		Object obj = getSession().getAttribute("user");
		if (obj == null) {
			return false;
		}
		return true;
	}


	/**
	 * 获取参数
	 * 
	 * @param parameterName
	 * @return
	 */
	protected String getParameter(String parameterName) {
		String parameter = this.request.getParameter(parameterName);
		if (parameter == null) {
			parameter = "";
		}
		return parameter;
	}

	public void setServletRequest(HttpServletRequest request) {
		try{
			request.setCharacterEncoding("utf-8");
		}catch(Exception e){e.printStackTrace();}
		this.request = request;
	}

	public void setServletResponse(HttpServletResponse response) {
		try{
			 response.setCharacterEncoding("utf-8");
			 response.setHeader("Cache-Control","no-cache, no-store, must-revalidate, post-check=0, pre-check=0"); //HTTP 1.1    
			 response.setHeader("Pragma","no-cache"); //HTTP 1.0    
			 response.setDateHeader ("Expires", 0); //prevents caching at the proxy server    
		}catch(Exception e){}
		this.response = response;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

}

展开阅读全文

没有更多推荐了,返回首页