1、Filter概述:
2、自写一个Filter
import javax.servlet.*;
import java.io.IOException;
public class Demo01Filter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
}
@Override
public void destroy() {
}
}
Demo01Filter
Demo01.Demo01Filter
Demo01Filter
/demo01
3、Filter的方法:
3、Filter的生命周期:
4、Filter的url-pattern的配置:
5、FliterChain:过滤链
6、filter-mapping中的子标签:
7、在web.xml中配置全局的统一错误页面,可以配置多个
404
/index.jsp
8、FilterConfig
@WebFilter(filterName = "Demo02Filter" ,urlPatterns = {"/demo01"})
public class Demo02Filter implements Filter {
FilterConfig fc = null;
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
chain.doFilter(req, resp);
//获取Filter的名称
String filterName = fc.getFilterName();
System.out.println(filterName);
//获取初始化参数
String code = fc.getInitParameter("code");
System.out.println(code);
//获取所有初始化参数
Enumeration initParameterNames = fc.getInitParameterNames();
while (initParameterNames.hasMoreElements()){
String s = initParameterNames.nextElement();
System.out.println(s+":"+fc.getInitParameter(s));
}
//获取上下文对象
ServletContext servletContext = fc.getServletContext();
System.out.println(servletContext);
chain.doFilter(req,resp);
}
public void init(FilterConfig config) throws ServletException {
fc=config;
}
}
Demo02Filter
Demo01.Demo02Filter
code
utf-8
db
mysql
Demo02Filter
/demo01
1、需求:
2、源码
@WebFilter(filterName = "UserFilter",urlPatterns = {"/*"})
public class UserFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
//把ServletRequest强转为HttpServletRequest
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)resp;
//判断Session中是否有用户存在
String username1 = (String) request.getSession().getAttribute("username");
//若有,return不执行下面语句,避免重复查询数据库
if (username1 != null){
//放行
chain.doFilter(request,response);
return;
}
//获取所有的cookie,
Cookie[] cookies = request.getCookies();
Cookie coo = null;
//判断cookies是否为空
if(cookies != null){
//从cookies中查找与user匹配的cookie
for (Cookie cookie:cookies
) {
//如果相匹配
if("user".equals(cookie.getName())){
coo = cookie;
}
}
}
//判断是否是第一次登录
if(coo != null){
//若不是第一次登录,完成自动登录
//获取cookie中的用户名和密码
String value = coo.getValue();
//切割value字符串
String[] split = value.split("-");
String username = split[0];
String password = split[1];
//通过用户名和密码调用UserService的方法
User user = UserService.queryUser(username, password);
if(user != null){
//保证用户在线,把用户名放入Session中
request.getSession().setAttribute("username",user.getUsername());
//放行
chain.doFilter(request,response);
}
}else {
//若是第一次登录,放行
chain.doFilter(request,response);
}
}
public void init(FilterConfig config) throws ServletException {
}
}
@WebServlet(name = "UserServlet",urlPatterns = {"/yzm"})
public class UserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置response编码格式为utf-8,这样给前台写中文信息不会出现乱码
response.setHeader("content-type","text/html;charset=utf-8");
//获取前台输入的验证码
String code = request.getParameter("code");
//获取Session
HttpSession session = request.getSession();
//获取Session中存的随机生成的验证码
String code1 = (String) session.getAttribute("code");
//清空Session,保证点击登录时,验证码是最新的
session.removeAttribute("code");
//若前台输入的验证码为空或者都为空格
if(code==null || code.trim().length()==0){
//System.out.println("请输入验证码");
//把错误信息放入request域中
request.setAttribute("msg","请输入验证码");
//请求转发
request.getRequestDispatcher("/login.jsp").forward(request,response);
}else if(!(code.equalsIgnoreCase(code1))){
//判断输入的验证码是否和Session中存的一致,忽略大小写
//System.out.println("请输入正确的验证码");
request.setAttribute("msg","请输入正确的验证码");
//请求转发
request.getRequestDispatcher("/login.jsp").forward(request,response);
}else {
//获取请求的用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
//调用UserService的queryUser方法,把从前端HTML获取的用户名和密码传过去
User user = UserService.queryUser(username,password);
//判断从数据库中查询的数据,若查询到,登录成功,否则,登录失败
if(user == null){
//往前端HTML页面写信息
//response.getWriter( ).print("登录失败");
//System.out.println("登录失败");
request.setAttribute("msg","登录失败");
//请求转发
request.getRequestDispatcher("/login.jsp").forward(request,response);
}else {
//获取前台"请记住我"复选框的value值
String remember = request.getParameter("remember");
//判断是否勾选"请记住我"复选框
if("ok".equals(remember)){
//创建Cookie//把当前的用户名和密码放入Cookie中
Cookie cookie = new Cookie("user", username+"-"+password);
//设置Cookie的存活时间
cookie.setMaxAge(3600);
//把Cookie写回给浏览器
response.addCookie(cookie);
}
//request.getSession().setAttribute("username",user.getUsername());
//往前端HTML页面写信息
response.getWriter( ).print(username+",欢迎回来");
//System.out.println("登录成功");
}
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
1、需求:
@WebFilter(filterName = "EncodingFilter",urlPatterns = {"/*"})
public class EncodingFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)resp;
chain.doFilter(new MyRequest(request), response);
}
public void init(FilterConfig config) throws ServletException {
}
}
class MyRequest extends HttpServletRequestWrapper {
public MyRequest(HttpServletRequest request) {
super(request);
}
@Override
public String getParameter(String name) {
//获取提交方式
String method = super.getMethod();
//如果是get方式
if("get".equalsIgnoreCase(method)){
String username = super.getParameter("username");
try {
username = new String(username.getBytes("iso-8859-1"),"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return username;
//如果是post方式
}else if("post".equalsIgnoreCase(method)){
try {
super.setCharacterEncoding("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return super.getParameter(name);
}
return super.getParameter(name);
}
}
@WebServlet(name = "EncodingServlet",urlPatterns = {"/encoding"})
public class EncodingServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
System.out.println(username);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
System.out.println(username);
}
}
Title
以get方式提交