1.web.xml加入spring配置如下:
<filter> <filter-name>springSecurityFilterChain</filter-name> <filter-lass>org.springframework.web.filter.DelegatingFilterProxy </filter-class> </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> //spring监听器 <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
2.security_authority.xml配置如下:
<http auto-config='true'> //指定要拦截的请求,以及拥有的权限 <intercept-url pattern="/login.jsp" access="IS_AUTHENTICATED_ANONYMOUSLY"/> <intercept-url pattern="/reg.jsp" access="IS_AUTHENTICATED_ANONYMOUSLY"/> <intercept-url pattern="/admin.jsp" access="ROLE_ADMIN" /> <intercept-url pattern="/index.jsp" access="ROLE_USER,ROLE_ADMIN" /> <form-login login-page="/login.jsp" authentication-failure-url="/error.jsp" default-target-url="/index.jsp"/> //制定数据源,查询语句 <authentication-manager> <authentication-provider> <jdbc-user-service data-source-ref="dataSource" users-by-username-query="select username,password,status as enabled from user where username=?" authorities-by-username-query="select u.username,r.name as authority from user u join user_role ur on u.id=ur.user_id join role r on r.id=ur.role_id where u.username=?" /> </authentication-provider> </authentication-manager> </http>
3.数据库表结构如下:
create table role( id bigint primary key auto_increment, name varchar(50), descn varchar(200) ); create table user( id bigint primary key auto_increment, username varchar(50), password varchar(50), status integer, descn varchar(200) ); create table user_role( user_id bigint, role_id bigint ); alter table user_role add constraint pk_user_role primary key(user_id, role_id); alter table user_role add constraint fk_user_role_user foreign key(user_id) references user(id); alter table user_role add constraint fk_user_role_role foreign key(role_id) references role(id);
4.login.jsp如下:
<fieldset> <legend>登陆</legend> //注意一下的j_spring_security_check、j_username、j_password不能改变名称 <form action="j_spring_security_check" method="post"> username:<input type="text" name="j_username" value="${sessionScope['SPRING_SECURITY_LAST_USERNAME']}"/> </br> password:<input type="text" name="j_password"/> </br> <input type="checkbox" name="spring_security_remember_me" />两周之内不必登陆<br /> <input type="submit" value="submit">|<input type="reset" value="reset"> </form> </fieldset> //错误信息 ${sessionScope['SPRING_SECURITY_LAST_EXCEPTION'].message }