2012-01-18 97 views
1

我已經構建了一個可以正常工作的簡單SpringMVC登錄系統,但是我想限制頁面只表示只有使用有效登錄才能看到它們。如果我只用JSP我會檢查...SpringMVC需要登錄才能使用會話查看頁面

if (login.equals("admin") && password.equals("guess")) { 
     // Valid login 
     session.setAttribute("authorized", "yes"); 
} else { 
     // Invalid login 
     session.setAttribute("authorized", "no"); 
} 

但我怎麼在全球範圍內我用SpringMVC中的應用程序設置,如果組servlet可以通過會話訪問?我可以設置會話沒問題,但在SpringMVC中,我的會話處理是在控制器或servlet-context.xml(甚至是web.xml)上完成的,因此我可以檢查「如果用戶登錄顯示此頁面,否則網頁「。

我的login.jsp是一個非常簡單的...

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 
<%@ page session="true" %> 
<html> 
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> 
<head> 
    <title>Login</title> 
</head> 
<body> 
<h1> 
    Hello please login to this application 
</h1> 
<script> 

     function login(){ 
      var username = $("#username").val(); 
      var password = $("#password").val(); 

      $.post('login', { username : username , password : password }, function(data) { 
       $('#results').html(data).hide().slideDown('slow'); 
      }); 
     } 

</script> 
Username : <input id="username" type="text" /> 
Password : <input id="password" type="password" /> 
<input name="send" type="submit" value="Click me" onclick="login()" /> 
<form name="next" action="auth/details" method="get"> 
    <input name="send" type="submit" value="Go Through"/> 
</form> 
<div id="results" /> 
</body> 
</html> 

我只是想在AUTH /細節控制器有返回的詳細信息,如果用戶已經登錄,什麼是這個最好的方法?餅乾/會議等?

感謝,

大衛

回答

2

看起來像重新發明輪子。 Spring Security已經處理了你的情況,並在web.xml(定義一個servlet過濾器)和一些基本配置的XML幾行限制訪問選定的URL,提供登錄/註銷屏幕,處理用戶存儲和HTTP會話管理。

雖然號稱是非常複雜的,默認配置(auto)就足以啓動:

<http auto-config='true'> 
    <intercept-url pattern="/**" access="ROLE_USER" /> 
</http> 

tutorial。現在,Apache Shiro似乎也獲得了很多牽引力。

如果出於某種原因,您不想將Spring Security引入到您的堆棧中,Spring MVC interceptors是實現交叉安全邏輯的好地方。您可以訪問原始請求和響應,因此您可以發現URL並檢查HTTP會話。

0

看一看的Spring Security JSP Taglib。一旦配置,它可以讓你做的事情,如

<sec:authorize access="hasRole('user')"> 
    Only logged in users will see this. 
</sec:authorize>