Springle MVC 获得request、response、session对象

1、Action基类

@Controller
public class BaseAction {
	
	private HttpServletRequest request;
	private HttpServletResponse response;
	
	
	public HttpServletRequest getRequest() {
		return request;
	}
	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}
	
	
	public HttpServletResponse getResponse() {
		return response;
	}
	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}
	
	/**
	 * 利用指定的Response对象向网页输出内容
	 * @param value
	 */
	public void outputResponse(String value){
		try {
			PrintWriter out= response.getWriter();
			out.write(value);
			out.flush();
			out.close();
		} catch (IOException e) {
			 e.printStackTrace();
		}
	}
	
	/**
	 * 向页面输出内容 
	 * @param encoding  编码 
	 * @param contentType 格式
	 * @param value 内容
	 * @throws SystemException
	 */
	public void outputResponse(String encoding,String contentType,String value){
		
		try { 
			response.setCharacterEncoding(encoding); 
			response.setContentType(contentType);
			PrintWriter out= response.getWriter();
			out.write(value);
			out.flush();
			out.close();
			
		} catch (IOException e) {
			 e.printStackTrace();
		}
		
	}
	
}
 

 

 

2、Spring MVC拦截器

@Component("springMVCInterceptor")
public class SpringMVCInterceptor extends HandlerInterceptorAdapter {

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		// 获得当前父类的class
		Class baseActionClass = BaseAction.class;
		// 获得当前action的class
		Class newClass = Class.forName(handler.getClass().getName())
				.newInstance().getClass();
		// 判断是否有父子关系
		if (baseActionClass.isAssignableFrom(newClass)) {
			//注入request、response对象
			BaseAction ba = (BaseAction) handler;
			ba.setRequest(request);
			ba.setResponse(response);
		}
		return super.preHandle(request, response, handler);
	}

}

 3、拦截器配置

<!-- baseAction通过拦截注入request、response对象 -->
	<bean
		class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
		<property name="interceptors">
			<list>
				<ref bean="springMVCInterceptor" />
			</list>
		</property>
	</bean>
	<mvc:interceptors>
		<bean id="springMVCInterceptor" class="com.netsdar.zm.action.SpringMVCInterceptor">
	    </bean>
	</mvc:interceptors>
	<!-- baseAction通过拦截注入request、response对象 -->
 

 

你可能感兴趣的:(response)