发布网友 发布时间:2022-04-23 00:03
共2个回答
热心网友 时间:2023-10-09 02:00
public class User {
private int id;
private String name;
private String passWord;
private Set<String> groups = new HashSet<String>();
}
UserGroup表:
user:intgroup:String使用联合主键, 在java中没有对应的类。
Hibernate映射文件是:
<hibernate-mapping auto-import="true" default-lazy="false">
<class name="net.ideawu.User" table="User">
<cache usage="read-write" />
<id name="id" column="id">
<generator class="native"/>
</id>
<property name="name" column="name"/>
<property name="password" column="password"/>
<set name="groups" table="UserGroup" cascade="save-update" lazy="false">
<key column="user" />
<element column="`group`" type="string" />
</set>
</class>
</hibernate-mapping>
一切的身份验证交给一个继续HandlerInterceptorAdapter的类来做:
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.UrlPathHelper;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
...
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.groupMappings = groupMappings;
}
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String url = urlPathHelper.getLookupPathForRequest(request);
String group = lookupGroup(url);
// 找出资源所需要的权限, 即组名
if(group == null){
// 所请求的资源不需要保护.
return true;
}
// 假如已经登录, 一个User实例被保存在session中.
User loginUser = (User)request.getSession().getAttribute("loginUser");
ModelAndView mav = new ModelAndView("system/authorizeError");
if(loginUser == null){
mav.addObject("errorMsg", "你还没有登录!");
throw new ModelAndViewDefiningException(mav);
}else{
if(!loginUser.getGroups().contains(group)){
mav.addObject("errorMsg", "授权失败! 你不在 <b>" + group + "</b> 组!");
throw new ModelAndViewDefiningException(mav);
} return true;
}
}
/* * 查看
org.springframework.web.servlet.handler.AbstractUrlHandlerMapping.lookupHandler()
* Ant模式的最长子串匹配法.
*/
private String lookupGroup(String url){
String group = groupMappings.getProperty(url);
if (group == null) {
String bestPathMatch = null;
for (Iterator it = this.groupMappings.keySet().iterator();it.hasNext();) {
String registeredPath = (String) it.next();
if (this.pathMatcher.match(registeredPath, url) && (bestPathMatch == null bestPathMatch.length() <= registeredPath.length())) {
group = this.groupMappings.getProperty(registeredPath);
bestPathMatch = registeredPath;
}
}
}
return group;
}
}
热心网友 时间:2023-10-09 02:00
springSecurity!!