登录流程

1)容器启动(MySecurityMetadataSource:loadResourceDefine加载系统资源与权限列表)

 2)用户发出请求

 3)过滤器拦截(MySecurityFilter:doFilter)

 4)取得请求资源所需权限(MySecurityMetadataSource:getAttributes)

 5)匹配用户拥有权限和请求权限(MyAccessDecisionManager:decide),如果用户没有相应的权限,

执行第6步,否则执行第7步。

 6)登录

 7)验证并授权(MyUserDetailServiceImpl:loadUserByUsername)

1、web.xml中加入过滤器

  1. <!-- SpringSecurity 核心过滤器配置 -->
  2. <filter>
  3. <filter-name>springSecurityFilterChain</filter-name>
  4. <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  5. </filter>
  6. <filter-mapping>
  7. <filter-name>springSecurityFilterChain</filter-name>
  8. <url-pattern>/*</url-pattern>
  9. </filter-mapping>
<!-- SpringSecurity 核心过滤器配置 -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

2、新建spring-security.xml文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans:beans xmlns="http://www.springframework.org/schema/security"
  3. xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans
  5. http://www.springframework.org/schema/beans/spring-beans.xsd
  6. http://www.springframework.org/schema/security
  7. http://www.springframework.org/schema/security/spring-security.xsd">
  8. <!-- entry-point-ref 配置自定义登录 -->
  9. <http use-expressions="true" entry-point-ref="authenticationProcessingFilterEntryPoint">
  10. <!-- 登出配置 -->
  11. <logout logout-url="/j_spring_security_logout" logout-success-url="/login" />
  12. <access-denied-handler error-page="/noPower" />
  13. <!-- 过滤不被拦截的请求 -->
  14. <intercept-url pattern="/login*" access="permitAll" />
  15. <intercept-url pattern="/resources/**" access="permitAll" />
  16. <!-- 只有权限才能访问的请求 -->
  17. <intercept-url pattern="/admin/**" access="isAuthenticated()" />
  18. <custom-filter ref="loginFilter" position="FORM_LOGIN_FILTER" />
  19. <custom-filter ref="securityFilter" before="FILTER_SECURITY_INTERCEPTOR" />
  20. </http>
  21. <beans:bean id="loginFilter"
  22. class="cn.com.abel.test.service.security.MyUsernamePasswordAuthenticationFilter">
  23. <!-- 登录提交处理 -->
  24. <beans:property name="filterProcessesUrl" value="/j_spring_security_check"></beans:property>
  25. <!-- 登录成功跳转 -->
  26. <beans:property name="authenticationSuccessHandler"
  27. ref="loginLogAuthenticationSuccessHandler"></beans:property>
  28. <!-- 设置登录失败的网址 -->
  29. <beans:property name="authenticationFailureHandler"
  30. ref="simpleUrlAuthenticationFailureHandler"></beans:property>
  31. <!-- 用户拥有权限 -->
  32. <beans:property name="authenticationManager" ref="myAuthenticationManager"></beans:property>
  33. </beans:bean>
  34. <beans:bean id="loginLogAuthenticationSuccessHandler"
  35. class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
  36. <beans:property name="defaultTargetUrl" value="/admin/index"></beans:property>
  37. </beans:bean>
  38. <beans:bean id="simpleUrlAuthenticationFailureHandler"
  39. class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
  40. <beans:property name="defaultFailureUrl" value="/login"></beans:property>
  41. </beans:bean>
  42. <authentication-manager alias="myAuthenticationManager">
  43. <authentication-provider user-service-ref="myUserDetailServiceImpl">
  44. <password-encoder ref="encoder" />
  45. </authentication-provider>
  46. </authentication-manager>
  47. <beans:bean id="myUserDetailServiceImpl"
  48. class="cn.com.abel.test.service.security.AdminUserDetailServiceImpl">
  49. </beans:bean>
  50. <beans:bean id="authenticationProcessingFilterEntryPoint"
  51. class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
  52. <beans:property name="loginFormUrl" value="/login"></beans:property>
  53. </beans:bean>
  54. <!-- 认证过滤器 -->
  55. <beans:bean id="securityFilter"
  56. class="cn.com.abel.test.service.security.MySecurityFilter">
  57. <!-- 用户拥有的角色 -->
  58. <beans:property name="authenticationManager" ref="myAuthenticationManager" />
  59. <!-- 用户是否拥有所请求资源的权限 -->
  60. <beans:property name="accessDecisionManager" ref="myAccessDecisionManager" />
  61. <!-- 资源与角色的对应关系 -->
  62. <beans:property name="securityMetadataSource" ref="mySecurityMetadataSource" />
  63. <!-- <beans:property name="rejectPublicInvocations" value="true"/> -->
  64. </beans:bean>
  65. <beans:bean id="myAccessDecisionManager" class="myAccessDecisionManager"></beans:bean>
  66. <beans:bean id="mySecurityMetadataSource"
  67. class="cn.com.abel.test.service.security.MySecurityMetadataSource">
  68. <beans:constructor-arg>
  69. <beans:ref bean="resourceService" />
  70. </beans:constructor-arg>
  71. </beans:bean>
  72. <beans:bean id="encoder" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder"></beans:bean>
  73. </beans:beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans" 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.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
&lt;!-- entry-point-ref 配置自定义登录 --&gt;
&lt;http use-expressions="true" entry-point-ref="authenticationProcessingFilterEntryPoint"&gt; &lt;!-- 登出配置 --&gt;
&lt;logout logout-url="/j_spring_security_logout" logout-success-url="/login" /&gt; &lt;access-denied-handler error-page="/noPower" /&gt; &lt;!-- 过滤不被拦截的请求 --&gt;
&lt;intercept-url pattern="/login*" access="permitAll" /&gt;
&lt;intercept-url pattern="/resources/**" access="permitAll" /&gt; &lt;!-- 只有权限才能访问的请求 --&gt;
&lt;intercept-url pattern="/admin/**" access="isAuthenticated()" /&gt; &lt;custom-filter ref="loginFilter" position="FORM_LOGIN_FILTER" /&gt;
&lt;custom-filter ref="securityFilter" before="FILTER_SECURITY_INTERCEPTOR" /&gt; &lt;/http&gt; &lt;beans:bean id="loginFilter"
class="cn.com.abel.test.service.security.MyUsernamePasswordAuthenticationFilter"&gt; &lt;!-- 登录提交处理 --&gt;
&lt;beans:property name="filterProcessesUrl" value="/j_spring_security_check"&gt;&lt;/beans:property&gt; &lt;!-- 登录成功跳转 --&gt;
&lt;beans:property name="authenticationSuccessHandler"
ref="loginLogAuthenticationSuccessHandler"&gt;&lt;/beans:property&gt; &lt;!-- 设置登录失败的网址 --&gt;
&lt;beans:property name="authenticationFailureHandler"
ref="simpleUrlAuthenticationFailureHandler"&gt;&lt;/beans:property&gt; &lt;!-- 用户拥有权限 --&gt;
&lt;beans:property name="authenticationManager" ref="myAuthenticationManager"&gt;&lt;/beans:property&gt;
&lt;/beans:bean&gt; &lt;beans:bean id="loginLogAuthenticationSuccessHandler"
class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler"&gt;
&lt;beans:property name="defaultTargetUrl" value="/admin/index"&gt;&lt;/beans:property&gt;
&lt;/beans:bean&gt;
&lt;beans:bean id="simpleUrlAuthenticationFailureHandler"
class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"&gt;
&lt;beans:property name="defaultFailureUrl" value="/login"&gt;&lt;/beans:property&gt;
&lt;/beans:bean&gt; &lt;authentication-manager alias="myAuthenticationManager"&gt;
&lt;authentication-provider user-service-ref="myUserDetailServiceImpl"&gt;
&lt;password-encoder ref="encoder" /&gt;
&lt;/authentication-provider&gt;
&lt;/authentication-manager&gt; &lt;beans:bean id="myUserDetailServiceImpl"
class="cn.com.abel.test.service.security.AdminUserDetailServiceImpl"&gt;
&lt;/beans:bean&gt; &lt;beans:bean id="authenticationProcessingFilterEntryPoint"
class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint"&gt;
&lt;beans:property name="loginFormUrl" value="/login"&gt;&lt;/beans:property&gt;
&lt;/beans:bean&gt; &lt;!-- 认证过滤器 --&gt;
&lt;beans:bean id="securityFilter"
class="cn.com.abel.test.service.security.MySecurityFilter"&gt;
&lt;!-- 用户拥有的角色 --&gt;
&lt;beans:property name="authenticationManager" ref="myAuthenticationManager" /&gt;
&lt;!-- 用户是否拥有所请求资源的权限 --&gt;
&lt;beans:property name="accessDecisionManager" ref="myAccessDecisionManager" /&gt;
&lt;!-- 资源与角色的对应关系 --&gt;
&lt;beans:property name="securityMetadataSource" ref="mySecurityMetadataSource" /&gt;
&lt;!-- &lt;beans:property name="rejectPublicInvocations" value="true"/&gt; --&gt; &lt;/beans:bean&gt; &lt;beans:bean id="myAccessDecisionManager" class="myAccessDecisionManager"&gt;&lt;/beans:bean&gt; &lt;beans:bean id="mySecurityMetadataSource"
class="cn.com.abel.test.service.security.MySecurityMetadataSource"&gt;
&lt;beans:constructor-arg&gt;
&lt;beans:ref bean="resourceService" /&gt;
&lt;/beans:constructor-arg&gt;
&lt;/beans:bean&gt; &lt;beans:bean id="encoder" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder"&gt;&lt;/beans:bean&gt;

</beans:beans>

3、MyUsernamePasswordAuthenticationFilter.java

  1. package cn.com.abel.test.service.security;
  2. import javax.servlet.http.HttpServletRequest;
  3. import javax.servlet.http.HttpServletResponse;
  4. import org.springframework.security.authentication.AuthenticationServiceException;
  5. import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
  6. import org.springframework.security.core.Authentication;
  7. import org.springframework.security.core.AuthenticationException;
  8. import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
  9. public class MyUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter{
  10. @Override
  11. public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
  12. if (!request.getMethod().equals("POST")) {
  13. throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
  14. }
  15. String username = obtainUsername(request);
  16. String password = obtainPassword(request);
  17. if (username == null) {
  18. username = "";
  19. }
  20. if (password == null) {
  21. password = "";
  22. }
  23. username = username.trim();
  24. UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
  25. // Allow subclasses to set the "details" property
  26. setDetails(request, authRequest);
  27. //      //登录验证码,如需要开启把下面注释去掉则可
  28. //      String authCode = StringUtils.defaultString(request.getParameter("authCode"));
  29. //      if(!AdwImageCaptchaServlet.validateResponse(request, authCode)){
  30. //          throw new AuthenticationServiceException("validCode.auth.fail");
  31. //      }
  32. return this.getAuthenticationManager().authenticate(authRequest);
  33. }
  34. }
package cn.com.abel.test.service.security;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse; import org.springframework.security.authentication.AuthenticationServiceException;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;

import org.springframework.security.core.Authentication;

import org.springframework.security.core.AuthenticationException;

import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; public class MyUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter{
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { if (!request.getMethod().equals("POST")) {
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
} String username = obtainUsername(request);
String password = obtainPassword(request); if (username == null) {
username = "";
} if (password == null) {
password = "";
} username = username.trim(); UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password); // Allow subclasses to set the "details" property
setDetails(request, authRequest);

// //登录验证码,如需要开启把下面注释去掉则可

// String authCode = StringUtils.defaultString(request.getParameter("authCode"));

// if(!AdwImageCaptchaServlet.validateResponse(request, authCode)){

// throw new AuthenticationServiceException("validCode.auth.fail");

// }

	return this.getAuthenticationManager().authenticate(authRequest);
}

}

4、MySecurityFilter.java

  1. package cn.com.abel.test.service.security;
  2. import java.io.IOException;
  3. import javax.servlet.Filter;
  4. import javax.servlet.FilterChain;
  5. import javax.servlet.FilterConfig;
  6. import javax.servlet.ServletException;
  7. import javax.servlet.ServletRequest;
  8. import javax.servlet.ServletResponse;
  9. import org.springframework.security.access.SecurityMetadataSource;
  10. import org.springframework.security.access.intercept.AbstractSecurityInterceptor;
  11. import org.springframework.security.access.intercept.InterceptorStatusToken;
  12. import org.springframework.security.web.FilterInvocation;
  13. import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
  14. public class MySecurityFilter extends AbstractSecurityInterceptor implements Filter {
  15. //与applicationContext-security.xml里的myFilter的属性securityMetadataSource对应,
  16. //其他的两个组件,已经在AbstractSecurityInterceptor定义
  17. private FilterInvocationSecurityMetadataSource securityMetadataSource;
  18. @Override
  19. public SecurityMetadataSource obtainSecurityMetadataSource() {
  20. return this.securityMetadataSource;
  21. }
  22. public void doFilter(ServletRequest request, ServletResponse response,
  23. FilterChain chain) throws IOException, ServletException {
  24. FilterInvocation fi = new FilterInvocation(request, response, chain);
  25. invoke(fi);
  26. }
  27. private void invoke(FilterInvocation fi) throws IOException, ServletException {
  28. // object为FilterInvocation对象
  29. //1.获取请求资源的权限
  30. //执行Collection<ConfigAttribute> attributes = SecurityMetadataSource.getAttributes(object);
  31. //2.是否拥有权限
  32. //获取安全主体,可以强制转换为UserDetails的实例
  33. //1) UserDetails
  34. // Authentication authenticated = authenticateIfRequired();
  35. //this.accessDecisionManager.decide(authenticated, object, attributes);
  36. //用户拥有的权限
  37. //2) GrantedAuthority
  38. //Collection<GrantedAuthority> authenticated.getAuthorities()
  39. //System.out.println("用户发送请求! ");
  40. InterceptorStatusToken token = null;
  41. token = super.beforeInvocation(fi);
  42. try {
  43. fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
  44. } finally {
  45. super.afterInvocation(token, null);
  46. }
  47. }
  48. public FilterInvocationSecurityMetadataSource getSecurityMetadataSource() {
  49. return securityMetadataSource;
  50. }
  51. public void setSecurityMetadataSource(FilterInvocationSecurityMetadataSource securityMetadataSource) {
  52. this.securityMetadataSource = securityMetadataSource;
  53. }
  54. public void init(FilterConfig arg0) throws ServletException {
  55. // TODO Auto-generated method stub
  56. }
  57. public void destroy() {
  58. // TODO Auto-generated method stub
  59. }
  60. @Override
  61. public Class<? extends Object> getSecureObjectClass() {
  62. //下面的MyAccessDecisionManager的supports方面必须放回true,否则会提醒类型错误
  63. return FilterInvocation.class;
  64. }
  65. }
package cn.com.abel.test.service.security;

import java.io.IOException;

import javax.servlet.Filter;

import javax.servlet.FilterChain;

import javax.servlet.FilterConfig;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse; import org.springframework.security.access.SecurityMetadataSource;

import org.springframework.security.access.intercept.AbstractSecurityInterceptor;

import org.springframework.security.access.intercept.InterceptorStatusToken;

import org.springframework.security.web.FilterInvocation;

import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource; public class MySecurityFilter extends AbstractSecurityInterceptor implements Filter {

//与applicationContext-security.xml里的myFilter的属性securityMetadataSource对应

//其他的两个组件,已经在AbstractSecurityInterceptor定义

private FilterInvocationSecurityMetadataSource securityMetadataSource;
@Override
public SecurityMetadataSource obtainSecurityMetadataSource() {
return this.securityMetadataSource;
} public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
FilterInvocation fi = new FilterInvocation(request, response, chain);
invoke(fi);
} private void invoke(FilterInvocation fi) throws IOException, ServletException {
// object为FilterInvocation对象
//1.获取请求资源的权限
//执行Collection&lt;ConfigAttribute&gt; attributes = SecurityMetadataSource.getAttributes(object);
//2.是否拥有权限
//获取安全主体,可以强制转换为UserDetails的实例
//1) UserDetails
// Authentication authenticated = authenticateIfRequired();
//this.accessDecisionManager.decide(authenticated, object, attributes);
//用户拥有的权限
//2) GrantedAuthority
//Collection&lt;GrantedAuthority&gt; authenticated.getAuthorities()
//System.out.println("用户发送请求! ");
InterceptorStatusToken token = null; token = super.beforeInvocation(fi); try {
fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
} finally {
super.afterInvocation(token, null);
}
} public FilterInvocationSecurityMetadataSource getSecurityMetadataSource() {
return securityMetadataSource;
} public void setSecurityMetadataSource(FilterInvocationSecurityMetadataSource securityMetadataSource) {
this.securityMetadataSource = securityMetadataSource;
} public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
} public void destroy() {
// TODO Auto-generated method stub } @Override
public Class&lt;? extends Object&gt; getSecureObjectClass() {
//下面的MyAccessDecisionManager的supports方面必须放回true,否则会提醒类型错误
return FilterInvocation.class;
}

}

5、AdminUserDetailServiceImpl.java

  1. package cn.com.abel.test.service.security;
  2. import java.util.HashSet;
  3. import java.util.List;
  4. import java.util.Set;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.security.core.GrantedAuthority;
  7. import org.springframework.security.core.authority.SimpleGrantedAuthority;
  8. import org.springframework.security.core.userdetails.UserDetails;
  9. import org.springframework.security.core.userdetails.UserDetailsService;
  10. import org.springframework.security.core.userdetails.UsernameNotFoundException;
  11. import cn.com.abel.test.model.RoleModel;
  12. import cn.com.abel.test.model.MemberModel;
  13. import cn.com.abel.test.service.RoleService;
  14. import cn.com.abel.test.service.MemberService;
  15. public class AdminUserDetailServiceImpl implements UserDetailsService {
  16. @Autowired
  17. private MemberService memberService;
  18. @Autowired
  19. RoleService roleService;
  20. //登录验证
  21. public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
  22. MemberModel member = memberService.getUserDetailsByUserName(username);
  23. if(member==null){
  24. throw new UsernameNotFoundException("member "+username +" not found.");
  25. }
  26. Set<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(member);
  27. //封装成spring security的user
  28. User userdetail = new User(user.getUserName(), user.getPassword(),
  29. true, // 账号状态 0 表示停用 1表示启用
  30. true, true, true, grantedAuths // 用户的权限
  31. );
  32. return userdetail;
  33. }
  34. //取得用户的权限
  35. private Set<GrantedAuthority> obtionGrantedAuthorities(MemberModel member) {
  36. Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
  37. List<RoleModel> roles = roleService.getRoleByUser(member)<span style="font-family:Arial, Helvetica, sans-serif;">;</span>
  38. if(roles!=null){
  39. for(RoleModel role : roles) {
  40. authSet.add(new SimpleGrantedAuthority(role.getRoleCode().trim()));
  41. }
  42. }
  43. return authSet;
  44. }
  45. }
package cn.com.abel.test.service.security;

import java.util.HashSet;

import java.util.List;

import java.util.Set; import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.core.GrantedAuthority;

import org.springframework.security.core.authority.SimpleGrantedAuthority;

import org.springframework.security.core.userdetails.UserDetails;

import org.springframework.security.core.userdetails.UserDetailsService;

import org.springframework.security.core.userdetails.UsernameNotFoundException; import cn.com.abel.test.model.RoleModel;

import cn.com.abel.test.model.MemberModel;

import cn.com.abel.test.service.RoleService;

import cn.com.abel.test.service.MemberService; public class AdminUserDetailServiceImpl implements UserDetailsService {

@Autowired

private MemberService memberService;

@Autowired

RoleService roleService;
//登录验证
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { MemberModel member = memberService.getUserDetailsByUserName(username); if(member==null){
throw new UsernameNotFoundException("member "+username +" not found.");
}
Set&lt;GrantedAuthority&gt; grantedAuths = obtionGrantedAuthorities(member); //封装成spring security的user
User userdetail = new User(user.getUserName(), user.getPassword(),
true, // 账号状态 0 表示停用 1表示启用
true, true, true, grantedAuths // 用户的权限
);
return userdetail;
} //取得用户的权限
private Set&lt;GrantedAuthority&gt; obtionGrantedAuthorities(MemberModel member) { Set&lt;GrantedAuthority&gt; authSet = new HashSet&lt;GrantedAuthority&gt;(); List&lt;RoleModel&gt; roles = roleService.getRoleByUser(member)&lt;span style="font-family:Arial, Helvetica, sans-serif;"&gt;;&lt;/span&gt;
if(roles!=null){
for(RoleModel role : roles) {
authSet.add(new SimpleGrantedAuthority(role.getRoleCode().trim()));
}
} return authSet;
}

}

6、MyAccessDecisionManager.java

  1. package cn.com.abel.test.service.security;
  2. import java.util.Collection;
  3. import java.util.Iterator;
  4. import org.springframework.security.access.AccessDecisionManager;
  5. import org.springframework.security.access.AccessDeniedException;
  6. import org.springframework.security.access.ConfigAttribute;
  7. import org.springframework.security.authentication.InsufficientAuthenticationException;
  8. import org.springframework.security.core.Authentication;
  9. import org.springframework.security.core.GrantedAuthority;
  10. public class MyAccessDecisionManager implements AccessDecisionManager {
  11. public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
  12. if(configAttributes == null) {
  13. return;
  14. }
  15. //所请求的资源拥有的权限(一个资源对多个权限)
  16. Iterator<ConfigAttribute> iterator = configAttributes.iterator();
  17. while(iterator.hasNext()) {
  18. ConfigAttribute configAttribute = iterator.next();
  19. //访问所请求资源所需要的权限
  20. String needPermission = configAttribute.getAttribute();
  21. System.out.println("needPermission is " + needPermission);
  22. //用户所拥有的权限authentication
  23. for(GrantedAuthority ga : authentication.getAuthorities()) {
  24. if(needPermission.equals(ga.getAuthority())) {
  25. return;
  26. }
  27. }
  28. }
  29. //没有权限让我们去捕捉
  30. throw new AccessDeniedException(" 没有权限访问!");
  31. }
  32. public boolean supports(ConfigAttribute attribute) {
  33. // TODO Auto-generated method stub
  34. return true;
  35. }
  36. public boolean supports(Class<?> clazz) {
  37. // TODO Auto-generated method stub
  38. return true;
  39. }
  40. }
package cn.com.abel.test.service.security;

import java.util.Collection;

import java.util.Iterator; import org.springframework.security.access.AccessDecisionManager;

import org.springframework.security.access.AccessDeniedException;

import org.springframework.security.access.ConfigAttribute;

import org.springframework.security.authentication.InsufficientAuthenticationException;

import org.springframework.security.core.Authentication;

import org.springframework.security.core.GrantedAuthority; public class MyAccessDecisionManager implements AccessDecisionManager {
public void decide(Authentication authentication, Object object, Collection&lt;ConfigAttribute&gt; configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
if(configAttributes == null) {
return;
}
//所请求的资源拥有的权限(一个资源对多个权限)
Iterator&lt;ConfigAttribute&gt; iterator = configAttributes.iterator();
while(iterator.hasNext()) {
ConfigAttribute configAttribute = iterator.next();
//访问所请求资源所需要的权限
String needPermission = configAttribute.getAttribute();
System.out.println("needPermission is " + needPermission);
//用户所拥有的权限authentication
for(GrantedAuthority ga : authentication.getAuthorities()) {
if(needPermission.equals(ga.getAuthority())) {
return;
}
}
}
//没有权限让我们去捕捉
throw new AccessDeniedException(" 没有权限访问!");
} public boolean supports(ConfigAttribute attribute) {
// TODO Auto-generated method stub
return true;
} public boolean supports(Class&lt;?&gt; clazz) {
// TODO Auto-generated method stub
return true;
}

}

7、MySecurityMetadataSource.java

  1. package cn.com.abel.test.service.security;
  2. import java.util.ArrayList;
  3. import java.util.Collection;
  4. import java.util.HashSet;
  5. import java.util.Iterator;
  6. import java.util.List;
  7. import java.util.Map;
  8. import java.util.Map.Entry;
  9. import java.util.TreeMap;
  10. import java.util.concurrent.ConcurrentHashMap;
  11. import javax.servlet.http.HttpServletRequest;
  12. import org.apache.commons.lang.StringUtils;
  13. import org.springframework.beans.factory.InitializingBean;
  14. import org.springframework.security.access.ConfigAttribute;
  15. import org.springframework.security.access.SecurityConfig;
  16. import org.springframework.security.web.FilterInvocation;
  17. import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
  18. import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
  19. import org.springframework.security.web.util.matcher.RequestMatcher;
  20. import cn.com.abel.test.model.RoleModel;
  21. import cn.com.abel.test.service.ResourceService;
  22. public class MySecurityMetadataSource  implements FilterInvocationSecurityMetadataSource,InitializingBean {
  23. private static final String AUTH_NO_ROLE =" __AUTH_NO_ROLE__";
  24. private ResourceService resourceService;
  25. public MySecurityMetadataSource(ResourceService resourceService) {
  26. this.resourceService = resourceService;
  27. }
  28. private static Map<String, Collection<ConfigAttribute>> resourceMap = null;
  29. public Collection<ConfigAttribute> getAllConfigAttributes() {
  30. return null;
  31. }
  32. public boolean supports(Class<?> clazz) {
  33. return true;
  34. }
  35. private void loadResourceDefine() {
  36. if(resourceMap == null) {
  37. resourceMap = new ConcurrentHashMap<String, Collection<ConfigAttribute>>();
  38. }else{
  39. resourceMap.clear();
  40. }
  41. Map<String,List<RoleModel>> resourceRoleMap = resourceService.getAllResourceRole();
  42. for (Entry<String,List<RoleModel>> entry : resourceRoleMap.entrySet()) {
  43. String url = entry.getKey();
  44. List<RoleModel> values = entry.getValue();
  45. Collection<ConfigAttribute> configAttributes = new ArrayList<ConfigAttribute>();
  46. for(RoleModel secRoleModel : values){
  47. ConfigAttribute configAttribute = new SecurityConfig(StringUtils.defaultString(secRoleModel.getRoleCode(),AUTH_NO_ROLE));
  48. configAttributes.add(configAttribute);
  49. }
  50. resourceMap.put(url, configAttributes);
  51. }
  52. }
  53. public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
  54. HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();
  55. TreeMap<String, Collection<ConfigAttribute>> attrMap = new TreeMap<String, Collection<ConfigAttribute>>(resourceMap);
  56. Iterator<String> ite = attrMap.keySet().iterator();
  57. RequestMatcher urlMatcher = null;
  58. Collection<ConfigAttribute> attrSet = new HashSet<ConfigAttribute>();
  59. //match all of /admin/**  a/b/**
  60. while (ite.hasNext()) {
  61. String resURL = ite.next();
  62. urlMatcher = new AntPathRequestMatcher(resURL);
  63. if (urlMatcher.matches(request)||StringUtils.equals(request.getRequestURI(),resURL)) {
  64. attrSet.addAll(attrMap.get(resURL));
  65. }
  66. }
  67. if(!attrSet.isEmpty()){
  68. return attrSet;
  69. }
  70. return null;
  71. }
  72. @Override
  73. public void afterPropertiesSet() throws Exception {
  74. loadResourceDefine() ;
  75. }
  76. }
package cn.com.abel.test.service.security;

import java.util.ArrayList;

import java.util.Collection;

import java.util.HashSet;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

import java.util.Map.Entry;

import java.util.TreeMap;

import java.util.concurrent.ConcurrentHashMap; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.StringUtils;

import org.springframework.beans.factory.InitializingBean;

import org.springframework.security.access.ConfigAttribute;

import org.springframework.security.access.SecurityConfig;

import org.springframework.security.web.FilterInvocation;

import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;

import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import org.springframework.security.web.util.matcher.RequestMatcher; import cn.com.abel.test.model.RoleModel;

import cn.com.abel.test.service.ResourceService; public class MySecurityMetadataSource implements FilterInvocationSecurityMetadataSource,InitializingBean {
private static final String AUTH_NO_ROLE =" __AUTH_NO_ROLE__";

private ResourceService resourceService;

public MySecurityMetadataSource(ResourceService resourceService) {
this.resourceService = resourceService;
} private static Map&lt;String, Collection&lt;ConfigAttribute&gt;&gt; resourceMap = null; public Collection&lt;ConfigAttribute&gt; getAllConfigAttributes() {
return null;
} public boolean supports(Class&lt;?&gt; clazz) {
return true;
}
private void loadResourceDefine() {
if(resourceMap == null) {
resourceMap = new ConcurrentHashMap&lt;String, Collection&lt;ConfigAttribute&gt;&gt;();
}else{
resourceMap.clear();
} Map&lt;String,List&lt;RoleModel&gt;&gt; resourceRoleMap = resourceService.getAllResourceRole(); for (Entry&lt;String,List&lt;RoleModel&gt;&gt; entry : resourceRoleMap.entrySet()) {
String url = entry.getKey();
List&lt;RoleModel&gt; values = entry.getValue(); Collection&lt;ConfigAttribute&gt; configAttributes = new ArrayList&lt;ConfigAttribute&gt;();
for(RoleModel secRoleModel : values){
ConfigAttribute configAttribute = new SecurityConfig(StringUtils.defaultString(secRoleModel.getRoleCode(),AUTH_NO_ROLE));
configAttributes.add(configAttribute);
}
resourceMap.put(url, configAttributes);
}
}
public Collection&lt;ConfigAttribute&gt; getAttributes(Object object) throws IllegalArgumentException { HttpServletRequest request = ((FilterInvocation) object).getHttpRequest(); TreeMap&lt;String, Collection&lt;ConfigAttribute&gt;&gt; attrMap = new TreeMap&lt;String, Collection&lt;ConfigAttribute&gt;&gt;(resourceMap); Iterator&lt;String&gt; ite = attrMap.keySet().iterator(); RequestMatcher urlMatcher = null; Collection&lt;ConfigAttribute&gt; attrSet = new HashSet&lt;ConfigAttribute&gt;();
//match all of /admin/** a/b/**
while (ite.hasNext()) { String resURL = ite.next();
urlMatcher = new AntPathRequestMatcher(resURL); if (urlMatcher.matches(request)||StringUtils.equals(request.getRequestURI(),resURL)) {
attrSet.addAll(attrMap.get(resURL));
}
} if(!attrSet.isEmpty()){
return attrSet;
}
return null;
} @Override
public void afterPropertiesSet() throws Exception {
loadResourceDefine() ;
}

}

8、ResourceService.java

此类是为从数据库获取系统中的资源所属的角色,根据自己的数据表自行编写。

  1. package cn.com.abel.test.service;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.HashSet;
  5. import java.util.List;
  6. import java.util.Map;
  7. import org.apache.commons.collections.CollectionUtils;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.stereotype.Service;
  10. import cn.com.abel.test.mapper.ResourceModelMapper;
  11. import cn.com.abel.test.mapper.RoleModelMapper;
  12. import cn.com.abel.test.mapper.RoleResourcetModelMapper;
  13. import cn.com.abel.test.model.ResourceModel;
  14. import cn.com.abel.test.model.ResourceModelCriteria;
  15. import cn.com.abel.test.model.RoleModel;
  16. import cn.com.abel.test.model.RoleModelCriteria;
  17. import cn.com.abel.test.model.RoleResourcetModel;
  18. import cn.com.abel.test.model.RoleResourcetModelCriteria;
  19. @Service
  20. public class ResourceService {
  21. @Autowired
  22. ResourceModelMapper resourceModelMapper;
  23. @Autowired
  24. RoleModelMapper roleMapper;
  25. @Autowired
  26. RoleResourcetModelMapper  roleResMapper;
  27. /**
  28. * 获取各个资源(url)对应的角色
  29. * @return
  30. */
  31. public Map<String,List<RoleModel>> getAllResourceRole(){
  32. Map<String,List<RoleModel>> resultMap = new HashMap<String,List<RoleModel>>();
  33. ResourceModelCriteria secResourceModelExample = new ResourceModelCriteria();
  34. List<ResourceModel> resourceList = resourceModelMapper.selectByExample(secResourceModelExample);
  35. if(CollectionUtils.isNotEmpty(resourceList)){
  36. for(ResourceModel secResourceModel : resourceList){
  37. RoleModelCriteria roleCriteria = new RoleModelCriteria();
  38. roleCriteria.createCriteria().andIdIn(getRoleIdsByResourceId(secResourceModel.getId()));
  39. List<RoleModel> roleList = roleMapper.selectByExample(roleCriteria);
  40. resultMap.put(secResourceModel.getValue(), roleList);
  41. }
  42. }
  43. return resultMap;
  44. }
  45. public List<Integer> getRoleIdsByResourceId(Integer resourceId){
  46. List<Integer> roleIds = new ArrayList<Integer>();
  47. RoleResourcetModelCriteria criteria = new RoleResourcetModelCriteria();
  48. criteria.createCriteria().andResourceIdEqualTo(resourceId);
  49. List<RoleResourcetModel> list = roleResMapper.selectByExample(criteria);
  50. if(CollectionUtils.isNotEmpty(list)){
  51. for(RoleResourcetModel model : list){
  52. roleIds.add(model.getRoleId());
  53. }
  54. }
  55. HashSet<Integer> h  =   new  HashSet<Integer>(roleIds);
  56. roleIds.clear();
  57. roleIds.addAll(h);
  58. return roleIds;
  59. }
  60. }
