servlet中的字符编码过滤器的使用

一:简介

Servlet过滤器是客户端和目标资源的中间层组件,主要是用于拦截客户端的请求和响应信息。如当web容器收到一条客户端发来的请求

web容器判断该请求是否与过滤器相关联,如果相关联就交给过滤器进行处理,处理完可以交给下一个过滤器或者其他业务,当其他业务完成

需要对客户端进行相应的时候,容器又将相应交给过滤器进行处理,过滤器处理完响应就将响应发送给客户端。

注意:上面话中的几个问题

1:web容器是如何判断请求和过滤器相关联。

2:过滤器是如何将处理完的请求交给其他过滤器的

前提知识:过滤器有三个接口

1:Filter接口中有三个方法

1>public void init(FilterConfig filterConfig)//这个参数中含有web.xml文件中的初始化参数,可以用来对请求进行处理

2>public void doFilter(ServletRequest request,ServletRequest response,FilterChain chain)//要注意第三个参数它主要是用来将处理完的请求发送到下一个过滤器

3>public void destroy()//销毁过滤器

2:FilterChain

1>void doFilter(ServletRequest request,ServletRequest response)

3:FilterConfig这个暂时不介绍

二:举例

字符编码过滤器:

1:创建字符编码过滤器类:

 1 public class FirstFilter implements Filter {
 2     protected String encoding = null;
 3     protected FilterConfig filter = null;
 4
 5
 6
 7
 8     /**
 9      * Default constructor.
10      */
11     public FirstFilter() {
12         // TODO Auto-generated constructor stub
13     }
14
15     /**
16      * @see Filter#destroy()
17      */
18     public void destroy() {
19         // TODO Auto-generated method stub
20         this.encoding = null;
21         this.filter = null;
22
23
24     }
25
26     /**
27      * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
28      */
29     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
30         // TODO Auto-generated method stub
31         // place your code here
32         if(encoding != null)
33         {
34             request.setCharacterEncoding(encoding);
35             response.setContentType("text/html; charset="+encoding);
36         }
37
38         // pass the request along the filter chai
39         chain.doFilter(request, response);//来将请求发送给下一个过滤器
40     }
41
42     /**
43      * @see Filter#init(FilterConfig)
44      */
45     public void init(FilterConfig fConfig) throws ServletException {//初始化将web.xml中的初始化参数的信息赋给encoding
46         // TODO Auto-generated method stub
47         this.filter = fConfig;
48         this.encoding = filter.getInitParameter("encoding");
49     }
50
51 }

2:在web.xml中配置相关信

   <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
 3   <display-name>MyfirstServlet</display-name>
 4   <welcome-file-list>
 5     <welcome-file>index.html</welcome-file>
 6     <welcome-file>index.htm</welcome-file>
 7     <welcome-file>index.jsp</welcome-file>
 8     <welcome-file>default.html</welcome-file>
 9     <welcome-file>default.htm</welcome-file>
10     <welcome-file>default.jsp</welcome-file>
11   </welcome-file-list><!-- servlet的配置信息-->
12   <servlet>
13     <servlet-name>HelloWorld</servlet-name>
14     <servlet-class>com.johnny.test.HelloWorld</servlet-class>
15   </servlet>
16   <servlet-mapping>
17     <servlet-name>HelloWorld</servlet-name>
18     <url-pattern>/helloworld</url-pattern>
19   </servlet-mapping><!--  filter的配置信息-->
20   <filter>
21     <filter-name>FirstFilter</filter-name>
22     <filter-class>com.johnny.test.FirstFilter</filter-class>  <!--  初始化参数-->
23     <init-param>
24        <param-name>encoding</param-name>
25        <param-value>GBK</param-value>
26     </init-param>
27   </filter>
28   <filter-mapping>
29      <filter-name>FirstFilter</filter-name>
30      <url-pattern>/*</url-pattern> <!--关联所有的url该使用该过滤器-->
31      <dispatcher>REQUEST</dispatcher><!--当客户端直接请求时进行过滤器处理-->
32      <dispatcher>FORWARD</dispatcher><!-- 当客户端用forward()方法请求时。。。。-->
33   </filter-mapping>
34
35
36
37 </web-app>

3:login.jsp登录界面:

 1 <%@ page language="java" contentType="text/html; charset=GB18030"
 2     pageEncoding="GB18030"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
 7 <title>Insert title here</title>
 8 </head>
 9 <body><!--action中放的是web.xml中映射servlet的url,它会直接将信息发送到servlet中进行处理-->
10 <form action = "helloworld" method = "post">
11   <table>
12      <tr>
13     <td> 登录名:</td><td><input type = "text" name = "usrname"></td>
14      </tr>
15      <tr>
16     <td>密码:</td><td><input type = "password" name = "password"></td>
17
18      </tr>
19
20   </table>
21      <input type = "submit" name = "submit" value = "登录">
22 </form>
23 </body>
24 </html>

4:编写servlet来进行处理login.jsp发来的信息

package com.johnny.test;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class HelloWorld
 */
@WebServlet("/HelloWorld")
public class HelloWorld extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public HelloWorld() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        PrintWriter out = response.getWriter();
        String name = request.getParameter("usrname");
        if(name != null && !name.equals(""))
        {
            out.println("你好"+name);
            out.println("欢迎来到英雄联盟");
            //request.getRequestDispatcher("index.jsp").forward(request, response);
        }
        else
        {
            out.println("请输入用户名");
        }
        out.print("<br><a href = index.jsp>返回</a>");
        out.flush();
        out.close();

    }

}

5:index.jsp页面来处理用户没有输入信息的处理

<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<!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=GB18030">
<title>Insert title here</title>
</head>
<body>

   <form action = "helloworld"  method = "post">
       <p>
         请你输入你的中文名字:
         <input type = "text" name = "usrname">
         <input type = "submit" name = "submit">
        </p>

   </form>

</body>
</html>

6:上面的问题答案在web.xml和filter类中可以找到答案

时间: 2024-08-03 19:20:02

servlet中的字符编码过滤器的使用的相关文章

web.xml中配置字符编码过滤器

<filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value&

Servlet字符编码过滤器

在Java Web程序开发中,由于Web容器内部使用编码格式并不支持中文字符集,所以,处理浏览器请求中的中文数据就会出现乱码的现象.由于Web容器使用了ISO-8859-1的编码格式,所以在Web应用的业务处理中也会使用ISO-8859-1编码格式.虽然浏览器提交的请求使用的是中文编码格式UTF-8,但经过业务处理中的ISO-8859-1编码,仍然会出现中文乱码现象.解决此问题的方法非常简单,在业务处理中重新指定中文字符集进行编码即可解决.在实际的开发过程中,如果通过每一个业务处理指定中文字符集

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

一.创建两个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

Java Web---登录验证和字符编码过滤器

什么是过滤器? 在Java Web中,过滤器即Filter.Servlet API中提供了一个Filter接口(javax.servlet.Filter),开发web应用时,如果编写的Java类实现了这个接口,则把这个Java类称之为过滤器Filter.通过Filter技术,开发人员可以实现用户在访问某个目标资源之前,对访问的请求和响应进行拦截.简单说,就是可以实现web容器对某资源的访问前截获进行相关的处理,还可以在某资源向web容器返回响应前进行截获进行处理. 创建一个Filter的步骤 1

深入Struts2的过滤器FilterDispatcher--中文乱码及字符编码过滤器

引用 前几天在论坛上看到一篇帖子,是关于Struts2.0中文乱码的,楼主采用的是spring的字符编码过滤器(CharacterEncodingFilter)统一编码为GBK,前台提交表单数据到Action,但是在Action中得到的中文全部是乱码,前台的页面编码都是GBK没有问题.这是为什么呢?下面我们就通过阅读FilterDispatcher和CharacterEncodingFilter这两个过滤器的源代码,了解其实现细节,最终得出为什么中文还是乱码! 测试环境及其前置知识 Struts

Android中检测字符编码(GB2312,ASCII,UTF8,UNICODE,TOTAL——ENCODINGS)方法(一)

package com.android.filebrowser; import java.io.*; import java.net.*; public class FileEncodingDetect { static final int GB2312 = 0; static final int ASCII = 1; static final int UTF8 = 2; static final int UNICODE = 3; //static final int GBK = 4; //st

perl脚本中对字符编码的支持

# 使perl程序支持utf8宽字符编码,不添加下面几行打印中文字符时将出现Wide character in print警告或错误.use utf8;binmode(STDIN, ':encoding(utf8)');binmode(STDOUT, ':encoding(utf8)');binmode(STDERR, ':encoding(utf8)');perl脚本处理中文等字符时,有时从文件读出的数据为字节码,需要进行解码才能正确显示.使用Encode模块即可处理.use Encode;#

浅析白盒审计中的字符编码及SQL注入

尽管现在呼吁所有的程序都使用unicode编码,所有的网站都使用utf-8编码,来一个统一的国际规范.但仍然有很多,包括国内及国外(特别是非英语国家)的一些cms,仍然使用着自己国家的一套编码,比如gbk,作为自己默认的编码类型.也有一些cms为了考虑老用户,所以出了gbk和utf-8两个版本. 我们就以gbk字符编码为示范,拉开帷幕.gbk是一种多字符编码,具体定义自行百度.但有一个地方尤其要注意: 通常来说,一个gbk编码汉字,占用2个字节.一个utf-8编码的汉字,占用3个字节.在php中

C#中的字符编码问题

该文件的编码为GB18030,每行的宽度为23个字符,其中第1-8列为员工姓名,第10-23列为工资额.现在我们要写一个C#程序求出该单位员工的平均工资,如下所示: 1using System; 2using System.IO; 3using System.Text; 4 5namespace Skyiv.Ben.Test 6{ 7  sealed class Avg 8  { 9    static void Main() 10    { 11      try 12      { 13