废话不多说,直接上代码
一、pom.xml添加依赖
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>3.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>3.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>3.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>3.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.14</version>
</dependency>
二、web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!-- 字符编码过滤器 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<!-- 配置项目的编码mapping -->
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置spring security filter -->
<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>/ps_service/*</url-pattern>
</filter-mapping>
<!-- 指定spring security配置文件的位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/spring-security.xml
/WEB-INF/config/authority_applicationContext.xml</param-value>
</context-param>
<!-- 开启spring功能 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- request监听 -->
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<!-- session监听-->
<listener>
<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
<!-- Spring MVC 基本配置 -->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/springMVC-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup><!-- 标记容器是否在启动的时候就加载这个servlet,1代表优先级 -->
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>ps_service/*</url-pattern><!-- 注意这里就是URL拦截配置 -->
</servlet-mapping>
<!-- session超时 17061434 -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
三、jetty中的mysql数据库配置jetty-env.xml
<?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Mort Bay Consulting//DTD Configure//EN" "http://jetty.mortbay.org/configure.dtd">
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
<New id="semanticDB" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg>jdbc/ps_service</Arg> <!--这个较为重要,是jndi用来找到下面数据库配置的重要标志-->
<Arg>
<New class="com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource">
<Set name="Url">jdbc:mysql://xx.xx.xx.xx:3306/ps_service</Set>
<Set name="User">xxx</Set>
<Set name="Password">xxx</Set>
</New>
</Arg>
</New>
</Configure>
四、servlet配置文件springMVC-servlet.xml与前面文章
SpringMVC+Spring Security实现登录认证的简单功能 一致
四、spring security的配置文件spring-security.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<security:http use-expressions="true">
<!-- 顺序不能乱 ,按照从上往下依次过滤 -->
<!-- 默认不过滤的url(不需要登录) -->
<security:intercept-url pattern="/ps_service/index.jsp" access="permitAll"/>
<security:intercept-url pattern="/ps_service/login.do" access="permitAll"/>
<security:intercept-url pattern="/ps_service/loginfailed.do" access="permitAll"/>
<!--<security:intercept-url pattern="/cs/404.html" access="permitAll"/>-->
<!--<security:intercept-url pattern="/favicon.ico" access="permitAll"/>--><!--过滤浏览器自动发起的链接-->
<!-- 除/admin/*(web.xml中)和permitAll外,任何url都要拦截 -->
<security:intercept-url pattern="/**" access="authenticated"/>
<!-- 登录认证 -->
<security:form-login login-page="/ps_service/login.do"
authentication-failure-url="/ps_service/loginfailed.do"
username-parameter="sescs_username"
password-parameter="sescs_password"
default-target-url="/"
always-use-default-target="false"/>
<!--过滤该用户没有权限访问的URL,即如果有权限就可访问用户请求的URL,没有权限就返回错误 -->
<security:custom-filter after="FILTER_SECURITY_INTERCEPTOR" ref="filterUrl"/>
<!-- logout-success-url:成功注销后跳转到的页面; -->
<security:logout logout-url="/ps_service/j_spring_security_logout" logout-success-url="/ps_service/login.do"/>
<!-- session管理,invalid-session-url重定向,指定使用已经超时的sessionId进行请求需要重定向的页面-->
<security:session-management invalid-session-url="/ps_service/login.do"/>
</security:http>
<!-- 启用注解 -->
<security:global-method-security pre-post-annotations="enabled"/>
<!-- 安全认证管理,这里用了数据库,后面再用-->
<security:authentication-manager>
<security:authentication-provider ref="filterLogin"/>
</security:authentication-manager>
<bean id="filterLogin" class="com.suning.web.authority.FilterLogin"/>
<bean id="filterUrl" class="com.suning.web.authority.FilterUrl"/>
</beans>
五、数据连接配置文件authority_applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd">
<aop:aspectj-autoproxy/>
<!-- xiaozhao -->
<!-- spring security jdbc start-->
<jee:jndi-lookup id="csdataSource" jndi-name="jdbc/ps_service" /> <--jndi-name在jetty-env.xml中可以找到-->
<bean id="urlJdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="csdataSource" />
</bean>
<bean id="filterSql" class="com.suning.web.authority.FilterSql"/>
<bean id="filterService" class="com.suning.web.authority.FilterService">
<property name="filterSql" ref="filterSql"/>
</bean>
<!-- spring security jdbc end-->
<!--LADP login begin暂时没有用到
<import resource="/ldap.xml" />-->
<!--LADP login end-->
</beans>
六、权限控制类:FilterUrl.java
package com.suning.web.authority;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
public class FilterUrl implements Filter{
private String user_id;//用户名
private List<String> user_role;//一个用户可能有多个角色
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String url = request.getRequestURI();//获取当前url
user_role = new ArrayList<String>();
user_id = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();//获取用户名
Collection<? extends GrantedAuthority> obj = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
for (Object o:obj){
user_role.add(o.toString());//获取用户角色
}
WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
FilterSql filterSql = (FilterSql)webApplicationContext.getBean("filterSql");//获取bean
JdbcTemplate urlJdbcTemplate = (JdbcTemplate)webApplicationContext.getBean("urlJdbcTemplate");
filterSql.setCsJdbcTemplate(urlJdbcTemplate);//注入jdbctemplate
boolean permit = filterSql.queryURL(url, user_id, user_role);
if( permit ){
filterChain.doFilter(request, response);
}
else{
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access is denied");
}
}
@Override
public void destroy() {
}
}
七、登录验证类FilterLogin.java
package com.suning.web.authority;
import java.util.ArrayList;
import java.util.List;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
public class FilterLogin implements AuthenticationProvider{
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String name = authentication.getName();
String password = authentication.getCredentials().toString();
WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
FilterSql filterSql = (FilterSql)webApplicationContext.getBean("filterSql");//获取bean
JdbcTemplate urlJdbcTemplate = (JdbcTemplate)webApplicationContext.getBean("urlJdbcTemplate");
//LdapTemplate ldapTemplate = (LdapTemplate)webApplicationContext.getBean("ldapTemplate");
filterSql.setCsJdbcTemplate(urlJdbcTemplate);//注入jdbctemplate
//filterSql.setLdapTemplate(ldapTemplate);//ldapTemplate
List<String> roles = filterSql.login(name, password);
if ( roles.size()>0 ) {
final List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
for(String role:roles){//一个用户可能有多个角色
grantedAuths.add(new SimpleGrantedAuthority(role));
}
return new UsernamePasswordAuthenticationToken(name, password, grantedAuths);
}
throw new BadCredentialsException("请核对用户名密码");
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}
八、为权限控制和登录验证提供公共服务类:
1、FilterSql.java
package com.suning.web.authority;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
public class FilterSql {
private Logger log = LoggerFactory.getLogger(FilterSql.class);
@Autowired
private JdbcTemplate urlJdbcTemplate;
// private LdapTemplate ldapTemplate;
//
public void setCsJdbcTemplate(JdbcTemplate urlJdbcTemplate) {
this.urlJdbcTemplate = urlJdbcTemplate;
}
// public void setLdapTemplate(LdapTemplate ldapTemplate) {
// this.ldapTemplate = ldapTemplate;
// }
/*
* 验证密码是否正确
* */
public boolean checkPassword(String user_id, String user_password)
{
boolean check = false;
List<String> list = new ArrayList<String>();
String sql = " SELECT * FROM MEMBER WHERE USER_NAME = ? ";
list = urlJdbcTemplate.query(sql, new Object[]{user_id}, new RowMapper<String>() {
@Override
public String mapRow(ResultSet rs, int i) throws SQLException {
return rs.getString("PASSWORD");
}
});
String password = list.get(0);
if(user_password.equals(password))
{
check = true;
}
return check;
}
public List<String> login(String user_id, String user_password) {//登录
List<String> list = new ArrayList<String>();
boolean check = checkPassword(user_id, user_password);
if (check) {//如果用户名密码匹配,检查是否授权
log.info("用户:" + user_id + "登录admin系统.");
String sql = " select t1.role_name from auth_role t1,member_role t2, member t3 where t3.user_name= ? and t3.id=t2.member_id and t2.role_id = t1.role_code";
list = urlJdbcTemplate.query(sql, new Object[]{user_id}, new RowMapper<String>() {
@Override
public String mapRow(ResultSet rs, int i) throws SQLException {
return rs.getString("ROLE_NAME");
}
});
if (list.size() == 0) {
list.add("ROLE_VISITOR");
}
}
return list;
}
/***
*重写用户权限的登录方法,目的是passport登录后,无需再校验密码
*/
public List<String> login2(String user_id){
List<String> list = new ArrayList<String>();
log.info("用户:" + user_id + "登录admin系统.");
String sql = " SELECT * FROM UAA_ROLE WHERE USER_IDENTITY = ? ";
try{
list = urlJdbcTemplate.query(sql, new Object[]{user_id}, new RowMapper<String>() {
@Override
public String mapRow(ResultSet rs, int i) throws SQLException {
return rs.getString("USER_ROLE");
}
});
}catch(Exception ex){
log.error(ex.getMessage());
}
if (list.size() == 0) {
list.add("ROLE_VISITOR");
}
return list;
}
public boolean queryURL(String url, String user_id, List<String> user_role) {//url权限管理
boolean permit = true;
boolean noFilter = true;//不需要拦截
List<String> list;
String sql = " SELECT VALUE FROM AUTH_RESOURCE ";
Pattern p = Pattern.compile("\\.do");//需要过滤的后缀(*.do、*.json)
Matcher m = p.matcher(url);
while (m.find()) {
noFilter = false;
}
p = Pattern.compile("\\.json");
m = p.matcher(url);
while (m.find()) {
noFilter = false;
}
if ("anonymousUser".equals(user_id) || noFilter) {//如果是用户登录,或者不是(*.do、*.json)
return true;//不需要拦截
}
if (user_role.contains("ROLE_VISITOR") && !"/ps_service/index.do".equals(url)) {//如果是访客且不是/admin/index.do,拦截。
return false;//拦截
}
list = urlJdbcTemplate.query(sql, new RowMapper<String>() {
@Override
public String mapRow(ResultSet rs, int i) throws SQLException {
return rs.getString("VALUE");
}
});
if (list.contains(url) && (!user_role.contains("ROLE_ADMIN"))) {//访问特定url,且不是管理员,拒绝访问
permit = false;//拦截
}
return permit;
}
public int getUrlPages() {//查询url数目
String sql = " SELECT COUNT(*) FROM UAA_ADMIN_URL ";
return urlJdbcTemplate.queryForInt(sql);
}
public List<UrlBean> getUrlList(int page) {//查询url列表
List<UrlBean> urlBeanList;
String sql = " SELECT * FROM UAA_ADMIN_URL LIMIT ?,10 ";
urlBeanList = urlJdbcTemplate.query(sql, new Object[]{(page - 1) * 10}, new RowMapper<UrlBean>() {
@Override
public UrlBean mapRow(ResultSet rs, int i) throws SQLException {
UrlBean urlBean = new UrlBean();
urlBean.setUrlType(rs.getString("type"));
urlBean.setUrlResource(rs.getString("resource"));
urlBean.setUrlDescription(rs.getString("description"));
return urlBean;
}
});
return urlBeanList;
}
public boolean urlAdd(String urlType, String urlResource, String urlDescription) {//添加url
String sql = " INSERT INTO UAA_ADMIN_URL(TYPE,RESOURCE,DESCRIPTION) VALUES(?,?,?) ";
boolean bool;
try {
urlJdbcTemplate.update(sql, urlType, urlResource, urlDescription);
bool = true;
} catch (Exception e) {
bool = false;
}
return bool;
}
public boolean urlUpdate(String urlResource, String newUrlType, String newUrlResource, String newUrlDescription) {//修改url
String sql = " UPDATE UAA_ADMIN_URL SET TYPE = ?, RESOURCE = ? , DESCRIPTION = ? WHERE RESOURCE = ? ";
boolean bool;
try {
urlJdbcTemplate.update(sql, newUrlType, newUrlResource, newUrlDescription, urlResource);
bool = true;
} catch (Exception e) {
bool = false;
}
return bool;
}
public boolean urlDelete(String urlResource) {//删除url
String sql = " DELETE FROM UAA_ADMIN_URL WHERE RESOURCE = ? ";
boolean bool;
try {
urlJdbcTemplate.update(sql, urlResource);
bool = true;
} catch (Exception e) {
bool = false;
}
return bool;
}
public int getRolePages() {//查询url数目
String sql = " SELECT COUNT(*) FROM UAA_ROLE ";
return urlJdbcTemplate.queryForInt(sql);
}
public List<RoleBean> getRoleList(int page) {//查询用户授权列表
List<RoleBean> roleBeanList;
String sql = " SELECT * FROM UAA_ROLE LIMIT ?,10 ";
roleBeanList = urlJdbcTemplate.query(sql, new Object[]{(page - 1) * 10}, new RowMapper<RoleBean>() {
@Override
public RoleBean mapRow(ResultSet rs, int i) throws SQLException {
RoleBean roleBean = new RoleBean();
roleBean.setIdentity(rs.getString("user_identity"));
roleBean.setRole(rs.getString("user_role"));
return roleBean;
}
});
return roleBeanList;
}
public boolean roleAdd(String roleIdentity, String role) {//添加用户
String sql = " INSERT INTO UAA_ROLE(USER_IDENTITY,USER_ROLE) VALUES(?,?) ";
boolean bool;
try {
urlJdbcTemplate.update(sql, roleIdentity, role);
bool = true;
} catch (Exception e) {
bool = false;
}
return bool;
}
public boolean roleUpdate(String roleIdentity, String newRole) {//修改role
String sql = " UPDATE UAA_ROLE SET USER_ROLE = ? WHERE USER_IDENTITY = ? ";
boolean bool;
try {
urlJdbcTemplate.update(sql, newRole, roleIdentity);
bool = true;
} catch (Exception e) {
bool = false;
}
return bool;
}
public boolean roleDelete(String roleIdentity) {//删除role
String sql = " DELETE FROM UAA_ROLE WHERE USER_IDENTITY = ? ";
boolean bool;
try {
urlJdbcTemplate.update(sql, roleIdentity);
bool = true;
} catch (Exception e) {
bool = false;
}
return bool;
}
public int getIpPages() {//查询ip数目
String sql = " SELECT COUNT(*) FROM UAA_IP_FILTER ";
return urlJdbcTemplate.queryForInt(sql);
}
public List<RoleBean> getIpList(int page) {//查询ip黑名单列表
List<RoleBean> roleBeanList;
String sql = " SELECT * FROM UAA_IP_FILTER LIMIT ?,10 ";
roleBeanList = urlJdbcTemplate.query(sql, new Object[]{(page - 1) * 10}, new RowMapper<RoleBean>() {
@Override
public RoleBean mapRow(ResultSet rs, int i) throws SQLException {
RoleBean roleBean = new RoleBean();
roleBean.setIdentity(rs.getString("ip"));
roleBean.setRole(rs.getString("ip_role"));
return roleBean;
}
});
return roleBeanList;
}
public boolean ipAdd(String roleIdentity, String role) {//添加用户
String sql = " INSERT INTO UAA_IP_FILTER(IP,IP_ROLE) VALUES(?,?) ";
boolean bool;
try {
urlJdbcTemplate.update(sql, roleIdentity, role);
bool = true;
} catch (Exception e) {
bool = false;
}
return bool;
}
public boolean ipUpdate(String roleIdentity, String newRole) {//修改role
String sql = " UPDATE UAA_IP_FILTER SET IP_ROLE = ? WHERE IP = ? ";
boolean bool;
try {
urlJdbcTemplate.update(sql, newRole, roleIdentity);
bool = true;
} catch (Exception e) {
bool = false;
}
return bool;
}
public boolean ipDelete(String roleIdentity) {//删除role
String sql = " DELETE FROM UAA_IP_FILTER WHERE ip = ? ";
boolean bool;
try {
urlJdbcTemplate.update(sql, roleIdentity);
bool = true;
} catch (Exception e) {
bool = false;
}
return bool;
}
public void setJdbcTemplate(JdbcTemplate template){
this.urlJdbcTemplate = template;
}
}
2、FilterService.java
package com.suning.web.authority;
import java.util.List;
public class FilterService {
private FilterSql filterSql;
public void setFilterSql(FilterSql filterSql) {
this.filterSql = filterSql;
}
public int getUrlPages() {
return filterSql.getUrlPages();
}
public List<UrlBean> getUrlList(int page) {
return filterSql.getUrlList(page);
}
public boolean urlAdd(String urlType, String urlResource, String urlDescription) {
return filterSql.urlAdd(urlType.trim(), urlResource.trim(), urlDescription.trim());
}
public boolean urlUpdate(String urlResource, String newUrlType, String newUrlResource, String newUrlDescription) {
return filterSql.urlUpdate(urlResource.trim(), newUrlType.trim(), newUrlResource.trim(), newUrlDescription.trim());
}
public boolean urlDelete(String urlResource) {
return filterSql.urlDelete(urlResource.trim());
}
public int getRolePages() {
return filterSql.getRolePages();
}
public List<RoleBean> getRoleList(int page) {
return filterSql.getRoleList(page);
}
public boolean roleAdd(String roleIdentity, String role) {
return filterSql.roleAdd(roleIdentity.trim(), role.trim());
}
public boolean roleUpdate(String roleIdentity, String newRole) {
return filterSql.roleUpdate(roleIdentity.trim(), newRole.trim());
}
public boolean roleDelete(String roleIdentity) {
return filterSql.roleDelete(roleIdentity.trim());
}
public int getIpPages() {
return filterSql.getIpPages();
}
public List<RoleBean> getIpList(int page) {
return filterSql.getIpList(page);
}
public boolean ipAdd(String roleIdentity, String role) {
return filterSql.ipAdd(roleIdentity.trim(), role.trim());
}
public boolean ipUpdate(String roleIdentity, String newRole) {
return filterSql.ipUpdate(roleIdentity.trim(), newRole.trim());
}
public boolean ipDelete(String roleIdentity) {
return filterSql.ipDelete(roleIdentity.trim());
}
}
3、RoleBean.java
package com.suning.web.authority;
public class RoleBean {
private String identity;
private String role;
public String getIdentity() {
return identity;
}
public String getRole() {
return role;
}
public void setIdentity(String identity) {
this.identity = identity;
}
public void setRole(String role) {
this.role = role;
}
}
4、UrlBean.java
package com.suning.web.authority;
public class UrlBean {
private String urlType;
private String urlResource;
private String urlDescription;
public String getUrlType() {
return urlType;
}
public void setUrlType(String urlType) {
this.urlType = urlType;
}
public String getUrlResource() {
return urlResource;
}
public void setUrlResource(String urlResource) {
this.urlResource = urlResource;
}
public String getUrlDescription() {
return urlDescription;
}
public void setUrlDescription(String urlDescription) {
this.urlDescription = urlDescription;
}
}
九、mysql建表语句:
(1)创建资源访问表,规定哪些用户,哪些角色可以使用哪些资源。
CREATE TABLE `auth_resource` (
`id` INT(11) NOTNULL AUTO_INCREMENT,
`name` VARCHAR(100)NULL DEFAULT NULL COMMENT '资源名称',
`value` VARCHAR(100)NULL DEFAULT NULL COMMENT '资源值',
`summary`VARCHAR(1000) NULL DEFAULT NULL COMMENT '资源描述',
PRIMARY KEY(`id`)
)
COMMENT='资源访问表'
COLLATE='utf8_general_ci'
ENGINE=InnoDB;
(2)创建角色表
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 '角色代码',
PRIMARY KEY (`id`)
)
COMMENT='角色表'
COLLATE='utf8_general_ci'
ENGINE=InnoDB;
(3)创建资源角色关联表
CREATE TABLE`role_resource` (
`id` INT(11) NOT NULLAUTO_INCREMENT,
`role_id` INT(11) NOTNULL,
`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;
(4)创建用户表
CREATE TABLE `member` (
`id` INT(11) NOT NULLAUTO_INCREMENT,
`user_name`VARCHAR(100) NULL DEFAULT NULL,
`password`VARCHAR(100) NULL DEFAULT NULL,
PRIMARY KEY(`id`)
)
COMMENT='用户表'
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=2;
(5)创建用户角色关联表
CREATE TABLE `member_role` (
`id` INT(11) NOT NULLAUTO_INCREMENT,
`member_id` INT(11)NOT NULL,
`role_id` INT(11) NOTNULL,
PRIMARY KEY(`id`),
UNIQUE INDEX`member_id_role_id` (`member_id`, `role_id`)
)
COMMENT='用户角色关联表'
COLLATE='utf8_general_ci'
ENGINE=InnoDB;
十、测试:
1、创建ROLE_ADMIN和ROLE_ORDINARY两个权限的账户,然后给admin账户分配两个只有管理员能够访问的url,admin账户登录可以访问,ORDINARY账户登录无法访问