package cn.com.abel.test.service;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.HashSet;

import java.util.List;

import java.util.Map; import org.apache.commons.collections.CollectionUtils;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service; import cn.com.abel.test.mapper.ResourceModelMapper;

import cn.com.abel.test.mapper.RoleModelMapper;

import cn.com.abel.test.mapper.RoleResourcetModelMapper;

import cn.com.abel.test.model.ResourceModel;

import cn.com.abel.test.model.ResourceModelCriteria;

import cn.com.abel.test.model.RoleModel;

import cn.com.abel.test.model.RoleModelCriteria;

import cn.com.abel.test.model.RoleResourcetModel;

import cn.com.abel.test.model.RoleResourcetModelCriteria; @Service

public class ResourceService {
@Autowired
ResourceModelMapper resourceModelMapper; @Autowired
RoleModelMapper roleMapper; @Autowired
RoleResourcetModelMapper roleResMapper; /**
* 获取各个资源(url)对应的角色
* @return
*/
public Map&lt;String,List&lt;RoleModel&gt;&gt; getAllResourceRole(){ Map&lt;String,List&lt;RoleModel&gt;&gt; resultMap = new HashMap&lt;String,List&lt;RoleModel&gt;&gt;(); ResourceModelCriteria secResourceModelExample = new ResourceModelCriteria();
List&lt;ResourceModel&gt; resourceList = resourceModelMapper.selectByExample(secResourceModelExample); if(CollectionUtils.isNotEmpty(resourceList)){
for(ResourceModel secResourceModel : resourceList){
RoleModelCriteria roleCriteria = new RoleModelCriteria();
roleCriteria.createCriteria().andIdIn(getRoleIdsByResourceId(secResourceModel.getId()));
List&lt;RoleModel&gt; roleList = roleMapper.selectByExample(roleCriteria);
resultMap.put(secResourceModel.getValue(), roleList); }
} return resultMap;
} public List&lt;Integer&gt; getRoleIdsByResourceId(Integer resourceId){
List&lt;Integer&gt; roleIds = new ArrayList&lt;Integer&gt;(); RoleResourcetModelCriteria criteria = new RoleResourcetModelCriteria();
criteria.createCriteria().andResourceIdEqualTo(resourceId);
List&lt;RoleResourcetModel&gt; list = roleResMapper.selectByExample(criteria);
if(CollectionUtils.isNotEmpty(list)){
for(RoleResourcetModel model : list){
roleIds.add(model.getRoleId());
}
} HashSet&lt;Integer&gt; h = new HashSet&lt;Integer&gt;(roleIds);
roleIds.clear();
roleIds.addAll(h);
return roleIds;
}

}

