在本文中
User的結構是:
public class User {
private int id;
private String name;
private String password;
private Set<String> groups = new HashSet<String>();
}
UserGroup表:
user:intgroup:String使用聯合主鍵
Hibernate映射文件是:
<hibernate
<class name=
<cache usage=
<id name=
<generator class=
</id>
<property name=
<property name=
<set name=
<key column=
<element column=
</set>
</class>
</hibernate
一切的身份驗證交給一個繼承HandlerInterceptorAdapter的類來做:
import org
import org
import org
import org
public class AuthorizeInterceptor extends HandlerInterceptorAdapter {
private UrlPathHelper urlPathHelper = new UrlPathHelper();
private PathMatcher pathMatcher = new AntPathMatcher();
private Properties groupMappings;
/** * Attach URL paths to group
public void setGroupMappings(Properties groupMappings) {
this
}
public boolean preHandle(HttpServletRequest request
String url = urlPathHelper
String group = lookupGroup(url);
// 找出資源所需要的權限
if(group == null){
// 所請求的資源不需要保護
return true;
}
// 如果已經登錄
User loginUser = (User)request
ModelAndView mav = new ModelAndView(
if(loginUser == null){
mav
throw new ModelAndViewDefiningException(mav);
}else{
if(!loginUser
mav
throw new ModelAndViewDefiningException(mav);
} return true;
}
}
/* * 查看
org
* Ant模式的最長子串匹配法
*/
private String lookupGroup(String url){
String group = groupMappings
if (group == null) {
String bestPathMatch = null;
for (Iterator it = this
String registeredPath = (String) it
if (this
group = this
bestPathMatch = registeredPath;
}
}
}
return group;
}
}
下面我們需要在Spring的應用上下文配置文件中設置:
<bean id=
<property name=
<value>
<!
/admin/*=admin
</value>
</property>
</bean>
<bean id=
<property name=
<list>
<ref bean=
</property>
<property name=
<value>
/index
</value>
</property>
</bean>
注意到
From:http://tw.wingwit.com/Article/program/Java/ky/201311/28877.html