spring 拦截器封装值传到controller的问题
现在我有个拦截器,连接前台的请求,并封装参数。然后我想在在各个controller的方法里面通过@RequestAttribute拿到这个封装的值。但是拿不到。代码如下
拦截器写法:
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
// TODO Auto-generated method stub
// log.info("****************************preHandle****************************");
// 记录请求开始时间
startTime = System.currentTimeMillis();
// 前台页面请求参数JSON化
JSONObject json = new JSONObject();
Map<String, String[]> map = request.getParameterMap();
for (Map.Entry<String, String[]> me : map.entrySet()) {
json.put(me.getKey(), (me.getValue().length > 0 ? me.getValue()[0] : null));
}
log.debug("######Params:" + json.toString());
// 如何将这个封装的数据转发到各个方法呢???
request.setAttribute("pData", json);
return true;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView arg3) throws Exception {
// TODO Auto-generated method stub
// log.info("****************************postHandle****************************");
}
/**
* 请求之后,打印每条请求花费的时间
*/
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception arg3) throws Exception {
// TODO Auto-generated method stub
endTime = System.currentTimeMillis(); // 记录请求结束时间
// 计算请求消耗时间
log.debug("######RequestUrl:" + request.getRequestURL());
log.debug("######Finished TIME:" + ((endTime - startTime) / 1000f) + "s");
// log.info("****************************afterCompletion****************************");
}
controller写法:
@ResponseBody
@RequestMapping("/accreditLogin")
public void accreditLogin(HttpServletRequest request, HttpServletResponse response,
@RequestAttribute(value = "pData", required = true) JSONObject pData) throws Exception {
// log.info("pData:" + pData.toString());
// Object pData1 = request.getAttribute("pData");
log.info("pData:"+pData.toString);
。。。
JSONObject json = new JSONObject();
json.put("errCode", errCode);
response.getWriter().write(json.toString());
}
【1】我将@RequestAttribute下载方法上,运行程序报错。 拦截器封装的数据包和controller用的包时同一个。
【2】我在方法里面通过request.getAttribute("pData");方式获取拦截器封装的值是可以拿到的。但是不想那样做。
只想通过@RequestAttribute的方式去获取封装的值。请问怎么解决这个问题?