最后附上数据表的SQL:

  1. CREATE TABLE `auth_resource` (
  2. `id` INT(11) NOT NULL AUTO_INCREMENT,
  3. `name` VARCHAR(100) NULL DEFAULT NULL COMMENT '资源名称',
  4. `value` VARCHAR(100) NULL DEFAULT NULL COMMENT '资源值',
  5. `summary` VARCHAR(1000) NULL DEFAULT NULL COMMENT '资源描述',
  6. `updated_time` DATETIME NULL DEFAULT NULL,
  7. `updated_user` VARCHAR(100) NULL DEFAULT NULL,
  8. PRIMARY KEY (`id`)
  9. )
  10. COMMENT='资源访问表'
  11. COLLATE='utf8_general_ci'
  12. ENGINE=InnoDB;
  13. CREATE TABLE `auth_role` (
  14. `id` INT(11) NOT NULL AUTO_INCREMENT,
  15. `role_name` VARCHAR(100) NULL DEFAULT NULL COMMENT '角色名称',
  16. `role_code` VARCHAR(100) NULL DEFAULT NULL COMMENT '角色代码',
  17. `updated_time` DATETIME NULL DEFAULT NULL,
  18. `updated_user` VARCHAR(100) NULL DEFAULT NULL,
  19. PRIMARY KEY (`id`)
  20. )
  21. COMMENT='角色表'
  22. COLLATE='utf8_general_ci'
  23. ENGINE=InnoDB;
  24. CREATE TABLE `role_resource` (
  25. `id` INT(11) NOT NULL AUTO_INCREMENT,
  26. `role_id` INT(11) NOT NULL,
  27. `resource_id` INT(11) NOT NULL,
  28. PRIMARY KEY (`id`),
  29. UNIQUE INDEX `role_id_resource_id` (`role_id`, `resource_id`)
  30. )
  31. COMMENT='资源角色关联表'
  32. COLLATE='utf8_general_ci'
  33. ENGINE=InnoDB;
  34. CREATE TABLE `member` (
  35. `id` INT(11) NOT NULL AUTO_INCREMENT,
  36. `user_name` VARCHAR(100) NULL DEFAULT NULL,
  37. `nick` VARCHAR(100) NULL DEFAULT NULL,
  38. `password` VARCHAR(100) NULL DEFAULT NULL,
  39. `sex` INT(11) NULL DEFAULT NULL,
  40. `birthday` DATE NULL DEFAULT NULL,
  41. `mobile` VARCHAR(50) NULL DEFAULT NULL,
  42. `email` VARCHAR(50) NULL DEFAULT NULL,
  43. `address` VARCHAR(512) NULL DEFAULT NULL,
  44. `regip` VARCHAR(100) NULL DEFAULT NULL,
  45. `created_time` DATETIME NULL DEFAULT NULL,
  46. PRIMARY KEY (`id`)
  47. )
  48. COMMENT='用户表'
  49. COLLATE='utf8_general_ci'
  50. ENGINE=InnoDB
  51. AUTO_INCREMENT=2;
  52. CREATE TABLE `member_role` (
  53. `id` INT(11) NOT NULL AUTO_INCREMENT,
  54. `member_id` INT(11) NOT NULL,
  55. `role_id` INT(11) NOT NULL,
  56. PRIMARY KEY (`id`),
  57. UNIQUE INDEX `member_id_role_id` (`member_id`, `role_id`)
  58. )
  59. COMMENT='用户角色关联表'
  60. COLLATE='utf8_general_ci'
  61. ENGINE=InnoDB;
