Java Web——过滤器
Posted 我不吃饼干呀
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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>
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 ; } } }
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; } }
<?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>
以上是关于Java Web——过滤器的主要内容,如果未能解决你的问题,请参考以下文章
[原创]java WEB学习笔记61:Struts2学习之路--通用标签 property,uri,param,set,push,if-else,itertor,sort,date,a标签等(代码片段