1.工程说明
通常在一个网站中,用户想要访问一些信息,需要用户是我们网站中注册过的用户,才有这个权限看到这些信息。
比如说:在一个学校的教育管理系统中,你想看到该学校的课程信息MyClassInfor.jsp,必须先登录验证通过才能访问站内的资源,如果你直接访问MyClassInfor.jsp这个页面,那么系统一般会跳转到登录页面让你去登录。
这一个过程就是过滤器要做的:你想访问这个网站,但是要把你过滤一遍,看你是否有相应的权限,再做出相应的响应。
因此在本次实战中,就要求当用户访问我们的主页面的时候,需要用过滤器验证一下其是否登录过,要是其登陆过就能直接访问,否则跳转到登录界面中去。
2.项目介绍
接下来介绍一下在工程中用到的几个文件所代表的含义:
1.主页面:welcome.jsp
2.登录界面:login.jsp
3.登录失败界面:failure.jsp
4.路径都输错了进入的界面404:error.jsp
5.用户的登录验证使用一个servlet来处理:DoLoginServlet
6.创建过滤器LoginFilter,web.xml中注册过滤器
3.效果演示
a.首先访问我们的主页面welcome.jsp-->http://localhost:8080/LoginDemo_Filter/welcome.jsp
但是过滤器会过滤用户的请求,发现其未登陆过,所以跳转到了login.jsp,地址栏中的地址也发生了改变
b.登录(默认用户名和密码都是admin)-->正确登录-->跳转到主页面
c.登录失败的话,跳转到failure.jsp页面
d.以上就是整个工程的主要用到的界面,那么error.jsp是用来干什么的呢?有时候我们可能在地址栏中输入地址的时候发生错误(少输或者多数一个字符),那么error.jsp就是当用户输入错误地址的时候提示的一个页面,以增加用户交互的友好度。
ok,那我们输入一个错误的地址看一下运行的效果吧~
4.工程代码
4.1 主页面:welcome.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 'welcome.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>
<center>
<h1>嗨,你好~我是主界面!</h1>
<hr>
恭喜 ${username } ~成功访问了我~
</center>
</body>
</html>
4.2 登录界面:login.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 'welcome.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>
<center>
<h1>登录界面</h1>
<hr>
<br><br><br><br><br>
<form action="servlet/DoLoginServlet" method="post" name="infor">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="登录"></td>
</tr>
</table>
</form>
</center>
</body>
</html>
4.3 登录失败界面:failure.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 'welcome.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>
<center>
<h1>不好意思,登录失败!</h1>
<hr>
看来你不是我们的用户,你想干什么?<br><br><br><br><br>
<a href="login.jsp">想再登录一次?好给你机会</a><br>
</center>
</body>
</html>
4.4 路径都输错了进入的界面404:error.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 'welcome.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>
<center>
<h1>我的天呐!您既然访问了错误的路径!!!</h1>
<hr>
老铁,再检查一下路径对不对吧!<br><br><br><br><br>
<a href="welcome.jsp">我是快速通道,点我直接访问吧~</a><br>
</center>
</body>
</html>
4.5 用户的登录验证的servlet:DoLoginServlet
package servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/*
* 2018.5.11
* @author Dragon
* 功能:验证用户登录并响应相应的请求
*/
public class DoLoginServlet extends HttpServlet {
public DoLoginServlet() {
super();
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
//让doGet做doPost的工作
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
System.out.println("doPost开始执行");
String name=request.getParameter("username");
String password=request.getParameter("password");
//如果用户名和密码登录成功
if("admin".equals(name) && "admin".equals(password))
{
HttpSession session = request.getSession();
session.setAttribute("username", name);
response.sendRedirect(request.getContextPath()+"/welcome.jsp");
}else{
response.sendRedirect(request.getContextPath()+"/failure.jsp");
}
}
public void init() throws ServletException {
}
}
4.6 创建过滤器LoginFilter
package 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.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet Filter implementation class LoginFilter
*/
@WebFilter("/LoginFilter")
public class LoginFilter implements Filter {
/**
* Default constructor.
*/
public LoginFilter() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException
{
HttpServletRequest request = (HttpServletRequest) arg0;
HttpServletResponse response = (HttpServletResponse) arg1;
HttpSession session = request.getSession();
//验证该用户是否登陆过
if(session.getAttribute("username")!=null){
arg2.doFilter(arg0, arg1);
}else{
response.sendRedirect("login.jsp");
}
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
4.7 web.xml中注册过滤器
<?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>LoginDemo_Filter</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>DoLoginServlet</servlet-name>
<servlet-class>servlet.DoLoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DoLoginServlet</servlet-name>
<url-pattern>/servlet/DoLoginServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>welcome.html</welcome-file>
<welcome-file>welcome.htm</welcome-file>
<welcome-file>welcome.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<error-page>
<error-code>404</error-code>
<location>/error.jsp</location>
</error-page>
<filter>
<filter-name>LoginFilter</filter-name>
<filter-class>filter.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>/welcome.jsp</url-pattern>
</filter-mapping>
</web-app>
在我们的web.xml文件中,红色部分是注册servlet中的,绿色部分是我们输入错误路径的时候发生404错误需要的配置的地方,蓝色部分是我们过滤器需要配置的内容。
5.小结
这是过滤器创建并使用的一个简单的小demo,该工程演示了如何过滤一个路径的实例。其中需要注意一下几个方面:
1.如何使用过滤器
写一个过滤器然后在web.xml中注册->其要过滤的路径在注册的时候写明
2.servlet中各个对象获取的方法
request:HttpServletRequest request
response:HttpServletResponse response
session:HttpSession session = request.getSession();
3.servlet中页面的跳转
重定向:response.sendRedirect(request.getContextPath+"test.jsp");
服务器内部跳转:request.getRequestDispatcher("/test.jsp").forward(request,response);