通常我們在點擊某個按鈕的時候,對某個對象進行操作,是需要登陸才能做的,這時候就需要一個攔截器對某個方法進行攔截,
比如你在一個圖書管理中心中你要借書,這時候你就會被要求出示借書證,管理員才能借書給你。而攔截器就具有這樣的功能
:游客點擊借書按鈕-->后台攔截器攔截該方法-->判斷你是否登陸-->已經登陸-->允許操作-->沒登陸-->請登陸-->允許操作
代碼如下:
UserFiler.java
package com.utis.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 UserFiter implements Filter{ public void init(FilterConfig filterConfig) throws ServletException { // TODO Auto-generated method stub } public void destroy() { // TODO Auto-generated method stub } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //獲取HttpSession對象,判斷是否登陸 HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; HttpSession session = req.getSession(); if(session.getAttribute("model")==null){ //非法訪問,沒有登陸,跳轉到登陸頁面 session.setAttribute("error", "非法訪問"); // 保存客戶想要去的地址, 登錄成功后則直接跳轉,而不是到首頁 String goURL = req.getServletPath();//(獲取到地址不包括參數) //判斷參數是否為空,不null就獲取參數 if(req.getQueryString()!=null){ goURL+="?"+req.getQueryString(); } session.setAttribute("goURL", goURL); res.sendRedirect(req.getContextPath() + "/user/userLogin.jsp"); }else{ // 如果有下一個過濾器則跳轉到下一個過濾器否則目標頁面 chain.doFilter(request, response); } } }
web.xml
<filter>
<!-- 配置在web.xml的攔截器,在容器啟動的時候一起啟動 --> <filter-name>userFilter</filter-name> <filter-class>com.utis.filter.UserFiter</filter-class> </filter> <filter-mapping> <filter-name>userFilter</filter-name> <url-pattern>/book/*</url-pattern> </filter-mapping>
UserContrller.java
/** * 用戶登陸功能 * @return */ @RequestMapping(value="login",method=RequestMethod.POST) public ModelAndView userLogin(@Valid User user,HttpServletRequest request,HttpServletResponse response){ Map<String, Object> maplist = new HashMap<String, Object>(); HttpSession session = request.getSession(); User model = userService.findUser(user); if(model != null && !model.equals("")){ session.setAttribute("model", model); maplist.put("model", model); return new ModelAndView("index","maplist",maplist); }else{ request.setAttribute("message", "用戶或密碼錯誤!"); return new ModelAndView("user/userLogin"); } }
userLogin.jsp
<html> <head> <title>登陸頁面</title> </head> <body> <center> <h1>登陸頁面</h1> <table> <form action="login" method="post"> 用戶名:<input type="text" class="username" name="username"/><br/> 密 碼:<input type="password" class="password" name="password"/><br/> <input type="submit" value="登陸"><br/> </form> ${message} </table> </center> </body> </html>
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <% 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>首頁</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> <c:choose> <c:when test="${empty sessionScope.model}"> <a href="<%=basePath%>user/userLogin.jsp">登陸</a> <a href="<%=basePath%>user/userRegister.jsp">注冊</a> </c:when> <c:otherwise> 歡迎使用圖書管理系統:${sessionScope.model.username } </c:otherwise> </c:choose> <c:if test="${booklist ne '' && booklist != null}"> <!-- 作為隱藏的傳遞參數 --> <table border="1" style="border-collapse: collapse; border-color: blue;"> <!-- 表頭 --> <tr> <th> 書名 </th> <th> 出版社 </th> <th> 是否可借 </th> <th> 數量 </th> <th> 操作 </th> </tr> <!-- 顯示數據列表 --> <c:forEach items="${booklist}" var="book"> <tr> <td> ${book.bookname } </td> <td> ${book.chubanshe } </td> <td> ${book.state } </td> <td> ${book.number } </td> <td> <a href="book/borrowBook?bookid=${book.bookid }&userid=${sessionScope.model.userid }">借書</a> </td> </tr> </c:forEach> <!-- 其他操作 --> <tr> <td colspan="7"> <a href="#">添加</a> </td> </tr> </table> </c:if> </CENTER> </body> </html>
初始化數據
IniDataListener.java
package com.booksys.listener; import java.util.Timer; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import org.springframework.context.ApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import com.booksys.service.BookService; import com.utis.util.GoodsTimerTask; /** * 該類的主要作用是用於加載index首頁的方法,查詢數據,顯示首頁 * @author chunyu * */ public class InitDataListener implements ServletContextListener{ private BookService bookService; private GoodsTimerTask goodsTimerTask; public void contextDestroyed(ServletContextEvent sce) { } public void contextInitialized(ServletContextEvent event) { ApplicationContext context = null; //通過spring的web工具類來加載spring容器(配置文件),並且調用某個類來做某事 context=WebApplicationContextUtils.getWebApplicationContext(event.getServletContext()); //1、獲取bookservice bookService = (BookService) context.getBean("bookService"); goodsTimerTask = (GoodsTimerTask) context.getBean("goodsTimerTask"); //2、查詢所有圖書 event.getServletContext().setAttribute("booklist", bookService.findBook()); //將Application內置對象,傳入到goodsTimerTask查詢的數據對象中 goodsTimerTask.setApplication(event.getServletContext()); // 設置時間任務,每隔一段時間加載首頁的商品信息, 此線程必須設置守護線程, 主線程停止的時候此線程也要停止 new Timer(true).schedule(goodsTimerTask, 0,1000*60); } }
web.xml
<!-- 初始化首頁信息(查詢)監聽器 --> <listener> <listener-class> com.booksys.listener.InitDataListener </listener-class> </listener>
時間戳:用於自動調用查詢方法,更新首頁數據顯示
GoodsTimerTask.java
package com.utis.util; import java.util.List; import java.util.TimerTask; import javax.annotation.Resource; import javax.servlet.ServletContext; import org.springframework.stereotype.Component; import com.booksys.domain.Book; import com.booksys.service.BookService; @Component("goodsTimerTask") public class GoodsTimerTask extends TimerTask { //傳入Application內置對象 private ServletContext application; public void setApplication(ServletContext application) { this.application = application; } //獲取業務邏輯類 @Resource private BookService bookService=null; @Override public void run() { System.out.println("GoodsTimerTask.run()"); //首頁加載圖書數據信息 List<Book> booklist = bookService.findBook(); //將list集合數據存儲到app內置對象中,在inde前台通過循環查詢出來 application.setAttribute("booklist", booklist); } }