问题描述:

springboot项目 HttpServletRequest getRequest().getInputStream()或getReader()只能读取一次read closed

问题分析:

在前端发送数据给后端时是使用ajax传输的JSON.stringify(json)的json 字符串化数据

// An highlighted block
var json = {a:1};
var jsonStr = JSON.stringify(json);
//jsonStr转化为
var jsonStr2 = '{"a":1}'; 

我在项目中使用controller中方法进行接收数据的时候需要加上@RequestBody注解接收这种数据,使用POJO对象进行接收,
但是我的项目需要为这个方法增加LogAspect的功能,这就要求我需要获取到RequestBody中的数据,但是一个request数据只能读取一次,在方法内部已经读取过了,不能在LogAspect中再次读取
(试过Filter的方法,但是会对原项目中的Filter有冲突)

问题解决:

在Controller的方法中增加参数HttpServletRequest request,使用request.setAttribute()将对象重新放入到request中,在Aspect中使用getAttribute()进行获取就可以避免getInputStream()这个方法出bug了

//Controller方法
@Log(title = "社团职务管理", businessType = BusinessType.DELETE)
    @RequiresPermissions("system:user:dept:remove")
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(@RequestBody DTO dto, HttpServletRequest request) {
        //@RequestParam(value = "ids")String ids,@RequestParam(value = "list")List<SysUserDept> list
        System.out.println("getIds:"+dto.getIds());
        request.setAttribute("dto",dto);
   
        return toAjax(userDeptService.deleteUserDeptByIds(dto.getIds()));
    }
//LogAspect中的方法
/**
     * 获取请求的参数,放到log中
     * 
     * @param operLog 操作日志
     * @throws Exception 异常
     */
    private void setRequestValue(SysOperLog operLog) throws Exception
    {
        Map<String, String[]> map = ServletUtils.getRequest().getParameterMap();
        if (StringUtils.isNotEmpty(map))
        {
            PropertyPreFilters.MySimplePropertyPreFilter excludefilter = new PropertyPreFilters().addFilter();
            excludefilter.addExcludes(EXCLUDE_PROPERTIES);
            String params = JSONObject.toJSONString(map, excludefilter);
            operLog.setOperParam(StringUtils.substring(params, 0, 2000));
        }else{
            DTO dto = (DTO) ServletUtils.getRequestAttributes().getAttribute("dto",0);
            //String sb = HttpContextUtils.getBodyString(ServletUtils.getRequest());
            PropertyPreFilters.MySimplePropertyPreFilter excludefilter = new PropertyPreFilters().addFilter();
            excludefilter.addExcludes(EXCLUDE_PROPERTIES);
            String params = JSONObject.toJSONString(dto, excludefilter);
            operLog.setOperParam(StringUtils.substring(params, 0, 2000));

        }

    }

//DTO

public class DTO implements Serializable {
    private static final long serialVersionUID = 1L;
    private List<?> list;
    private String ids;

    public List<?> getList() {

        return list;
    }

    public void setList(List<?> list) {
        this.list = list;
    }

    public String getIds() {
        return ids;
    }

    public void setIds(String ids) {
        this.ids = ids;
    }

    @Override
    public String toString() {
        return "{" +
                "list=" + list +
                ", ids='" + ids + '\'' +
                '}';
    }
}


点击阅读全文
Logo

快速构建 Web 应用程序

更多推荐