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::
  
  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值