Java WEB之过滤器
过滤器是什么玩意?
所谓过滤器,其实就是一个服务端组件,用来截取用户端的请求与响应信息。
过滤器的应用场景:
1.对用户请求进行统一认证,保证不会出现用户账户安全性问题
2.编码转换,可在服务端的过滤器中设置统一的编码格式,避免出现乱码
3.对用户发送的数据进行过滤替换
4.转换图像格式
5.对响应的内容进行压缩
其中,第1,2场景经常涉及。
<%@ page language="java" import="java.util.*" contentType="text/html; charset=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 'login.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="<%=path %>/servlet/LoginServlet" method="post" >用户名:<input type="text" name="username" />密码:<input type="password" name="password" /><input type="submit" value="登录" /></form></body> </html>
login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8" contentType="text/html; charset=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 'index.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></body> </html>
success.jsp
<%@ page language="java" import="java.util.*" contentType="text/html; charset=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 'login.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>登录失败,请检查用户名或密码!</body> </html>
failure.jsp
package com.cityhuntshou.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; import javax.servlet.http.HttpSession;public class LoginFilter implements Filter {private FilterConfig config;public void destroy() {}public void doFilter(ServletRequest arg0, ServletResponse arg1,FilterChain arg2) throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest) arg0;HttpServletResponse response = (HttpServletResponse) arg1;HttpSession session = request.getSession();//过滤器实际应用场景之二-----编码转换 String charset = config.getInitParameter("charset");if(charset == null){charset = "UTF-8";}request.setCharacterEncoding(charset);String noLoginPaths = config.getInitParameter("noLoginPaths");if(noLoginPaths != null){String[] strArray = noLoginPaths.split(";");for(int i = 0; i < strArray.length; i++){//空元素,放行if(strArray[i] == null || "".equals(strArray[i]))continue;if(request.getRequestURI().indexOf(strArray[i]) != -1){arg2.doFilter(arg0, arg1);return;}}}if(request.getRequestURI().indexOf("login.jsp") != -1|| request.getRequestURI().indexOf("LoginServlet") != -1){arg2.doFilter(arg0, arg1);return;}if(session.getAttribute("username") != null){arg2.doFilter(arg0, arg1);}else {response.sendRedirect("login.jsp");}}public void init(FilterConfig arg0) throws ServletException {config = arg0;}}
LoginFilter.java
package com.cityhuntshou.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 {/*** Constructor of the object.*/public LoginServlet() {super();}/*** Destruction of the servlet. <br>*/public void destroy() {super.destroy(); // Just puts "destroy" string in log// Put your code here }/*** The doGet method of the servlet. <br>** This method is called when a form has its tag value method equals to get.* * @param request the request send by the client to the server* @param response the response send by the server to the client* @throws ServletException if an error occurred* @throws IOException if an error occurred*/public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {}/*** The doPost method of the servlet. <br>** This method is called when a form has its tag value method equals to post.* * @param request the request send by the client to the server* @param response the response send by the server to the client* @throws ServletException if an error occurred* @throws IOException if an error occurred*/public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String username = request.getParameter("username");String password = request.getParameter("password");//new String(username.getBytes("ISO-8859-1"),"UTF-8") System.out.println(username);if("admin".equals(username) && "admin".equals(password)){//校验通过HttpSession session = request.getSession();session.setAttribute("username", username);response.sendRedirect(request.getContextPath()+"/success.jsp");}else {//校验失败response.sendRedirect(request.getContextPath()+"/failure.jsp");}}/*** Initialization of the servlet. <br>** @throws ServletException if an error occurs*/public void init() throws ServletException {// Put your code here }}
LoginServlet.java
<?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"><display-name></display-name><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.cityhuntshou.servlet.LoginServlet</servlet-class></servlet><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><filter><filter-name>LoginFilter</filter-name><filter-class>com.cityhuntshou.filter.LoginFilter</filter-class><init-param><param-name>noLoginPaths</param-name><param-value>login.jsp;failure.jsp;loginServlet</param-value></init-param><init-param><param-name>charset</param-name><param-value>UTF-8</param-value></init-param></filter><filter-mapping><filter-name>LoginFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping> </web-app>
web.xml
运行效果:
访问结果:
转载于:https://www.cnblogs.com/cityhuntshou/p/7443688.html
Java WEB之过滤器相关推荐
- java web压缩过滤器_Java Web过滤器Filter(五)
Filter概述 Filter意为滤镜或者过滤器,用于在Servlet之外对request或者response进行修改.Filter提出滤镜链的概念,一个FilterChain包括多外Filter.客 ...
- 初学Java Web(8)——过滤器和监听器
什么是过滤器 过滤器就是 Servlet 的高级特性之一,就是一个具有拦截/过滤功能的一个东西,在生活中过滤器可以是香烟滤嘴,滤纸,净水器,空气净化器等,在 Web 中仅仅是一个实现了 Filter ...
- Java web—Servlet过滤器(Filter)
前言: 过滤器是Servlet中一个非常重要的组成部分,进行WEB开发时无不用到过滤器:因此这篇blog来单独总结下关于过滤器的知识点. 一.首先来了解一下什么是过滤器: 下面这句话引 ...
- Java Web之过滤器的简单创建
Java Web开发中 的过滤器 ( filter ) 是 从Servlet 2.3规范开始增加 的 功能 , 并在Servlet 2.4规范中得到增强. 对Web应用来说 ,过滤器是 一个驻留在服务 ...
- Java Web之过滤器(Filter)
过滤器(Filter) 过滤器实际上就是对web资源进行拦截,做一些处理后再交给下一个过滤器或servlet处理 通常都是用来拦截request进行处理的,也可以对返回的response进行拦截处理 ...
- java web 开发应用 ----过滤器
过滤器的作用 1.当用户请求web资源时,如果没有过滤器,用户可以直接获取到这个web资源,当有了过滤器之后,当用户请求web资源时,web容器中的过滤器先会拦截到这个请求,然后根据这个请求 做相应的 ...
- Java Web之过滤器Filter(@WebFilter)
过滤器(Filter) 过滤器实际上就是对web资源进行拦截,做一些处理后再交给下一个过滤器或servlet处理 通常都是用来拦截request进行处理的,也可以对返回的response进行拦截处理 ...
- Java Web之Ajax
在之前的学习web前端专栏中已经对Ajax相关知识有过介绍了,不清楚的同学可以看一下这篇博客:从零开始学习WEB前端之数据交互(Ajax) 这里就不在赘述了. 但是之前是用PHP简单的搭了个环境,既然 ...
- java web三大组件之filter过滤器
过滤器是java web中相当重要的组成成分,是JavaWeb三大组件之一,它与Servlet很相似.不过过滤器有以下三条特性: 过滤器是用来拦截请求的,而不是处理请求的. 当用户请求某个Servle ...
最新文章
- A* 算法之父、人工智能先驱Nils Nilsson逝世 | 缅怀
- 从入职到离职创业,我在谷歌、亚马逊的八年
- 字符串的最大最小表示法 模板
- HDMI显示器驱动设计与验证
- ant中table表格的多选框如何清空
- 中国电网招聘 计算机岗位
- 图像旋转(信息学奥赛一本通-T1127)
- 北风设计模式课程---创建模式、结构模式、行为模式的区别
- 电子工程可以报考二建_二建报考要求是工程类专业怎么办?非工程类专业可以报名吗?...
- 软件测试完后,还有bug,责任全在于测试吗?
- AcWing 1236. 递增三元组 (flag + 前缀和 | 二分 | 滑动窗口)
- 1106冒泡排序语法树
- 系统学习机器学习之增强学习(一)--模型基础
- Lightroom 教程,如何将照片从 Lightroom 移至Photoshop,在 Ps 中合并图像?
- uniapp监听PDA激光扫描
- java gc loggc_java9中gc log参数迁移
- hyper运算符_查询构造器
- GeoDa空间计量(一)——空间权重矩阵的生成
- SCDM学习笔记(1)
- android 奥利奥功能,一加5/5T吃上Android 8.0奥利奥 这些新功能特性你不可不知
热门文章
- 队列和通知区别_Java多线程学习(五)——等待通知机制
- uni-app android白屏,uniapp页面跳转出现白屏怎么办
- 后台userlist.php,后台用户管理(管理员登录后管理会员)
- docker 启动容器的时候没-p 后面怎么加-p_基于Docker搭建基础自动化部署
- 中的枚举属性函数_对于 JavaScript 中循环之间的技术差异分析
- Python-Matplotlib可视化(4)——添加注释让统计图通俗易懂
- c+const_如何在C ++中使用const? 初学者指南
- java线程池示例_Java线程连接示例
- advanced installer 使用常见问题整理
- C++基础知识(八)例外、异常处理