`
dkn28dkn
  • 浏览: 17637 次
最近访客 更多访客>>
社区版块
存档分类
最新评论

jsp编码过滤器的配置和使用-用心做程序-iteye技术网站

 
阅读更多

jsp编码过滤器的配置和使用-用心做程序-iteye技术网站
2011年08月01日
   一、写一个过滤器类 
  package com.test.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; public class CharacterEncodingFilter implements Filter { protected FilterConfig filterConfig = null; protected String encoding = ""; public void destroy() { filterConfig = null; encoding = null; } public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { if (encoding != null) { //设置request和response的编程格式,注意两个都要设,若没设response的 //charset,则在输出页面会显示乱码。 request.setCharacterEncoding(this.encoding); response.setContentType("text/html;charset=utf-8") ; } //继续执行下一个过滤器 filterChain.doFilter(request, response); } public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; this.encoding = filterConfig.getInitParameter("encoding"); } } 
  二、在web.xml中配置该过滤器的使用,加入下面配置代码: 
   CharacterEncodingFilter com.test.filter.CharacterEncodingFilte r  encoding utf-8    CharacterEncodingFilter /*  
  三、写JSP和Servlet进行测试 
  JSP: 
       ">     filterTest    username:
password:
     
  Servlet: 
  package com.test.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class LoginServlet extends HttpServlet { public LoginServlet() { super(); } public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //页面转发,留意这里并没有对request和response的编码格式进行设置,如果没有 //编码过滤器,则会在跳到的页面中无法显示中文 this.getServletContext().getRequestDispatcher("/re sultLogin.jsp").forward(request, response); } public void init() throws ServletException { // Put your code here } } 
  输出页面JSP: 
    My JSP 'resultLogin.jsp' starting page   username::
password::   
  
  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics