统一全站字符编码的过滤器
- 通过配置参数encoding指明使用何种字符编码,以处理Html Form请求参数的中文问题
没配置过滤器:
CharseterEncodingFilter.java
- package com.hbsi.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;
- import javax.servlet.http.HttpServletRequest;
- public class CharseterEncodingFilter implements Filter {
- private FilterConfig config = null;
- private String defaultCharset = "UTF-8";
- public void destroy() {
- // TODO Auto-generated method stub
- }
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
- // TODO Auto-generated method stub
- String charset = config.getInitParameter("charset");
- if(charset==null){
- charset = defaultCharset;
- }
- request.setCharacterEncoding(charset);
- //如果是servlet进行相应设置
- response.setCharacterEncoding("UTF-8");
- response.setContentType("text/html;charset="+charset);
- chain.doFilter(request, response);
- }
- public void init(FilterConfig filterConfig) throws ServletException {
- // TODO Auto-generated method stub
- this.config = filterConfig;
- }
- }
web.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <!--
- <filter>
- <filter-name>FilterChain</filter-name>
- <filter-class>com.hbsi.filter.FilterChain</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>FilterChain</filter-name>
- <url-pattern>*.jsp</url-pattern>
- </filter-mapping>
- <filter>
- <filter-name>FilterDemo1</filter-name>
- <filter-class>com.hbsi.filter.FilterDemo1</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>FilterDemo1</filter-name>
- <url-pattern>*.html</url-pattern>
- </filter-mapping>
- <filter>
- <filter-name>FilterShengZhou</filter-name>
- <filter-class>com.hbsi.filter.FilterShengZhou</filter-class>
- <init-param>
- <param-name>abc</param-name>
- <param-value>aaaaa</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>FilterShengZhou</filter-name>
- <url-pattern>*.jsp</url-pattern>
- </filter-mapping>
- -->
- <servlet>
- <description>This is the description of my J2EE component</description>
- <display-name>This is the display name of my J2EE component</display-name>
- <servlet-name>LuanMaServlet</servlet-name>
- <servlet-class>com.hbsi.servlet.LuanMaServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>LuanMaServlet</servlet-name>
- <url-pattern>/servlet/luanMa.do</url-pattern>
- </servlet-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
LuanMaServlet.java
- package com.hbsi.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;
- public class LuanMaServlet extends HttpServlet {
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- String city = request.getParameter("city");
- response.getWriter().write(city);
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doGet(request, response);
- }
- }
luanMa.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>My JSP 'luanMa.jsp' starting page</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- <!--
- <link rel="stylesheet" type="text/css" href="styles.css">
- -->
- </head>
- <body>
- <form action="servlet/luanMa.do" method="post">
- 城市:<input type="text" name="city"/>
- <input type="submit" value="提交"/>
- </form>
- </body>
- </html>
![](https://img-my.csdn.net/uploads/201212/04/1354619333_7307.png)
配置过滤器:
web.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5"
- <span style="white-space:pre"> </span>xmlns="http://java.sun.com/xml/ns/javaee"
- <span style="white-space:pre"> </span>xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- <span style="white-space:pre"> </span>xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- <span style="white-space:pre"> </span>http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <span style="white-space:pre"> </span><!--
- <span style="white-space:pre"> </span><filter>
- <span style="white-space:pre"> </span><filter-name>FilterChain</filter-name>
- <span style="white-space:pre"> </span><filter-class>com.hbsi.filter.FilterChain</filter-class>
- <span style="white-space:pre"> </span></filter>
- <span style="white-space:pre"> </span><filter-mapping>
- <span style="white-space:pre"> </span><filter-name>FilterChain</filter-name>
- <span style="white-space:pre"> </span><url-pattern>*.jsp</url-pattern>
- <span style="white-space:pre"> </span></filter-mapping>
- <span style="white-space:pre"> </span>
- <span style="white-space:pre"> </span><filter>
- <span style="white-space:pre"> </span><filter-name>FilterDemo1</filter-name>
- <span style="white-space:pre"> </span><filter-class>com.hbsi.filter.FilterDemo1</filter-class>
- <span style="white-space:pre"> </span></filter>
- <span style="white-space:pre"> </span><filter-mapping>
- <span style="white-space:pre"> </span><filter-name>FilterDemo1</filter-name>
- <span style="white-space:pre"> </span><url-pattern>*.html</url-pattern>
- <span style="white-space:pre"> </span></filter-mapping>
- <span style="white-space:pre"> </span>
- <span style="white-space:pre"> </span><filter>
- <span style="white-space:pre"> </span><filter-name>FilterShengZhou</filter-name>
- <span style="white-space:pre"> </span><filter-class>com.hbsi.filter.FilterShengZhou</filter-class>
- <span style="white-space:pre"> </span><init-param>
- <span style="white-space:pre"> </span><param-name>abc</param-name>
- <span style="white-space:pre"> </span><param-value>aaaaa</param-value>
- <span style="white-space:pre"> </span></init-param>
- <span style="white-space:pre"> </span></filter>
- <span style="white-space:pre"> </span><filter-mapping>
- <span style="white-space:pre"> </span><filter-name>FilterShengZhou</filter-name>
- <span style="white-space:pre"> </span><url-pattern>*.jsp</url-pattern>
- <span style="white-space:pre"> </span></filter-mapping>
- <span style="white-space:pre"> </span>-->
- <span style="white-space:pre"> </span><filter>
- <span style="white-space:pre"> </span><filter-name>CharseterEncodingFilter</filter-name>
- <span style="white-space:pre"> </span><filter-class>com.hbsi.filter.CharseterEncodingFilter</filter-class>
- <span style="white-space:pre"> </span><init-param>
- <span style="white-space:pre"> </span><param-name>charset</param-name>
- <span style="white-space:pre"> </span><param-value>UTF-8</param-value>
- <span style="white-space:pre"> </span></init-param>
- <span style="white-space:pre"> </span></filter>
- <span style="white-space:pre"> </span><filter-mapping>
- <span style="white-space:pre"> </span><filter-name>CharseterEncodingFilter</filter-name>
- <span style="white-space:pre"> </span><url-pattern>*.jsp</url-pattern>
- <span style="white-space:pre"> </span></filter-mapping>
- <span style="white-space:pre"> </span><filter-mapping>
- <span style="white-space:pre"> </span><filter-name>CharseterEncodingFilter</filter-name>
- <span style="white-space:pre"> </span><url-pattern>/servlet/*</url-pattern>
- <span style="white-space:pre"> </span></filter-mapping>
- <servlet>
- <description>This is the description of my J2EE component</description>
- <display-name>This is the display name of my J2EE component</display-name>
- <servlet-name>LuanMaServlet</servlet-name>
- <servlet-class>com.hbsi.servlet.LuanMaServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>LuanMaServlet</servlet-name>
- <url-pattern>/servlet/luanMa.do</url-pattern>
- </servlet-mapping>
- <span style="white-space:pre"> </span>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
禁止浏览器缓存所有动态页面的过滤器
- 有 3 个 HTTP 响应头字段都可以禁止浏览器缓存当前页面,它们在 Servlet 中的示例代码如下:
- response.setDateHeader("Expires",-1);
- response.setHeader("Cache-Control","no-cache");
- response.setHeader("Pragma","no-cache");
- 并不是所有的浏览器都能完全支持上面的三个响应头,因此最好是同时使用上面的三个响应头。
- Expires数据头:值为GMT时间值,为-1指浏览器不要缓存页面
- Cache-Control响应头有两个常用值:
- no-cache指浏览器不要缓存当前页面。
- max-age:xxx指浏览器缓存页面xxx秒。
允许缓存:不编写过滤器
NoCacheFilter.java
- package com.hbsi.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;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- public class NoCacheFilter implements Filter {
- public void destroy() {
- // TODO Auto-generated method stub
- }
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
- // TODO Auto-generated method stub
- HttpServletRequest req = (HttpServletRequest) request;
- HttpServletResponse resp = (HttpServletResponse) response;
- resp.setDateHeader("expires",-1);
- resp.setHeader("Cache-Control", "no-cache");
- resp.setHeader("Pragma", "no-cache");
- chain.doFilter(req,resp);
- }
- public void init(FilterConfig filterConfig) throws ServletException {
- // TODO Auto-generated method stub
- }
- }
web.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <!--
- <filter>
- <filter-name>FilterChain</filter-name>
- <filter-class>com.hbsi.filter.FilterChain</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>FilterChain</filter-name>
- <url-pattern>*.jsp</url-pattern>
- </filter-mapping>
- <filter>
- <filter-name>FilterDemo1</filter-name>
- <filter-class>com.hbsi.filter.FilterDemo1</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>FilterDemo1</filter-name>
- <url-pattern>*.html</url-pattern>
- </filter-mapping>
- <filter>
- <filter-name>FilterShengZhou</filter-name>
- <filter-class>com.hbsi.filter.FilterShengZhou</filter-class>
- <init-param>
- <param-name>abc</param-name>
- <param-value>aaaaa</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>FilterShengZhou</filter-name>
- <url-pattern>*.jsp</url-pattern>
- </filter-mapping>
- -->
- <filter>
- <filter-name>CharseterEncodingFilter</filter-name>
- <filter-class>com.hbsi.filter.CharseterEncodingFilter</filter-class>
- <init-param>
- <param-name>charset</param-name>
- <param-value>UTF-8</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>CharseterEncodingFilter</filter-name>
- <url-pattern>*.jsp</url-pattern>
- </filter-mapping>
- <filter-mapping>
- <filter-name>CharseterEncodingFilter</filter-name>
- <url-pattern>/servlet/*</url-pattern>
- </filter-mapping>
- <servlet>
- <description>This is the description of my J2EE component</description>
- <display-name>This is the display name of my J2EE component</display-name>
- <servlet-name>LuanMaServlet</servlet-name>
- <servlet-class>com.hbsi.servlet.LuanMaServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>LuanMaServlet</servlet-name>
- <url-pattern>/servlet/luanMa.do</url-pattern>
- </servlet-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
访问luanMa.jsp
![](https://img-my.csdn.net/uploads/201212/04/1354620510_9254.png)
![](https://img-my.csdn.net/uploads/201212/04/1354620519_8244.png)
![](https://img-my.csdn.net/uploads/201212/04/1354620408_9692.png)
编写过滤器禁止缓存:
NoCacheFilter.java
- package com.hbsi.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;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- public class NoCacheFilter implements Filter {
- public void destroy() {
- // TODO Auto-generated method stub
- }
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
- // TODO Auto-generated method stub
- HttpServletRequest req = (HttpServletRequest) request;
- HttpServletResponse resp = (HttpServletResponse) response;
- resp.setDateHeader("expires",-1);
- resp.setHeader("Cache-Control", "no-cache");
- resp.setHeader("Pragma", "no-cache");
- chain.doFilter(req,resp);
- }
- public void init(FilterConfig filterConfig) throws ServletException {
- // TODO Auto-generated method stub
- }
- }
web.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <!--
- <filter>
- <filter-name>FilterChain</filter-name>
- <filter-class>com.hbsi.filter.FilterChain</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>FilterChain</filter-name>
- <url-pattern>*.jsp</url-pattern>
- </filter-mapping>
- <filter>
- <filter-name>FilterDemo1</filter-name>
- <filter-class>com.hbsi.filter.FilterDemo1</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>FilterDemo1</filter-name>
- <url-pattern>*.html</url-pattern>
- </filter-mapping>
- <filter>
- <filter-name>FilterShengZhou</filter-name>
- <filter-class>com.hbsi.filter.FilterShengZhou</filter-class>
- <init-param>
- <param-name>abc</param-name>
- <param-value>aaaaa</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>FilterShengZhou</filter-name>
- <url-pattern>*.jsp</url-pattern>
- </filter-mapping>
- -->
- <filter>
- <filter-name>CharseterEncodingFilter</filter-name>
- <filter-class>com.hbsi.filter.CharseterEncodingFilter</filter-class>
- <init-param>
- <param-name>charset</param-name>
- <param-value>UTF-8</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>CharseterEncodingFilter</filter-name>
- <url-pattern>*.jsp</url-pattern>
- </filter-mapping>
- <filter-mapping>
- <filter-name>CharseterEncodingFilter</filter-name>
- <url-pattern>/servlet/*</url-pattern>
- </filter-mapping>
- <filter>
- <filter-name>NoCahceFilter</filter-name>
- <filter-class>com.hbsi.filter.NoCacheFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>NoCahceFilter</filter-name>
- <url-pattern>*.jsp</url-pattern>
- </filter-mapping>
- <filter-mapping>
- <filter-name>NoCahceFilter</filter-name>
- <url-pattern>/servlet/*</url-pattern>
- </filter-mapping>
- <servlet>
- <description>This is the description of my J2EE component</description>
- <display-name>This is the display name of my J2EE component</display-name>
- <servlet-name>LuanMaServlet</servlet-name>
- <servlet-class>com.hbsi.servlet.LuanMaServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>LuanMaServlet</servlet-name>
- <url-pattern>/servlet/luanMa.do</url-pattern>
- </servlet-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
![](https://img-my.csdn.net/uploads/201212/04/1354620701_9434.png)
控制浏览器缓存页面中的静态资源的过滤器:
- 场景:有些动态页面中引用了一些图片或css文件以修饰页面效果,这些图片和css文件经常是不变化的,所以为减轻服务器的压力,可以使用filter控制浏览器缓存这些文件,以提升服务器的性能。
ExpiresFilter.java
- package com.hbsi.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;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- //控制浏览器可以缓存js,css,jpg。
- public class ExpiresFilter implements Filter {
- private FilterConfig config;
- public void destroy() {
- // TODO Auto-generated method stub
- }
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
- // TODO Auto-generated method stub
- HttpServletRequest req = (HttpServletRequest) request;
- HttpServletResponse resp = (HttpServletResponse) response;
- String uri = req.getRequestURI();
- if(uri.endsWith(".css")){
- long time = Integer.parseInt(config.getInitParameter("css"))*1000;
- resp.setDateHeader("expires",System.currentTimeMillis()+time);
- }else if(uri.endsWith(".js")){
- long time = Integer.parseInt(config.getInitParameter("js"))*1000;
- resp.setDateHeader("expires",System.currentTimeMillis()+time);
- }else if(uri.endsWith(".jpg")){
- long time = Integer.parseInt(config.getInitParameter("jpg"))*1000;
- resp.setDateHeader("expires",System.currentTimeMillis()+time);
- }
- chain.doFilter(req, resp);
- }
- public void init(FilterConfig filterConfig) throws ServletException {
- // TODO Auto-generated method stub
- this.config = filterConfig;
- }
- }
web.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <!--
- <filter>
- <filter-name>FilterChain</filter-name>
- <filter-class>com.hbsi.filter.FilterChain</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>FilterChain</filter-name>
- <url-pattern>*.jsp</url-pattern>
- </filter-mapping>
- <filter>
- <filter-name>FilterDemo1</filter-name>
- <filter-class>com.hbsi.filter.FilterDemo1</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>FilterDemo1</filter-name>
- <url-pattern>*.html</url-pattern>
- </filter-mapping>
- <filter>
- <filter-name>FilterShengZhou</filter-name>
- <filter-class>com.hbsi.filter.FilterShengZhou</filter-class>
- <init-param>
- <param-name>abc</param-name>
- <param-value>aaaaa</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>FilterShengZhou</filter-name>
- <url-pattern>*.jsp</url-pattern>
- </filter-mapping>
- -->
- <filter>
- <filter-name>CharseterEncodingFilter</filter-name>
- <filter-class>com.hbsi.filter.CharseterEncodingFilter</filter-class>
- <init-param>
- <param-name>charset</param-name>
- <param-value>UTF-8</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>CharseterEncodingFilter</filter-name>
- <url-pattern>*.jsp</url-pattern>
- </filter-mapping>
- <filter-mapping>
- <filter-name>CharseterEncodingFilter</filter-name>
- <url-pattern>/servlet/*</url-pattern>
- </filter-mapping>
- <filter>
- <filter-name>NoCahceFilter</filter-name>
- <filter-class>com.hbsi.filter.NoCacheFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>NoCahceFilter</filter-name>
- <url-pattern>*.jsp</url-pattern>
- </filter-mapping>
- <filter-mapping>
- <filter-name>NoCahceFilter</filter-name>
- <url-pattern>/servlet/*</url-pattern>
- </filter-mapping>
- <filter>
- <filter-name>ExpiresFilter</filter-name>
- <filter-class>com.hbsi.filter.ExpiresFilter</filter-class>
- <init-param>
- <param-name>css</param-name>
- <param-value>120</param-value>
- </init-param>
- <init-param>
- <param-name>jpg</param-name>
- <param-value>120</param-value>
- </init-param>
- <init-param>
- <param-name>js</param-name>
- <param-value>120</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>ExpiresFilter</filter-name>
- <url-pattern>*.css</url-pattern>
- </filter-mapping>
- <filter-mapping>
- <filter-name>ExpiresFilter</filter-name>
- <url-pattern>*.jpg</url-pattern>
- </filter-mapping>
- <filter-mapping>
- <filter-name>ExpiresFilter</filter-name>
- <url-pattern>*.js</url-pattern>
- </filter-mapping>
- <servlet>
- <description>This is the description of my J2EE component</description>
- <display-name>This is the display name of my J2EE component</display-name>
- <servlet-name>LuanMaServlet</servlet-name>
- <servlet-class>com.hbsi.servlet.LuanMaServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>LuanMaServlet</servlet-name>
- <url-pattern>/servlet/luanMa.do</url-pattern>
- </servlet-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
expiresFilter.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>My JSP 'expiresFilter.jsp' starting page</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- <!--
- <link rel="stylesheet" type="text/css" href="styles.css">
- -->
- </head>
- <body>
- <img src="tu.jpg">
- </body>
- </html>
![](https://img-my.csdn.net/uploads/201212/04/1354621715_6318.png)
实现用户自动登陆的过滤器
- 在用户登陆成功后,发送一个名称为user的cookie给客户端,cookie的值为用户名和md5加密后的密码。
- 编写一个AutoLoginFilter,这个filter检查用户是否带有名称为user的cookie来,如果有,则调用dao查询cookie的用户名和密码是否和数据库匹配,匹配则向session中存入user对象(即用户登陆标记),以实现程序完成自动登陆。
login.jsp
建表:
DBUtils连接数据库倒包
c3p0_config.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <c3p0-config>
- <default-config>
- <property name="driverClass">com.mysql.jdbc.Driver</property>
- <property name="jdbcUrl">jdbc:mysql://localhost:3306/filter</property>
- <property name="user">root</property>
- <property name="password">123456</property>
- <property name="acquireIncrement">5</property>
- <property name="initialPoolSize">10</property>
- <property name="minPoolSize">5</property>
- <property name="maxPoolSize">20</property>
- </default-config>
- <named-config name="mysql">
- <property name="driverClass">com.mysql.jdbc.Driver</property>
- <property name="jdbcUrl">jdbc:mysql://localhost:3306/filter</property>
- <property name="user">root</property>
- <property name="password">123456</property>
- <property name="acquireIncrement">5</property>
- <property name="initialPoolSize">10</property>
- <property name="minPoolSize">5</property>
- <property name="maxPoolSize">20</property>
- </named-config>
- </c3p0-config>
- package com.hbsi.util;
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import javax.sql.DataSource;
- import com.mchange.v2.c3p0.ComboPooledDataSource;
- public class DBManager {
- private static ComboPooledDataSource ds = null;
- static{
- try{
- //创建连接池
- ds = new ComboPooledDataSource("mysql");
- }catch(Exception e){
- e.printStackTrace();
- }
- }
- //获取链接
- public static DataSource getDataSource(){
- return ds;
- }
- }
User.java
- package com.hbsi.domain;
- public class User {
- private String username;
- private String password;
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- public String getUsername() {
- return username;
- }
- }
UserDao.java
- package com.hbsi.dao;
- import java.util.List;
- import com.hbsi.domain.User;
- public interface UserDao {
- public List<User> getAll();
- public User find(String username,String password);
- public User find(String username);
- }
UserDaoImpl.java
- package com.hbsi.dao;
- import java.util.List;
- import org.apache.commons.dbutils.QueryRunner;
- import org.apache.commons.dbutils.handlers.BeanHandler;
- import org.apache.commons.dbutils.handlers.BeanListHandler;
- import com.hbsi.domain.User;
- import com.hbsi.util.DBManager;
- public class UserDaoImpl implements UserDao {
- public List<User> getAll(){
- try{
- QueryRunner runner = new QueryRunner(DBManager.getDataSource());
- String sql = "select * from user";
- return (List<User>) runner.query(sql,new BeanListHandler(User.class));
- }catch(Exception e){
- throw new RuntimeException();
- }
- }
- public User find(String username,String password){
- try{
- QueryRunner runner = new QueryRunner(DBManager.getDataSource());
- String sql = "select * from user where username=? and password=?";
- Object[] params = {username,password};
- return (User) runner.query(sql, params, new BeanHandler(User.class));
- }catch(Exception e){
- e.printStackTrace();
- throw new RuntimeException(e);
- }
- }
- public User find(String username){
- try{
- QueryRunner runner = new QueryRunner(DBManager.getDataSource());
- String sql = "select * from user where username=?";
- return (User) runner.query(sql, username, new BeanHandler(User.class));
- }catch(Exception e){
- throw new RuntimeException();
- }
- }
- }
LoginServlet.java
- package com.hbsi.servlet;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.security.MessageDigest;
- import java.security.NoSuchAlgorithmException;
- import javax.servlet.ServletException;
- import javax.servlet.http.Cookie;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import sun.misc.BASE64Encoder;
- import com.hbsi.dao.UserDao;
- import com.hbsi.dao.UserDaoImpl;
- import com.hbsi.domain.User;
- public class LoginServlet extends HttpServlet {
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- String username = request.getParameter("username");
- String password = request.getParameter("password");
- int autoLoginTime =Integer.parseInt(request.getParameter("autoLoginTime"));
- UserDao dao = new UserDaoImpl();
- User user = dao.find(username, password);
- if(user != null){
- //放到session域
- request.getSession().setAttribute("user",user);
- Cookie cookie1 = new Cookie("username",user.getUsername());
- Cookie cookie2 = new Cookie("password",user.getPassword());
- cookie1.setMaxAge(autoLoginTime);
- cookie2.setMaxAge(autoLoginTime);
- cookie1.setPath("/Filter");
- cookie2.setPath("/Filter");
- response.addCookie(cookie1);
- response.addCookie(cookie2);
- //重定向
- response.sendRedirect("../ChangJianYingYong/welcome.jsp");
- }else{
- request.setAttribute("message","用户名密码错");
- request.getRequestDispatcher("../ChangJianYingYong/message.jsp").forward(request, response);
- }
- }
- private String md5(String input){
- try {
- MessageDigest md = MessageDigest.getInstance("md5");
- byte[] result = md.digest(input.getBytes());
- BASE64Encoder encoder = new BASE64Encoder();
- return encoder.encode(result);
- } catch (NoSuchAlgorithmException e) {
- e.printStackTrace();
- throw new RuntimeException(e);
- }
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doGet(request, response);
- }
- }
AutoLoginFilter.java
- package com.hbsi.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;
- import javax.servlet.http.Cookie;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import com.hbsi.dao.UserDao;
- import com.hbsi.dao.UserDaoImpl;
- import com.hbsi.domain.User;
- public class AutoLoginFilter implements Filter {
- public void destroy() {
- // TODO Auto-generated method stub
- }
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
- // TODO Auto-generated method stub
- HttpServletRequest req = (HttpServletRequest) request;
- HttpServletResponse resp = (HttpServletResponse) response;
- //1.检查用户是否登录
- User user = (User) req.getSession().getAttribute("user");
- if(user!=null){
- chain.doFilter(req,resp);
- return;
- }
- //2.检查用户是否带cookie来
- String username = null;
- String password = null;
- Cookie[] cookies = req.getCookies();
- for(int i=0;cookies!=null && i<cookies.length;i++){
- if(cookies[i].getName().equals("username")){
- username = cookies[i].getValue();
- }
- if(cookies[i].getName().equals("password")){
- password = cookies[i].getValue();
- }
- }
- if(username==null && password==null){
- chain.doFilter(req, resp);
- return;
- }
- UserDao dao = new UserDaoImpl();
- User user1 = dao.find(username);
- String save_password = user1.getPassword();
- if(!password.equals(save_password)){
- chain.doFilter(req, resp);
- return;
- }
- req.getSession().setAttribute("user",user1);
- chain.doFilter(req, resp);
- }
- public void init(FilterConfig filterConfig) throws ServletException {
- // TODO Auto-generated method stub
- }
- }
web.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <!--
- <filter>
- <filter-name>FilterChain</filter-name>
- <filter-class>com.hbsi.filter.FilterChain</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>FilterChain</filter-name>
- <url-pattern>*.jsp</url-pattern>
- </filter-mapping>
- <filter>
- <filter-name>FilterDemo1</filter-name>
- <filter-class>com.hbsi.filter.FilterDemo1</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>FilterDemo1</filter-name>
- <url-pattern>*.html</url-pattern>
- </filter-mapping>
- <filter>
- <filter-name>FilterShengZhou</filter-name>
- <filter-class>com.hbsi.filter.FilterShengZhou</filter-class>
- <init-param>
- <param-name>abc</param-name>
- <param-value>aaaaa</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>FilterShengZhou</filter-name>
- <url-pattern>*.jsp</url-pattern>
- </filter-mapping>
- -->
- <filter>
- <filter-name>CharseterEncodingFilter</filter-name>
- <filter-class>com.hbsi.filter.CharseterEncodingFilter</filter-class>
- <init-param>
- <param-name>charset</param-name>
- <param-value>UTF-8</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>CharseterEncodingFilter</filter-name>
- <url-pattern>*.jsp</url-pattern>
- </filter-mapping>
- <filter-mapping>
- <filter-name>CharseterEncodingFilter</filter-name>
- <url-pattern>/servlet/*</url-pattern>
- </filter-mapping>
- <filter>
- <filter-name>NoCahceFilter</filter-name>
- <filter-class>com.hbsi.filter.NoCacheFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>NoCahceFilter</filter-name>
- <url-pattern>*.jsp</url-pattern>
- </filter-mapping>
- <filter-mapping>
- <filter-name>NoCahceFilter</filter-name>
- <url-pattern>/servlet/*</url-pattern>
- </filter-mapping>
- <filter>
- <filter-name>ExpiresFilter</filter-name>
- <filter-class>com.hbsi.filter.ExpiresFilter</filter-class>
- <init-param>
- <param-name>css</param-name>
- <param-value>120</param-value>
- </init-param>
- <init-param>
- <param-name>jpg</param-name>
- <param-value>120</param-value>
- </init-param>
- <init-param>
- <param-name>js</param-name>
- <param-value>120</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>ExpiresFilter</filter-name>
- <url-pattern>*.css</url-pattern>
- </filter-mapping>
- <filter-mapping>
- <filter-name>ExpiresFilter</filter-name>
- <url-pattern>*.jpg</url-pattern>
- </filter-mapping>
- <filter-mapping>
- <filter-name>ExpiresFilter</filter-name>
- <url-pattern>*.js</url-pattern>
- </filter-mapping>
- <servlet>
- <description>This is the description of my J2EE component</description>
- <display-name>This is the display name of my J2EE component</display-name>
- <servlet-name>LuanMaServlet</servlet-name>
- <servlet-class>com.hbsi.servlet.LuanMaServlet</servlet-class>
- </servlet>
- <servlet>
- <description>This is the description of my J2EE component</description>
- <display-name>This is the display name of my J2EE component</display-name>
- <servlet-name>LoginServlet</servlet-name>
- <servlet-class>com.hbsi.servlet.LoginServlet</servlet-class>
- </servlet>
- <filter>
- <filter-name>AutoLoginFilter</filter-name>
- <filter-class>com.hbsi.filter.AutoLoginFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>AutoLoginFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <servlet-mapping>
- <servlet-name>LuanMaServlet</servlet-name>
- <url-pattern>/servlet/luanMa.do</url-pattern>
- </servlet-mapping>
- <servlet-mapping>
- <servlet-name>LoginServlet</servlet-name>
- <url-pattern>/servlet/LoginServlet</url-pattern>
- </servlet-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
welcome.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>My JSP 'welcome.jsp' starting page</title>
- </head>
- <body>
- 欢迎您:${user.username} <br>
- </body>
- </html>
message.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>My JSP 'message.jsp' starting page</title>
- </head>
- <body>
- ${message}<br>
- </body>
- </html>