javaweb 实现对文本内容的“加密”处理

论坛 期权论坛 脚本     
匿名技术用户   2020-12-22 03:23   34   0

我们经常会在网上发表各种言论,但是如果系统发现了自己发的文本中的出现了不文明的言论就会把自己的文本进行加密处理,也就是改成***。下面,我就来简单说一说javaweb的textarea中实现一个简易的“加密”处理。

1.创建一个文本输入表单

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
     <form action="bbs.jsp" method="post">
          <textarea rows="5" cols="30" name="text"></textarea>
          <input type="submit" value="提交"/>
     </form>
</body>
</html>

2.创建一个Servlet

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class MyHttpServlet extends HttpServletRequestWrapper {

 public MyHttpServlet(HttpServletRequest request) {
  super(request);
 }

    public String getParameter(String name) {
     String val=super.getParameter(name);
     if(val!=null&&val.contains(" fuck ")) {
      val=val.replaceAll("fuck", "****");
     }
     return val;
    }
 
    
}

这里主要继承的是HttpServletRequestWrapper这个类。

HttpServletRequestWrapper:继承了ServletRequestWrapper类和HttpServletRequest接口,所以它具备了大部分的request中的方法。可以通过继承它来实现一个功能强大的拦截模式。

3.设置过滤器

 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  //1.获取请求参数的值
  String context=request.getParameter("txet");
  
  
  //2.把其中fuck,shit等字符串替换为****
  HttpServletRequest req=new MyHttpServlet((HttpServletRequest)request);
  //3.转到目标界面
  chain.doFilter(req, response);
 }
    private FilterConfig filterconfig;
 /**
  * @see Filter#init(FilterConfig)
  */
 public void init(FilterConfig fConfig) throws ServletException {
  this.filterconfig=fConfig;// TODO Auto-generated method stub
 }

用当前的request对象作为参数创建一个HttpServletRequest对象,同时通过doFilter()方法把HttpServletRequest对象作为一个新的request对象到目标界面。

4.创建一个简单获取文本内容并输出的网页


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    content:${param.text}
</body>
</html>

${param.text}实际调用的是MyHttpServlet类中的getParameter方法,他会先获取表单中传过来的文本内容,然后把文本中所有不合法的字符全部替换成***,然后返回替换后的内容,输出到页面上。

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP