Filter+Servlet
程序员文章站
2022-06-03 09:13:36
...
代码仓库地址+文档:https://gitee.com/DerekAndroid/FilterServlet.git
保存用户登录信息效果:
自动登录’复选框
案例一:完成自动登录
需求:当用户第一次登录该网站的时候,如果勾选了‘自动登录’复选框,'保存用户登录信息'
那么关闭浏览器后,下次在访问该网站任何资源的时候,都会显示用户在线
技术分析:
session(保证用户在线)
cookie(保存第一访问网站的状态)
filter(到达目标资源之前,完成登录操作)
案例二:全局统一编码
需求:在向服务器发送请求的时候,使用filter过滤乱码问题
技术分析:
filter
对方法增强:
继承
动态代理
装饰者模式(静态代理)
如何使用装饰者模式:
装饰者和被装饰者继承同一个类或者实现同一个接口
装饰者中需要有被装饰者的引用
对需要增强的方法进行增强
对不需要增强的方法,直接使用父类的方法
filter处理编码:方案1:getParameter
package com.itheima.servlet;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.Map;
import java.util.Set;
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.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import com.itheima.bean.User;
import com.itheima.service.LoginService;
public class LoginFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
// HttpServletRequest request = (HttpServletRequest)req;
// chain.doFilter(new myCode(request), res);
//把servletReuqest强转为HttpServletRequest
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)res;
//判断session中是否有用户存在
String username1=(String)request.getSession().getAttribute("username");
if(username1!=null){
//放行
// chain.doFilter(request, response);
chain.doFilter(new myCodeParameter(request), res);
return;
}
//获取所有的cookie
Cookie[] cookies = request.getCookies();
Cookie co = null;
//判断cookies是否为null
if(cookies!=null){
//从cookies中查找与usernameAndPwd相匹配的cookie
for(Cookie cookie:cookies){
if("usernameAndPwd".equals(cookie.getName())){
co=cookie;
}
}
}
//判断是否是第一次登录
if(co!=null){
//获取cookie中的用户名和密码
String up = co.getValue();
System.out.println(co.getValue());
String[] sp = up.split("-");
String username = sp[0];
String password = sp[1];
//完成自动登录,调用LoginService
LoginService ls = new LoginService();
try {
User user = ls.getUserByUsernameAndPwd(username, password);
System.out.println("查询一次数据库");
if(user!=null){
//保证用户在线
request.getSession().setAttribute("username", user.getUsername());
}
//放行
// chain.doFilter(request, response);
chain.doFilter(new myCodeParameter(request), res);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
// chain.doFilter(request, response);
chain.doFilter(new myCodeParameter(request), res);
}
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
class myCodeParameter extends HttpServletRequestWrapper {
public myCodeParameter(HttpServletRequest request) {
super(request);
// TODO Auto-generated constructor stub
}
@Override
public String getParameter(String name) {
String method = super.getMethod();
if("get".equalsIgnoreCase(method)){
// String value = super.getParameter("username");
// try {
// value = new String(value.getBytes("iso-8859-1"),"utf-8");
// } catch (UnsupportedEncodingException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// return value;
//返回值有问题,全部拦截了
// username=阿根
// password=阿根
// yzm=阿根
// yzm=阿根
//编码转换
String value=super.getParameter(name);
System.out.println("value="+value);
//判断是参数提交才转换编码
if (null!=value) {
try {
value = new String(value.getBytes("iso-8859-1"),"utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return value;
}else if("post".equalsIgnoreCase(method)){
try {
super.setCharacterEncoding("utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return super.getParameter(name);
}
return super.getParameter(name);
}
}
方案2:重写getParameterValues
package com.itheima.servlet;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
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.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
/**
* 统一编码
* @author Administrator
*
*/
public class EncodingFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
//1.强转
HttpServletRequest request=(HttpServletRequest) req;
HttpServletResponse response=(HttpServletResponse) resp;
//2.放行
chain.doFilter(new MyRequest(request), response);
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
class MyRequest extends HttpServletRequestWrapper{
private HttpServletRequest request;
private boolean flag=true;
public MyRequest(HttpServletRequest request) {
super(request);
this.request=request;
}
@Override
public String getParameter(String name) {
if(name==null || name.trim().length()==0){
return null;
}
String[] values = getParameterValues(name);
if(values==null || values.length==0){
return null;
}
return values[0];
}
@Override
/**
* hobby=[eat,drink]
*/
public String[] getParameterValues(String name) {
if(name==null || name.trim().length()==0){
return null;
}
Map<String, String[]> map = getParameterMap();
if(map==null || map.size()==0){
return null;
}
return map.get(name);
}
@Override
/**
* map{ username=[tom],password=[123],hobby=[eat,drink]}
*/
public Map<String,String[]> getParameterMap() {
/**
* 首先判断请求方式
* 若为post request.setchar...(utf-8)
* 若为get 将map中的值遍历编码就可以了
*/
String method = request.getMethod();
if("post".equalsIgnoreCase(method)){
try {
request.setCharacterEncoding("utf-8");
return request.getParameterMap();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if("get".equalsIgnoreCase(method)){
Map<String,String[]> map = request.getParameterMap();
if(flag){
for (String key:map.keySet()) {
String[] arr = map.get(key);
//继续遍历数组
for(int i=0;i<arr.length;i++){
//编码
try {
arr[i]=new String(arr[i].getBytes("iso8859-1"),"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
flag=false;
}
//需要遍历map 修改value的每一个数据的编码
return map;
}
return super.getParameterMap();
}
}
上一篇: Servlet与filter
下一篇: input = file 实现上传文件
推荐阅读