CREATE TABLE `auth_resource` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) NULL DEFAULT NULL COMMENT '资源名称',
`value` VARCHAR(100) NULL DEFAULT NULL COMMENT '资源值',
`summary` VARCHAR(1000) NULL DEFAULT NULL COMMENT '资源描述',
`updated_time` DATETIME NULL DEFAULT NULL,
`updated_user` VARCHAR(100) NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
COMMENT='资源访问表'
COLLATE='utf8_general_ci'
ENGINE=InnoDB; CREATE TABLE auth_role (

id INT(11) NOT NULL AUTO_INCREMENT,

role_name VARCHAR(100) NULL DEFAULT NULL COMMENT '角色名称',

role_code VARCHAR(100) NULL DEFAULT NULL COMMENT '角色代码',

updated_time DATETIME NULL DEFAULT NULL,

updated_user VARCHAR(100) NULL DEFAULT NULL,

PRIMARY KEY (id)

)

COMMENT='角色表'

COLLATE='utf8_general_ci'

ENGINE=InnoDB; CREATE TABLE role_resource (

id INT(11) NOT NULL AUTO_INCREMENT,

role_id INT(11) NOT NULL,

resource_id INT(11) NOT NULL,

PRIMARY KEY (id),

UNIQUE INDEX role_id_resource_id (role_id, resource_id)

)

