利用@Webfilter过滤敏感文字

  • 编写过滤器类
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;

import java.io.IOException;


@WebFilter(filterName = "WordFilter",urlPatterns = "/MessageServlet",initParams ={
        @WebInitParam(name="encoding",value = "UTF-8")
} )
public class WordFilter implements Filter {
    // 非法字符数组
    private String words[];
    // 字符编码
    private String encoding;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //获取字符编码
         encoding = filterConfig.getInitParameter("encoding");
         //初始化非法字符数组
        words= new String[]{"糟糕","混蛋"};

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 判断字符编码是否有效
        if (encoding != null){
            // 设置request字符编码
            request.setCharacterEncoding(encoding);
            //将request转换为重写后的Request对象
            request= new Request((HttpServletRequest) request);
            //设置response字符编码
            response.setContentType("text/html;charset="+encoding);

        }chain.doFilter(request,response);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
        this.words = null;
        this.encoding = null;
    }

    class Request extends HttpServletRequestWrapper{

        public Request(HttpServletRequest request) {
            super(request);
        }
        
        //重写getParameer()方法
        @Override
        public String getParameter(String name) {
            return filter(super.getParameter(name));
        }

        /*@Override
        public String[] getParameterValues(String name) {
            //获取所有参数值
            String[] values = super.getParameterValues(name);
            // 通过循环对所有参数值进行过滤
            for (int i = 0; i < values.length; i++) {
                values[i] = filter(values[i]);
            }
            //返回过滤后的参数值
            return values;
        }*/
    }

    public String filter(String param){
        try{
            //判断非法字符是否被初始化
            if (words != null && words.length > 0){
                // 循环替换非法字符
                for (int i = 0; i < words.length; i++) {
                    //判断是否包含非法字符
                    if (param.indexOf(words[i])!=-1){
                        //将非法字符替换为"****"
                        param = param.replaceAll(words[i], "****");
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return param;
    }
}
  • 编写servlet
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "MessageServlet",urlPatterns = "/MessageServlet")
public class MessageServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取标题
        String title = req.getParameter("title");
        // 获取内容
        String content = req.getParameter("content");
        // 将标题放置到request中
        req.setAttribute("title", title);
        // 将内容放置到request中
        req.setAttribute("content", content);
        //转发到result.jsp页面
        req.getRequestDispatcher("wordFilter.jsp").forward(req,resp);
    }

}
  • 编写测试的jsp页面
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2024/4/24
  Time: 9:45
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>意见反馈</title>
    <style type="text/css">
        body {
            margin: 0px;
            font-size: 12px;
        }
        td{
            font-size: 12px;
        }
        .div1{
            width: 1003px;
            height: 707px;
            background-image: url("images/bg.jpg");
        }
        .div2{
            width: 500px;
            margin-top:245px;
            margin-left:180px;
            text-align:left;
        }
        .tl{
            width: 500px;
            height: 20px;
            font-weight: bold;
            background: #A3C0C6;
            padding: 5px;
        }
        .ct{
            width: 500px;
            padding-left: 30px;
            padding-top: 5px;
            padding-bottom: 5px;
        }
        .tt{
            margin-left:5px;
            width: 70px;
            background: #A3C0C6;
            padding: 5px;
            font-weight: bold;
            font-size: 13px;
        }
    </style>
</head>

<body>
<div align="center">
    <div class="div1">
        <div class="div2">
            <%
                String title = (String) request.getAttribute("title");
                String content = (String)request.getAttribute("content");
                if(title != null && !title.isEmpty()){
                    out.println("<span class='tl'>" + title + "</span>");
                }
                if(content != null && !content.isEmpty()){
                    out.println("<span class='ct'>" + content + "</span>");
                }
            %>
            <span class="tl">谢谢你们</span>
            <span class="ct">你们的公司服务态度非常好,谢谢你们!</span>
            <span class="tl">谢谢你们</span>
            <span class="ct">你们的公司服务态度非常好<br>但部分客服服务态度还要加强!</span>
            <form action="MessageServlet" method="post">
                <span class="tt">意见反馈</span>
                <table border="0" width="500" align="center">
                    <tr>
                        <td align="right">标 题:</td>
                        <td><input type="text" name="title" size="30"></td>
                    </tr>
                    <tr>
                        <td align="right">内 容:</td>
                        <td>
                            <textarea rows="5" cols="40" name="content"></textarea>
                        </td>
                    </tr>
                    <tr>
                        <td align="center" colspan="2">
                            <input type="submit" value="提 交">
                        </td>
                    </tr>
                </table>
            </form>
        </div>
    </div>
</div>

</body>
</html>
posted @ 2024-04-24 16:45  文采杰出  阅读(78)  评论(0)    收藏  举报