目录结构如下
1.pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>spring_security_1</groupId> <artifactId>spring_security_1</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>spring_security_1 Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <!-- spring版本号 --> <spring.version>3.2.4.RELEASE</spring.version> <!-- mybatis版本号 --> <mybatis.version>3.2.4</mybatis.version> <!-- log4j日志文件管理包版本 --> <slf4j.version>1.6.6</slf4j.version> <log4j.version>1.2.9</log4j.version> </properties> <dependencies> <!-- spring核心包 --> <!-- springframe start --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- springframe end --> <!-- mybatis核心包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- mybatis/spring包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <!-- mysql驱动包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.29</version> </dependency> <!-- junit测试包 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- 日志文件管理包 --> <!-- log start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log end --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javassist</groupId> <artifactId>javassist</artifactId> <version>3.11.0.GA</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-taglibs</artifactId> <version>3.2.4.RELEASE</version> </dependency> </dependencies> <build> <finalName>spring_security_1</finalName> </build> </project>
2.web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>spring_security_1</display-name> <context-param> <param-name>contextConfigLocation</param-name> <!-- 应用上下文配置文件 --> <!-- 两种位置写法 --> <!-- springMvc和spring security 两个配置文件 --> <!-- <param-value>/WEB-INF/spring-servlet.xml</param-value> --> <param-value>classpath:ApplicationContext.xml,classpath:spring-servlet2.xml,classpath:applicationContext-security.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- spring securit start --> <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> <!-- spring securit start --> <!-- 配置spring核心servlet --> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <!-- url-pattern配置为/ 拦截 --> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
3.ApplicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" 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-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <!-- 配置数据源--> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"> <value>com.mysql.jdbc.Driver</value> </property> <property name="url"> <value>jdbc:mysql://localhost/spring_security?useUnicode=true&characterEncoding=utf-8</value> <!--springmybaitis是我的数据库 --> </property> <property name="username"> <value>cqyusp_dev</value> </property> <property name="password"> <value>cqyusp_dev</value> </property> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:mybatis-config.xml"></property> </bean> <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="lqy.UserMapper"></property> <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> </bean> </beans>
4.applicationContext-security.xml
<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-3.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd"> <http auto-config="true" > <access-denied-handler error-page="/accessDenied.jsp"/> <intercept-url pattern="/login.jsp" access="IS_AUTHENTICATED_ANONYMOUSLY" /> <intercept-url pattern="/admin.jsp" access="ROLE_ADMIN" /> <intercept-url pattern="/**" access="ROLE_USER" /> <form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?error=true" default-target-url="/index.jsp" /> </http> <authentication-manager> <authentication-provider> <!-- <password-encoder hash="md5"> <salt-source user-property="username"/> </password-encoder> --> <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> <!-- ApplicationContext配了数据源了 --> <!-- <beans:bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <beans:property name="driverClassName" value="com.mysql.jdbc.Driver"/> <beans:property name="url" value="jdbc:mysql://localhost/spring_security?useUnicode=true&characterEncoding=utf-8"/> <beans:property name="username" value="cqyusp_dev"/> <beans:property name="password" value="cqyusp_dev"/> </beans:bean> --> </beans:beans>
5.mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <mappers> <mapper resource="lqy/User.xml"/> </mappers> </configuration>
6.spring-servlet2.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" 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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 启动注解驱动的Spring MVC功能,注册请求url和注解POJO类方法的映射--> <mvc:annotation-driven /> <!-- 启动包扫描功能,以便注册带有@Controller、@Service、@repository、@Component等注解的类成为spring的bean --> <context:component-scan base-package="lqy" /> <!--这个包根据自己的项目来配置,我的是lqy--> <!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" /> </beans>
再看看java文件
User.java
package lqy; public class User { private String id; private String username; private String password; private String status; private String descn; /** * @return 返回 id。 */ public String getId() { return id; } /** * @param id 设置 id。 */ public void setId(String id) { this.id = id; } /** * @return 返回 username。 */ public String getUsername() { return username; } /** * @param username 设置 username。 */ public void setUsername(String username) { this.username = username; } /** * @return 返回 password。 */ public String getPassword() { return password; } /** * @param password 设置 password。 */ public void setPassword(String password) { this.password = password; } /** * @return 返回 status。 */ public String getStatus() { return status; } /** * @param status 设置 status。 */ public void setStatus(String status) { this.status = status; } /** * @return 返回 descn。 */ public String getDescn() { return descn; } /** * @param descn 设置 descn。 */ public void setDescn(String descn) { this.descn = descn; } }
UserMapper.java
package lqy; public interface UserMapper { public User getUser(User user); public void addUser(User user); }
User.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="lqy.UserMapper"> <select id="getUser" parameterType="lqy.User" resultType="lqy.User"> SELECT id,username,password,status,descn FROM user WHERE id=#{id} </select> <insert id="addUser" parameterType="lqy.User" flushCache="true"> INSERT INTO user (id,username,password,status,descn) VALUES ( #{id},#{username},#{password},#{status},#{descn} ) </insert> </mapper>
WelcomeConstroller.java
package lqy; import java.util.Collection; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class WelcomeConstroller { @Autowired private UserMapper userMapper; @RequestMapping(value = "/welcome", method = RequestMethod.GET) public String welcome(HttpServletRequest request,Model model) { UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext() .getAuthentication() .getPrincipal(); Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities(); model.addAttribute("authorities", authorities.toString()); model.addAttribute("username", userDetails.getUsername()); model.addAttribute("userDetails", userDetails); return "/hello"; } @RequestMapping(value = "/testUser", method = RequestMethod.GET) public String testUser(HttpServletRequest request,Model model) { User user=new User(); //添加两条数据 user.setId("11"); user.setUsername("testUser"); userMapper.addUser(user); return "/hello"; } @SuppressWarnings("resource") public static void main(String[] args) { ApplicationContext ctx=null; ctx=new ClassPathXmlApplicationContext("applicationContext.xml"); UserMapper userMapper=(UserMapper) ctx.getBean("userMapper"); User user=new User(); //添加两条数据 user.setId("10"); user.setUsername("123"); userMapper.addUser(user); System.out.println("添加成功"); } }
运行main方法,成功
sql建表
-- 资源 CREATE TABLE resc( id BIGINT, NAME VARCHAR(50), res_type VARCHAR(50), res_string VARCHAR(200), priority INTEGER, descn VARCHAR(200) ); ALTER TABLE resc ADD CONSTRAINT pk_resc PRIMARY KEY(id); ALTER TABLE resc MODIFY id BIGINT AUTO_INCREMENT; -- 角色 CREATE TABLE role( id BIGINT, NAME VARCHAR(50), descn VARCHAR(200) ); ALTER TABLE role ADD CONSTRAINT pk_role PRIMARY KEY(id); ALTER TABLE role MODIFY id BIGINT AUTO_INCREMENT; -- 用户 CREATE TABLE USER( id BIGINT, username VARCHAR(50), PASSWORD VARCHAR(50), STATUS INTEGER, descn VARCHAR(200) ); ALTER TABLE USER ADD CONSTRAINT pk_user PRIMARY KEY(id); ALTER TABLE USER MODIFY id BIGINT AUTO_INCREMENT; -- 资源角色连接表 CREATE TABLE resc_role( resc_id BIGINT, role_id BIGINT ); ALTER TABLE resc_role ADD CONSTRAINT pk_resc_role PRIMARY KEY(resc_id, role_id); ALTER TABLE resc_role ADD CONSTRAINT fk_resc_role_resc FOREIGN KEY(resc_id) REFERENCES resc(id); ALTER TABLE resc_role ADD CONSTRAINT fk_resc_role_role FOREIGN KEY(role_id) REFERENCES role(id); -- 用户角色连接表 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); INSERT INTO USER(id,username,PASSWORD,STATUS,descn) VALUES(1,'admin','admin',1,'管理员'); INSERT INTO USER(id,username,PASSWORD,STATUS,descn) VALUES(2,'user','user',1,'用户'); INSERT INTO role(id,NAME,descn) VALUES(1,'ROLE_ADMIN','管理员角色'); INSERT INTO role(id,NAME,descn) VALUES(2,'ROLE_USER','用户角色'); INSERT INTO resc(id,NAME,res_type,res_string,priority,descn) VALUES(1,'','URL','/admin.jsp',1,''); INSERT INTO resc(id,NAME,res_type,res_string,priority,descn) VALUES(2,'','URL','/**',2,''); INSERT INTO resc_role(resc_id,role_id) VALUES(1,1); INSERT INTO resc_role(resc_id,role_id) VALUES(2,1); INSERT INTO resc_role(resc_id,role_id) VALUES(2,2); INSERT INTO user_role(user_id,role_id) VALUES(1,1); INSERT INTO user_role(user_id,role_id) VALUES(1,2); INSERT INTO user_role(user_id,role_id) VALUES(2,2);
测试输入 http://localhost:8080/spring_security_1/login.jsp
登陆成功
剩下jsp页面
hello.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> </head> <body> <h2>${username }</h2> <h3>${authorities }</h3> </body> </html>
accessDenied.jsp
<%@ page contentType="text/html;charset=UTF-8"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Access Denied</title> <style type="text/css"> div.error { width: 260px; border: 2px solid red; background-color: yellow; text-align: center; } </style> </head> <body> <h1>Access Denied</h1> <hr> <div class="error"> 访问被拒绝<br> ${requestScope['SPRING_SECURITY_403_EXCEPTION'].message} </div> <hr> </body> </html>
admin.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>登录首页</title> </head> <body> <span color="red">登录成功!</span> </body> </html>
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%String path=request.getContextPath(); %> <%@ taglib uri="http://www.springframework.org/security/tags" prefix="sec" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>登录首页</title> </head> <body> <div>username : <sec:authentication property="name"/></div> <span color="red">登录成功!</span> <a href="<%=path %>/welcome">welcome</a> </body> </html>
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String path=request.getContextPath(); %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>login</title> </head> <body> <div class="error ${param.error == true ? '' : 'hide'}"> ${sessionScope['SPRING_SECURITY_LAST_EXCEPTION'].message} </div> <form action="${pageContext.request.contextPath}/j_spring_security_check" method="post"> <fieldset> <legend>登陆</legend> 用户: <input type="text" name="j_username" style="width:150px;" value="${sessionScope['SPRING_SECURITY_LAST_USERNAME']}"/><br /> 密码: <input type="password" name="j_password" style="width:150px;" /><br /> <input type="checkbox" name="_spring_security_remember_me" />两周之内不必登陆<br /> <input type="submit" value="登陆"/> <input type="reset" value="重置"/> </fieldset> </form> </body> </html>