xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
contextConfigLocation
classpath:applicationContext*.xml
chinese
com.filter.EncodingFilter
loginFilter
com.filter.LoginFilter
sessionKey
LOGIN_NAME
redirectURL
/user/login.htm
notCheckURLList
/user/login.htm;/user/my.htm;
openSession
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
/**
* @Discription: 登陆过滤器:
* 用于检测用户是否登陆的过滤器,如果未登录,则重定向到指的登录页面
* 配置参数:
* sessionKey:需检查的在 Session 中保存的关键字
* redirectURL:如果用户未登录,则重定向到指定的页面,URL不包括 ContextPath
* notCheckURLList:不做检查的URL列表,以分号分开,并且 URL 中不包括 ContextPath
* @Project: SpringSecurity
* @Package: com.filter
* @Title: LoginFilter.java
* @author: [heyong]
* @date 2012-4-21
* @version 1.0
* @update [日期YYYY-MM-DD] [更改人姓名]
*/
public class LoginFilter implements Filter{
/**
* Discription:[logger日志]
*/
private static Log logger = LogFactory.getLog(LoginFilter.class);
/**
* Discription:[需检查的在 Session 中保存的关键字]
*/
private String sessionKey = null;
/**
* Discription:[如果用户未登录,则重定向到指定的页面,URL不包括 ContextPath ]
*/
private String redirectURL = null;
/**
* Discription:[不做检查的URL列表,以分号分开,并且 URL 中不包括 ContextPath]
*/
private List notCheckURLList = new ArrayList();
public void destroy() {
notCheckURLList.clear();
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
// 获得Session
HttpSession session = request.getSession();
// 判断sessionKey 是否为空
if(StringUtils.isEmpty(sessionKey)){
filterChain.doFilter(request, response);
return;
}
if (!checkRequestURIIntNotFilterList(request)) {
UserDetail userDetail = null;
try {
// 取得当前用户登陆的信息
userDetail = (UserDetail)SpringSecurityUtils.getCurrentUser();
} catch (Exception e) {
logger.info("Event=[LoginFilter#doFilter] redirect:".concat(request.getContextPath().concat(redirectURL)));
response.sendRedirect(request.getContextPath().concat(redirectURL));
return;
}
// 判断是否登陆
if (userDetail == null || userDetail.getUserId() == null) {
response.sendRedirect(request.getContextPath().concat(redirectURL));
return;
}
// 在userDetail中得到用户信息
SysStUser user = userDetail.getCurrentUser();
// UserDetail 存在,测检查Session是否存在,若不存在则,初始化Session
if (session.getAttribute(sessionKey) == null) {
logger.info("Event=[LoginFilter#doFilter] sessionKey: " + sessionKey);
session.setAttribute(sessionKey, user);
}
}
filterChain.doFilter(servletRequest, servletResponse);
}
public void init(FilterConfig filterConfig) throws ServletException {
sessionKey = filterConfig.getInitParameter("sessionKey");
redirectURL = filterConfig.getInitParameter("redirectURL");
String urlList = filterConfig.getInitParameter("notCheckURLList");
if (StringUtils.isNotEmpty(urlList)) {
StringTokenizer st = new StringTokenizer(urlList, ";");
notCheckURLList.clear();
while (st.hasMoreTokens()) {
notCheckURLList.add(st.nextToken());
}
}
}
/**
* @Description: 检测当前访问URL,是否有过滤掉的URL。
* @author [heyong]
* @date 2012-4-21
* @version 1.0
* @param request
* @return
* @update:[日期YYYY-MM-DD] [更改人姓名]
*/
private boolean checkRequestURIIntNotFilterList(HttpServletRequest request) {
String url = request.getServletPath() + (request.getPathInfo() == null ? "" : request.getPathInfo());
return notCheckURLList.contains(url);
}
}
第3步:提供一个UserDetail.java,该类继承org.springframework.security.userdetails.User类,用于保存一些自定义的业务数据,具体如下:
/**
* @Discription: UserDetail继承User
* @Project: SpringSecurity
* @Package: com.security
* @Title: UserDetail.java
* @author: [heyong]
* @date 2012-4-21
* @version 1.0
* @update [日期YYYY-MM-DD] [更改人姓名]
*/
public class UserDetail extends User {
/**
* Discription:[serialVersionUID]
*/
private static final long serialVersionUID = 5533186529087001787L;
/**
* 用户ID
*/
private String userId;
/**
* 用户真实姓名
*/
private String realName;
/**
* 当前登录的用户信息
*/
private SysStUser currentUser;
public UserDetail(String userId, String realName, String username,String password, GrantedAuthority[] authorities) {
super(username, password, true, true, true, true, authorities);
this.userId = userId;
this.realName = realName;
}
public UserDetail(String username, String password, boolean enabled,
boolean accountNonExpired, boolean credentialsNonExpired,
boolean accountNonLocked, GrantedAuthority[] authorities)throws IllegalArgumentException {
super(username, password, enabled, accountNonExpired,credentialsNonExpired, accountNonLocked, authorities);
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public SysStUser getCurrentUser() {
return currentUser;
}
public void setCurrentUser(SysStUser currentUser) {
this.currentUser = currentUser;
}
}
/**
* @Discription: UserDetailsServiceImpl实现UserDetailsService接口,实现UserDetailsService类中loadUserByUsername()方法
* @Project: SpringSecurity
* @Package: com.iservices
* @Title: UserDetailsServiceImpl.java
* @author: [heyong]
* @date 2012-4-20
* @version 1.0
* @update [日期YYYY-MM-DD] [更改人姓名]
*/
public class UserDetailsServiceImpl implements UserDetailsService{
/**
* 用户信息Services(自已提供查询Services查询接口)
*/
private UsersServices usersServices;
/**
* @Description: 实现loadUserByUsername(),根据用户名明查询用户的信息
* @author [heyong]
* @date 2012-4-20
* @version 1.0
* @param LoginName:登陆用户名
* @return
* @throws UsernameNotFoundException
* @throws DataAccessException
* @update:[日期YYYY-MM-DD] [更改人姓名]
*/
public UserDetails loadUserByUsername(String LoginName)throws UsernameNotFoundException, DataAccessException {
SysStUser sysStUser = usersServices.searchSysUserByLoginName(LoginName);
if (sysStUser != null) {
UserDetail userdetail = new UserDetail(sysStUser.getId(), sysStUser.getUserRname(),sysStUser.getUserName(),sysStUser.getUserPwd(),new GrantedAuthority[0]);
userdetail.setCurrentUser(sysStUser);
return userdetail;
}
return null;
}
public void setUsersServices(UsersServices usersServices) {
this.usersServices = usersServices;
}
}
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.4.xsd"
default-autowire="byType" default-lazy-init="true">
SpringSecurity安全配置
用户登陆-SpringSecurity安全配置Demo