JavaWeb之防止XSS攻击

XSS攻击

XSS攻击,言而言之,就是脚本攻击,下面向大家展示一下脚本攻击

使用过滤器来解决XSS攻击
JavaWeb之防止XSS攻击_第1张图片
代码:
1、过滤器

/**
 * 解决XSS攻击的过滤器
 * @author 紫炎易霄
 */
public class XssFilter implements Filter{
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("过滤器的初始化操作");
	}
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		//强转成为HttpServletRequest
		HttpServletRequest req = (HttpServletRequest) request;
		//使用转换器将传过来的脚本转换成HTML文本
		XssWarper xssWarper = new XssWarper(req);
		//放行
		chain.doFilter(xssWarper, response);
	}
	@Override
	public void destroy() {
		System.out.println("过滤器的销毁");
	}
}

2、Warpper

/**
 * 将传过来的值转换成HTML文本
 * @author 紫炎易霄
 */
public class XssWarper extends HttpServletRequestWrapper{
	//定义request的全局变量
	private HttpServletRequest request;
	public XssWarper(HttpServletRequest request) {
		super(request);
		this.request = request;
	}
	@Override
	public String getParameter(String name) {
		String username = request.getParameter(name);
		if(StringUtils.isNotEmpty(username)){
			username = StringEscapeUtils.escapeHtml4(username);
		}
		return username;
	}
}

3、Servlet

/**
 * 处理请求的类
 * @author 紫炎易霄
 */
@WebServlet("/zyyx")
public class XssServlet extends HttpServlet{
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//解决乱码问题
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html;charset=utf-8");
		//接收参数
		String username = req.getParameter("username");
		req.setAttribute("username", username);
		//将参数输出到页面上
		req.getRequestDispatcher("/content.jsp").forward(req, resp);
	}
}

我相信大家能把jsp自己脑补起来。。。不要忘记在web.xml文件中配置过滤器

你可能感兴趣的:(Web开发)