用@WebServlet和@WebFilter注解实现字符编码过滤器

效果图:
用@WebServlet和@WebFilter注解实现字符编码过滤器_第1张图片
用@WebServlet和@WebFilter注解实现字符编码过滤器_第2张图片

代码:
index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <form action="AddServlet" method="post">
    <table>
      <tr>
        <td>图书名称</td>
        <td><input type="text" name="name"></td>
      </tr>
      <tr>
        <td>图书作者</td>
        <td><input type="text" name="author"></td>
      </tr>
      <td><input type="submit" value="添加"></td>
    </table>
  </form>
  </body>
</html>

src目录下:
cn.test.AddServlet.java:

package cn.test;


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;
import java.io.PrintWriter;

@WebServlet("/AddServlet")
public class AddServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        String author = req.getParameter("author");

        PrintWriter out = resp.getWriter();
        out.print("

图书添加成功


"
); out.print("图书名称:"+name+"
"
); out.print("图书作者:"+author+"
"
); out.flush(); out.close(); } }

cn.test.CharactorFilter.java:

package cn.test;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import java.io.IOException;

@WebFilter(filterName = "CharactorFilter", urlPatterns = {"/*"}, initParams = {@WebInitParam(name = "encoding", value = "UTF-8")})
public class CharactorFilter implements Filter {

    String encoding = null;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        encoding = filterConfig.getInitParameter("encoding");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (encoding != null){
            //设置request的编码格式
            servletRequest.setCharacterEncoding(encoding);
            //设置response字符编码
            servletResponse.setContentType("text/html; charset="+encoding);
        }

        //传递给下一过滤器
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        encoding = null;
    }
}

你可能感兴趣的:(JSP)