COMMENT='资源角色关联表'

COLLATE='utf8_general_ci'

ENGINE=InnoDB; CREATE TABLE member (

id INT(11) NOT NULL AUTO_INCREMENT,

user_name VARCHAR(100) NULL DEFAULT NULL,

nick VARCHAR(100) NULL DEFAULT NULL,

password VARCHAR(100) NULL DEFAULT NULL,

sex INT(11) NULL DEFAULT NULL,

birthday DATE NULL DEFAULT NULL,

mobile VARCHAR(50) NULL DEFAULT NULL,

email VARCHAR(50) NULL DEFAULT NULL,

address VARCHAR(512) NULL DEFAULT NULL,

regip VARCHAR(100) NULL DEFAULT NULL,

created_time DATETIME NULL DEFAULT NULL,

PRIMARY KEY (id)

)

COMMENT='用户表'

COLLATE='utf8_general_ci'

ENGINE=InnoDB

AUTO_INCREMENT=2; CREATE TABLE member_role (

id INT(11) NOT NULL AUTO_INCREMENT,

member_id INT(11) NOT NULL,

role_id INT(11) NOT NULL,

PRIMARY KEY (id),

UNIQUE INDEX member_id_role_id (member_id, role_id)

)

COMMENT='用户角色关联表'

COLLATE='utf8_general_ci'

