码迷,mamicode.com
首页 > Web开发 > 详细

jsp过滤器之encoding字符编码过滤器

时间:2015-11-29 16:26:28      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

一、创建两个jsp页面:a.jsp和b.jsp。

1、a.jsp

1 <!-- 登陆表单 -->
2 <form action="CheckLoginServlet.do" method="post">
3     <input type="text" name="username">
4     <input type="password" name="password" />
5     <input type="submit" value="submit">
6 </form>

2、b.jsp

1 <!-- 登录成功,打印欢迎信息 -->
2 ${requestScope.username }    欢迎您。。。。。。

二、创建用于进行登录判断的Servlet:CheckLoginServlet.js

 1 import java.io.IOException;
 2 import javax.servlet.ServletException;
 3 import javax.servlet.annotation.WebServlet;
 4 import javax.servlet.http.HttpServlet;
 5 import javax.servlet.http.HttpServletRequest;
 6 import javax.servlet.http.HttpServletResponse;
 7 
 8 @WebServlet("/CheckLoginServlet.do")
 9 public class CheckLoginServlet extends HttpServlet {
10     private static final long serialVersionUID = 1L;
11     
12     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
13         /**
14          * 登录验证:如果用户名和密码相同,跳转到b.jsp页面。否则跳回到a.jsp页面重新登录。
15          */
16         String name = request.getParameter("username");
17         String password = request.getParameter("password");
18         if(name.equals(password) && name.trim()!="" && password.trim()!=""){
19             request.setAttribute("username", name);
20             request.getRequestDispatcher("b.jsp").forward(request, response);
21             return;
22         }else{
23             response.sendRedirect("a.jsp");
24         }
25     }
26 }

三、在web.xml文件中配置初始化参数encoding,值为utf-8。

<context-param>
    <param-name>encoding</param-name>
    <param-value>utf-8</param-value>
</context-param>

四、编写字符编码过滤器:EncodingFilter.java,过滤根目录下所有的文件。

 1 import java.io.IOException;
 2 import javax.servlet.Filter;
 3 import javax.servlet.FilterChain;
 4 import javax.servlet.FilterConfig;
 5 import javax.servlet.ServletException;
 6 import javax.servlet.ServletRequest;
 7 import javax.servlet.ServletResponse;
 8 import javax.servlet.annotation.WebFilter;
 9 
10 @WebFilter("/*")
11 public class EncodingFilter implements Filter {
12     
13     private String encoding;
14     
15     public EncodingFilter() {}
16 
17     public void init(FilterConfig fConfig) throws ServletException {
18         encoding = fConfig.getServletContext().getInitParameter("encoding");
19     }
20 
21     public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
22         request.setCharacterEncoding(encoding);
23         chain.doFilter(request, response);
24     }
25 
26     public void destroy() {}
27 
28 }

五、完成。。。。。。

jsp过滤器之encoding字符编码过滤器

标签:

原文地址:http://www.cnblogs.com/chulei926/p/5004772.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!