spring 拦截器封装值传到controller的问题

Ta曰丿、她活 2019-01-22 10:23:35
现在我有个拦截器,连接前台的请求,并封装参数。然后我想在在各个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的方式去获取封装的值。请问怎么解决这个问题?
...全文
1488 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_33641175 2021-05-19
  • 打赏
  • 举报
回复
搞定了没, 我也想这么干, 也是取不到值
亲爱的Joe 2019-01-27
  • 打赏
  • 举报
回复
既然有报错,那就把报错发出来看下吧
Ta曰丿、她活 2019-01-26
  • 打赏
  • 举报
回复
引用 4 楼 www.alphaos.club 的回复:
不用写RequestAttribute

能说具体一点吗? 不用写是什么意思?
podd 2019-01-25
  • 打赏
  • 举报
回复
不用写RequestAttribute
_loehuang_ 2019-01-25
  • 打赏
  • 举报
回复
HandlerMethodArgumentResolver
Ta曰丿、她活 2019-01-24
  • 打赏
  • 举报
回复
没人??? 求助啊。。。
哈希塞特 2019-01-24
  • 打赏
  • 举报
回复
真是画蛇添足

81,090

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