ENGINE=InnoDB;

完整代码下载(包含数据库):http://download.csdn.net/download/rongku/9931455

spring security 登录、权限管理配置的更多相关文章

  1. 使用Spring Security实现权限管理

    使用Spring Security实现权限管理 1.技术目标 了解并创建Security框架所需数据表 为项目添加Spring Security框架 掌握Security框架配置 应用Security ...

  2. Spring Security 之Session管理配置

    废话不多说,直接上代码.示例如下: 1.   新建Maven项目  session 2.   pom.xml <project xmlns="http://maven.apache.o ...

  3. springBoot整合spring security实现权限管理(单体应用版)--筑基初期

    写在前面 在前面的学习当中,我们对spring security有了一个小小的认识,接下来我们整合目前的主流框架springBoot,实现权限的管理. 在这之前,假定你已经了解了基于资源的权限管理模型 ...

  4. (39.1) Spring Boot Shiro权限管理【从零开始学Spring Boot】

    (本节提供源代码,在最下面可以下载)距上一个章节过了二个星期了,最近时间也是比较紧,一直没有时间可以写博客,今天难得有点时间,就说说Spring Boot如何集成Shiro吧.这个章节会比较复杂,牵涉 ...

  5. Spring Boot Shiro 权限管理

    Spring Boot Shiro 权限管理 标签: springshiro 2016-01-14 23:44 94587人阅读 评论(60) 收藏 举报 .embody{ padding:10px ...

  6. spring boot rest 接口集成 spring security(1) - 最简配置

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

  7. SpringBoot 优雅配置跨域多种方式及Spring Security跨域访问配置的坑

    前言 最近在做项目的时候,基于前后端分离的权限管理系统,后台使用 Spring Security 作为权限控制管理, 然后在前端接口访问时候涉及到跨域,但我怎么配置跨域也没有生效,这里有一个坑,在使用 ...

  8. Spring Security控制权限

    Spring Security控制权限 1,配置过滤器 为了在项目中使用Spring Security控制权限,首先要在web.xml中配置过滤器,这样我们就可以控制对这个项目的每个请求了. < ...

  9. Spring Boot中使用 Spring Security 构建权限系统

    Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架.它提供了一组可以在Spring应用上下文中配置的Bean,为应用系统提供声明式的安全 ...

  10. Spring Security 登录校验 源码解析

    传统情况下,在过滤器中做权限验证,Spring Secuirty也是在Filter中进行权限验证. 创建并注册过滤器 package com.awizdata.edubank.config; impo ...

随机推荐

  1. bunzip2命令

    bunzip2——解压缩.bz2格式文件 命令所在路径:/usr/bin/bunzip2 示例1: # bunzip2 yum.log.bz2 解压当前目录下的yum.log.bz2为yum.log, ...

  2. 如何在Kubernetes里创建一个Nginx应用

    使用命令行kubectl run --image=nginx nginx-app --port=80 创建一个名为nginx-app的应用 结果: deployment.apps/nginx-app ...

  3. Robot Framework(十三) 执行测试用例——创建输出

    3.5创建输出 执行测试时会创建几个输出文件,并且所有这些文件都与测试结果有某种关联.本节讨论创建的输出,如何配置它们的创建位置以及如何微调其内容. 3.5.1不同的输出文件 输出目录 输出文件 日志 ...

  4. python基础一 day13 复习

    # 函数 —— 2天 # 函数的定义和调用 # def 函数名(形参): #函数体 #return 返回值 #调用 函数名(实参) # 站在形参的角度上 : 位置参数,*args,默认参数(陷阱),* ...

  5. Codeforces Round #277.5 (Div. 2)-D. Unbearable Controversy of Being

    http://codeforces.com/problemset/problem/489/D D. Unbearable Controversy of Being time limit per tes ...

  6. JS中鼠标左右键以及中键的事件

    在三维场景中有时候需要判断鼠标的事件,除了使用的click事件,只有鼠标左键有效,而右键无效.而对于onmousedown.onmouseup的时候鼠标的事件左键/右键有效.详细请看w3c上的资料. ...

  7. CVE-2010-3333

    环境 windows xp sp3 office 2003 sp0 windbg ollydbg vmware 12.0 0x00 RTF格式 RTF是Rich TextFormat的缩写,意即富文本 ...

  8. 一. python基础知识

    第一章.变量与判断语句 1.第一个python程序 # -*- coding:utf-8 -*- # Author: Raymond print ("hello world") p ...

  9. POJ-3669-流星雨

    这题的话,卡了有两个小时左右,首先更新地图的时候越界了,我们进行更新的时候,要判断一下是不是小于零了,越界就会Runtime Error. 然后bfs 的时候,我没有允许它搜出300以外的范围,然后就 ...

  10. UVa-1368-DNA序列

    这题的话,我们每次统计的话,是以列为外层循环,以行为内层循环,逐一按列进行比较. 统计完了之后,题目中要求说到要hamming值最小的,那我们就选用该列最多的字母就可以了,如果有数目相等的字母,那就按 ...