防XSS注入以及无操作权限返回的BaseController

1.所有的控制器继承这个类 

2.代码

public class BaseController {

    @Autowired
    private UserService userService;

//    @InitBinder
//    public void initBinder(WebDataBinder binder) {
//        /**
//         * 自动转换日期类型的字段格式
//         */
//        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));
//        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
//        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM"), true));
//        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy"), true));
//
//
//        /**
//         * 防止XSS攻击
//         */
//        binder.registerCustomEditor(String.class, new StringEscapeEditor(true, false));
//    }
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        // 使用自定义的 DATE数据绑定类
        binder.registerCustomEditor(Date.class, new DateUtil2());

        /**
         * 防止XSS攻击
         */
        binder.registerCustomEditor(String.class, new StringEscapeEditor(true, false));
    }

    /**
     * 获取当前登录用户对象
     * @return
     */
    public User getCurrentUser() {
        ShiroUser shiroUser= (ShiroUser) SecurityUtils.getSubject().getPrincipal();
        User currentUser = userService.findUserById(shiroUser.id);
        return currentUser;
    }

    /**
     * 获取当前登录用户id
     * @return
     */
    public Long getUserId() {
        return this.getCurrentUser().getId();
    }

    /**
     * 获取当前登录用户名
     * @return
     */
    public String getStaffName() {
        return this.getCurrentUser().getLoginname();
    }

    /**
     *  获取当前用户 性别
     */
    public Integer getUserSex(){
        return this.getCurrentUser().getSex();
    }



    /**
     * 权限异常
     */
    @ExceptionHandler({ UnauthorizedException.class, AuthorizationException.class })
    public Object authorizationException(HttpServletRequest request, HttpServletResponse response) {
        if (WebUtilsPro.isAjaxRequest(request)) {
            // 输出JSON
            Map<String, Object> resp = new HashMap<String, Object>();
            Result result = new Result();
            result.setCode(2);
            result.setMessage("您无此功能权限,请联系开发组长");
            resp.put("result",result);
            writeJson(resp, response);
            return null;
        } else {
            return "redirect:/unAuth";
        }
    }

    /**
     * 输出JSON
     */
    private void writeJson(Map<String, Object> resp, HttpServletResponse response) {
        PrintWriter out = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            out = response.getWriter();
            out.write(JSONArray.toJSONString(resp));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}

3.DateUtil2类代码(日期格式化)

public class DateUtil2 extends PropertyEditorSupport{

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        Date date = null;
        SimpleDateFormat sdf = null;

        try {
            if (Pattern.compile("([GMT]|[gmt])").matcher(text).find()) { //Wed Nov 21 2018 08:00:00 GMT+0800(中国标准时间)
                sdf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss z", Locale.ENGLISH);
                try {
                    text = text.replace("GMT", "").replaceAll("\\(.*\\)", "");
                    date = sdf.parse(text);
                    setValue(date);
                    return;
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            //防止空数据出错
            if(StringUtils.isNotBlank(text)){
                sdf = getSimpleDateFormat(text);
                date = sdf.parse(text);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        setValue(date);
    }
    /**
     *
     *  @Enclosing_Method  : getSimpleDateFormat
     *  @Creation Date     : 2018-11-21 下午12:04:07
     *  @version           : v1.00
     *  @Description       : 使用正在表达式匹配正确的格式
     *
     *  @param source
     *  @return
     *
     */
    private SimpleDateFormat getSimpleDateFormat(String source) {
        SimpleDateFormat sdf = new SimpleDateFormat();
        if (Pattern.matches("^\\d{4}-\\d{2}-\\d{2}$", source)) { // yyyy-MM-dd
            sdf = new SimpleDateFormat("yyyy-MM-dd");
        }else if (Pattern.matches("^\\d{4}-\\d{2}$", source)) { // yyyy-MM
            sdf = new SimpleDateFormat("yyyy-MM");
        }else if (Pattern.matches("^\\d{4}$", source)) { // yyyy
            sdf = new SimpleDateFormat("yyyy");
        } else if (Pattern.matches("^\\d{4}-\\d{2}-\\d{2} \\d{2}-\\d{2}-\\d{2}$", source)) { // yyyy-MM-dd HH-mm-ss
            sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        } else if (Pattern.matches("^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$", source)) { // yyyy-MM-dd HH:mm:ss
            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        } else if (Pattern.matches("^\\d{4}/\\d{2}/\\d{2}$", source)) { // yyyy/MM/dd
            sdf = new SimpleDateFormat("yyyy/MM/dd");
        } else if (Pattern.matches("^\\d{4}/\\d{2}/\\d{2} \\d{2}/\\d{2}/\\d{2}$", source)) { // yyyy/MM/dd HH/mm/ss
            sdf = new SimpleDateFormat("yyyy/MM/dd HH/mm/ss");
        }  else if (Pattern.matches("^\\d{4}\\d{2}\\d{2}$", source)) { // yyyyMMdd
            sdf = new SimpleDateFormat("yyyyMMdd");
        }  else if (Pattern.matches("^\\d{4}\\d{2}\\d{2} \\d{2}\\d{2}\\d{2}$", source)) { // yyyyMMdd HHmmss
            sdf = new SimpleDateFormat("yyyyMMdd HHmmss");
        } else if (Pattern.matches("^\\d{4}\\.\\d{2}\\.\\d{2}$", source)) { // yyyy.MM.dd
            sdf = new SimpleDateFormat("yyyy.MM.dd");
        }  else if (Pattern.matches("^\\d{4}\\.\\d{2}\\.\\d{2} \\d{2}\\.\\d{2}\\.\\d{2}$", source)) { // yyyy.MM.dd HH.mm.ss
            sdf = new SimpleDateFormat("yyyy.MM.dd HH.mm.ss");
        }else{
            System.out.println("TypeMismatchException");
            throw new TypeMismatchException(source, Date.class);
        }
        return sdf;
    }

}

4.StringEscapeEditor类代码

public class StringEscapeEditor extends PropertyEditorSupport {

    private boolean escapeHTML;// 编码HTML
    private boolean escapeJavaScript;// 编码javascript

    public StringEscapeEditor() {
    }

    public StringEscapeEditor(boolean escapeHTML, boolean escapeJavaScript) {
        this.escapeHTML = escapeHTML;
        this.escapeJavaScript = escapeJavaScript;
    }

    @Override
    public String getAsText() {
        Object value = getValue();
        return value != null ? value.toString() : "";
    }

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        if (text == null) {
            setValue(null);
        } else {
            String value = text;
            if (escapeHTML) {
                value = HtmlUtils.htmlEscape(value);
            }
            if (escapeJavaScript) {
                value = JavaScriptUtils.javaScriptEscape(value);
            }
            setValue(value);
        }
    }

}

5.判断是否是ajax请求。WebUtilsPro类

public class WebUtilsPro {

    /**
     * 是否是Ajax请求
     *
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String requestType = request.getHeader("X-Requested-With");
        if ("XMLHttpRequest".equals(requestType)) {
            System.out.println("----------------"+requestType);
            return true;
        } else {
            return false;
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值