Java Web——过滤器
《Java Web开发技术应用——过滤器》
过滤器是一个程序,它先于与之相关的servlet或JSP页面运行在服务器上。过滤器可附加到一个或多个servlet或JSP页面上,并且可以检查进入这些资源的请求信息。在这之后,过滤器可以作如下的选择:
①以常规的方式调用资源(即,调用servlet或JSP页面)。
②利用修改过的请求信息调用资源。
③调用资源,但在发送响应到客户机前对其进行修改。
④阻止该资源调用,代之以转到其他的资源,返回一个特定的状态代码或生成替换输出。
用户请求——>过滤器——>WEB资源——>过滤器——>用户
过滤器的生命周期
1.实例化 web.xml 在web容器启动时依据web.xml实例化
2.初始化 init()
3.过滤 doFilter()
4.销毁 destroy()
配置:
可以通过Design界面快速配置
过滤器需要实现接口javax.servlet.Filter,开始以为是类……找了好久……
需要实现三个方法
public void destroy() {}
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {}
public void init(FilterConfig arg0) throws ServletException {}
在doFilter中实现逻辑
如果多个过滤器对应一个路径
那么按照在web.xml的中定义的顺序执行过滤器
请求——>过滤器1——>过滤器2——>Servlet——>过滤器2——>过滤器1——>用户
过滤器的分类:(默认是request
ASYNC:Servlet中异步执行过滤器和业务逻辑内容。
ERROR:处理error-page
FORWARD:通过request.getRequestDispatcher("url").forward(request, response);或者<jsp:forward page="..."></jsp:forward>
INCLUDE:通过request.getRequestDispatcher("url").include(request, response);或者<jsp:include page="..."></jsp:include>
REQUEST:通过链接直接访问,或者通过response.sendRedirect("url");
在web.xml里面配置error-page
- <error-page>
- <error-code>404</error-code>
- <location>/error.jsp</location>
- </error-page>
在类上面通过注解配置过滤器
@WebFilter(filterName="...", value={"/....jsp"}, dispatcherTypes={DispatcherType.REQUEST, DispatcherType.ASYNC})
public class FilterName implements Filter {...}
案例:登录校验,如果没有登录,不能直接通过url访问登录后才能访问的页面
(突然发现右键有Servlet的选项,内心是崩溃的……窝每次都是新建java类……
- <%@ 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 '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>
- <%
- request.setCharacterEncoding("utf-8");
- %>
- <body>
- <form action="<%=request.getContextPath() %>/servlet/LoginServlet" method="post">
- 用户名:<input type="text" name="username">
- 密码:<input type="password" name="password">
- <input type="submit" value="提交">
- </form>
- </body>
- </html>
login.jsp
- package com.imooc.servlet;
- import java.io.IOException;
- import java.io.PrintWriter;
- import javax.servlet.ServletConfig;
- 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 {
- /**
- * 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");
- 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");
- return ;
- } else{
- //校验失败
- response.sendRedirect(request.getContextPath()+"/fail.jsp");
- return ;
- }
- }
- }
LoginServlet.java
- package com.imooc.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;
- @Override
- public void destroy() {
- // TODO Auto-generated method stub
- }
- @Override
- public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
- throws IOException, ServletException {
- HttpServletRequest request = (HttpServletRequest) arg0;
- HttpServletResponse response = (HttpServletResponse) arg1;
- String charset = config.getInitParameter("charset");
- if (charset == null) {
- charset = "utf-8";
- }
- request.setCharacterEncoding("utf-8");
- String noLoginPaths = config.getInitParameter("noLoginPaths");
- if (noLoginPaths != null) {
- String[] strArray = noLoginPaths.split(";");
- for (String s: strArray) {
- if (s != null && !s.equals("") && request.getRequestURL().indexOf(s) != -1) {
- arg2.doFilter(arg0, arg1);
- return;
- }
- }
- }
- HttpSession session = request.getSession();
- if (session.getAttribute("username") != null) {
- arg2.doFilter(arg0, arg1);
- } else {
- response.sendRedirect("login.jsp");
- }
- }
- @Override
- public void init(FilterConfig arg0) throws ServletException {
- // TODO Auto-gegnerated method stub
- config = arg0;
- }
- }
LoginFilter.java
- <?xml version="1.0" encoding="UTF-8"?>
- <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">
- <display-name>LoginFilter</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.imooc.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.html</welcome-file>
- <welcome-file>index.htm</welcome-file>
- <welcome-file>index.jsp</welcome-file>
- <welcome-file>default.html</welcome-file>
- <welcome-file>default.htm</welcome-file>
- <welcome-file>default.jsp</welcome-file>
- </welcome-file-list>
- <filter>
- <filter-name>LoginFilter</filter-name>
- <filter-class>com.imooc.filter.LoginFilter</filter-class>
- <init-param>
- <param-name>noLoginPaths</param-name>
- <param-value>login.jsp;fail.jsp;LoginServlet</param-value>
- </init-param>
- <init-param>
- <param-name>charaset</param-name>
- <param-value>GBK</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>LoginFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- </web-app>
web.xml
Java Web——过滤器的更多相关文章
- java web 过滤器跟拦截器的区别和使用
注:文章整理自知乎大牛以及百度网友(电脑网络分类达人 吕明),特此感谢! 一.过滤器 1.什么是过滤器? 过滤器是一个程序,它先于与之相关的servlet或JSP页面运行在服务器上.过滤器可附加到一个 ...
- java web过滤器实际应用(解决中文乱码 html标签转义功能 敏感字符过滤功能)
转载地址:http://www.cnblogs.com/xdp-gacl/p/3952405.html 在filter中可以得到代表用户请求和响应的request.response对象,因此在编程中可 ...
- java web过滤器防止未登录进入界面
import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import ja ...
- JAVA WEB 过滤器(Filter)中向容器 Spring 注入 bean
如果直接使用 @Autoware 获取 bean 会直接使该 bean 为 null,这是因为这种配置过滤器的方法无法在过滤器中使用 Spring bean,因为 Filter 比 bean 先加载, ...
- java Web 过滤器Filter详解
简介 Filter也称之为过滤器,Web开发人员通过Filter技术,对web服务器管理的所有web资源:例如Jsp, Servlet, 静态图片文件或静态 html 文件等进行拦截,从而实现一些特殊 ...
- Java Web 中 过滤器与拦截器的区别
过滤器,是在java web中,你传入的request,response提前过滤掉一些信息,或者提前设置一些参数,然后再传入servlet或者struts的 action进行业务逻辑,比如过滤掉非法u ...
- 初学Java Web(8)——过滤器和监听器
什么是过滤器 过滤器就是 Servlet 的高级特性之一,就是一个具有拦截/过滤功能的一个东西,在生活中过滤器可以是香烟滤嘴,滤纸,净水器,空气净化器等,在 Web 中仅仅是一个实现了 Filter ...
- JAVA WEB 三器之过滤器(Filter)
过滤器(Filter) 1. 简介 过滤器可以动态地拦截请求和响应,以变换或使用包含在请求或响应中的信息,它是 Servlet 技术中最实用的技术,属于系统级别,主要是利用函数的回调实现.对 Jsp, ...
- SpringMVC内容略多 有用 熟悉基于JSP和Servlet的Java Web开发,对Servlet和JSP的工作原理和生命周期有深入了解,熟练的使用JSTL和EL编写无脚本动态页面,有使用监听器、过滤器等Web组件以及MVC架构模式进行Java Web项目开发的经验。
熟悉基于JSP和Servlet的Java Web开发,对Servlet和JSP的工作原理和生命周期有深入了解,熟练的使用JSTL和EL编写无脚本动态页面,有使用监听器.过滤器等Web组件以及MVC架构 ...
随机推荐
- easyui改变tab标题
截图: 代码: //更改tab的标题 var tab = $('#microAppVersionTabs').tabs('getTab',0);// 取得第一个tab $('#microAppVe ...
- linux上部署Appach,让文件目录以网页列表形式访问
效果: 1.首先,需要安装Apache httpd服务 yum install -y httpd 2.查看或者设置httpd主配文件 vim /etc/httpd/conf/htpd.conf 从中可 ...
- PhoenixFD插件流体模拟——UI布局【Simulation】详解
前言 之前使用RealFlow做流体模拟,但是总得和3ds导来导去,略显麻烦,特意学习PhoenixFD插件,直接在3ds中进行流体模拟.若读者有更好的流体模拟方法,欢迎在评论区交流. 原文地址:ht ...
- 11. Container With Most Water (JAVA)
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). ...
- FortiGate防火墙HA下联堆叠交换机
1.拓扑图 2.防火墙配置 3.交换机配置 interface GigabitEthernet1/0/47 switchport access vlan 30 switchport mode acce ...
- Java日志框架-logback的介绍及配置使用方法(纯Java工程)(转)
说明:内容估计有些旧,2011年的,但是大体意思应该没多大变化,最新的配置可以参考官方文档. 一.logback的介绍 Logback是由log4j创始人设计的又一个开源日志组件.logback当前分 ...
- js 加减乘除失精
js 计算失精是因为js 先将10十进制代码转化为2进制,再计算导致 具体解决方案: 1. 加 function accAdd(arg1,arg2){ var r1,r2,m; ].length}} ...
- Java线程池的构造以及使用
有时候,系统需要处理非常多的执行时间很短的请求,如果每一个请求都开启一个新线程的话,系统就要不断的进行线程的创建和销毁,有时花在创建和销毁线程上的时间会比线程真正执行的时间还长.而且当线程数量太多时, ...
- angularjs1.x的directive中的link参数element见解
angular.module("APP",[]) .directive("testDw",function () { return{ restrict:&quo ...
- css3回顾 checkbox
<div class="checkBox"> <input type="checkbox" id="check1"> ...