springmvc攔截器登錄驗證示例
一開始,學(xué)了攔截器與過濾器,咋一看兩者有點(diǎn)像,實(shí)際上兩者有很大的不同。就用攔截器和過濾器分別做了登錄驗證試驗,這次先說攔截器。下面是自己實(shí)踐的一個實(shí)例:
在spring-mvc.xml中配置攔截器:
<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/user/*"/> <!-- 定義在mvc:interceptor下面的表示是對特定的請求才進(jìn)行攔截的 --> <bean class="com.wyb.interceptor.LoginInterceptor"/> </mvc:interceptor> </mvc:interceptors>
如上所示,這里配置了LoginIntercepter,為了簡單起見,該過濾器只攔截了URL為"/user/*"的請求。
要攔截的請求對應(yīng)控制器如下:
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.wyb.domain.User;
import com.wyb.service.IUserService;
import com.wyb.service.impl.UserServiceImpl;
@Controller
@RequestMapping("/user")
public class UserController {
private static final Logger LOG=Logger.getLogger(UserController.class);
@Autowired
private IUserService userService;
@RequestMapping("/showAllUser")
public String showAllUser(Model m){
List<User> userlist=new ArrayList<User>();
userlist=userService.findAllUser();
for(User user :userlist){
System.out.println(user.getUserName());
}
return "/jsp/showAllUser";
}
}
這里的showAllUser()方法是為了輸出所有的用戶,為了表明執(zhí)行了方法,將所有用戶在后臺打印,URL為:http://localhost:8080/TestSSM/user/showAllUser,可見該URL肯定會被LoginIntercepter攔截。
測試頁面showAllUser.jsp如下:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>show All User</title> </head> <body> this is showAllUser Page!!! </body> </html>
LoginIntercepter如下:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.wyb.domain.User;
public class LoginInterceptor implements HandlerInterceptor{
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
System.out.println("this is afterCompletion of LoginInterceptor");
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
System.out.println("this is postHandle of LoginInterceptor");
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
// TODO Auto-generated method stub
System.out.println("this is preHandle of LoginInterceptor");
HttpSession session=request.getSession();
User user=(User)session.getAttribute("user");
if(user==null){
System.out.println("no user in LoginInterceptor!!!");
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
}
//返回true代表繼續(xù)往下執(zhí)行
return true;
}
}
這里我犯了一個錯誤,聰明的小伙伴也許已經(jīng)看出來了,如果按照上面的代碼,當(dāng)我們訪問:http://localhost:8080/TestSSM/user/showAllUser結(jié)果如下:

咋一看,成功攔截了,輸入用戶名信息,正常跳轉(zhuǎn)到主頁,再次進(jìn)入http://localhost:8080/TestSSM/user/showAllUser如下:

頁面正常輸出,已經(jīng)記錄了session,不會被再次攔截,看似成功了,可是看看后臺輸出:

有沒有發(fā)現(xiàn),我們執(zhí)行了兩次showAllUser()方法,可見第一次訪問雖然被攔截器攔截了下來進(jìn)入登錄頁面,但后臺已經(jīng)悄悄執(zhí)行了showAllUser()。為什么呢?我們回頭再看看LoginIntercepter.java,尤其是preHandle()方法:
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
// TODO Auto-generated method stub
System.out.println("this is preHandle of LoginInterceptor");
HttpSession session=request.getSession();
User user=(User)session.getAttribute("user");
if(user==null){
System.out.println("no user in LoginInterceptor!!!");
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
}
//返回true代表繼續(xù)往下執(zhí)行
return true;
}
在判斷user為空后,雖然執(zhí)行了頁面跳轉(zhuǎn),但是程序還是會繼續(xù)執(zhí)行,最后返回true,返回true意味著,被攔截的業(yè)務(wù)邏輯可以繼續(xù)往下執(zhí)行,因此,雖然表面上被攔截了,但從本質(zhì)上來說并沒有攔截到。因此需要修改如下:
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
// TODO Auto-generated method stub
System.out.println("this is preHandle of LoginInterceptor");
HttpSession session=request.getSession();
User user=(User)session.getAttribute("user");
if(user==null){
System.out.println("no user in LoginInterceptor!!!");
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
//本次訪問被攔截,業(yè)務(wù)邏輯不繼續(xù)執(zhí)行
return false;
}
//返回true代表繼續(xù)往下執(zhí)行
return true;
}
user為空,跳轉(zhuǎn)后,返回false,就不會執(zhí)行被攔截的業(yè)務(wù)邏輯了,修改后后臺輸出如下:

現(xiàn)在后臺正常輸出,且session保存了user信息后,才能執(zhí)行showAllUser()方法,大功告成!
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java實(shí)現(xiàn)通訊錄管理系統(tǒng)項目
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)通訊錄管理系統(tǒng)項目,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-11-11
SpringSecurity實(shí)現(xiàn)踢出指定用戶的示例
SpringSecurity中使用SessionRegistryImpl類可以獲取session信息并踢出用戶,這篇文章主要介紹了SpringSecurity實(shí)現(xiàn)踢出指定用戶的示例,需要的朋友可以參考下2025-03-03
Java FTPClient實(shí)現(xiàn)文件上傳下載
這篇文章主要為大家詳細(xì)介紹了Java FTPClient實(shí)現(xiàn)文件上傳下載的相關(guān)資料,需要的朋友可以參考下2016-04-04
Spring如何動態(tài)自定義logback日志目錄詳解
這篇文章主要給大家介紹了關(guān)于Spring如何動態(tài)自定義logback日志目錄的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-10-10
SpringBoot中application.yml配置文件的寫法
這篇文章主要介紹了SpringBoot中application.yml配置文件的寫法,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-07-07

