Spring MVC + Spring Security 4.2.3 完整示例DEMO

网上看到不少Security示例,总是缺少很多的环节,对于不甚了解而又急于通过一个简单示例指导入门学习Security的同学,感觉很是苦恼,当初笔者也曾经抓狂过,居然找不到一个完整的可运行demo,本着分享的原则,此处为大家提供一个完成基本认证功能的Security demo,与大家一起学习。

目录结构

先看一下目录结构
下图是整个项目的目录结构清单,包括sql脚本等,随后会把相关的文件内容分别贴出来,寄希望一通ctrl c ctrl v就可以运行,然后再研究各个技术细节

配置文件

为了方便管理,在resources下添加一个目录config,相关配置文件放置在这个目录下

web.xml

<?xml version="1.0" encoding="UTF-8"?>  
<web-app id="WebApp_ID" version="2.4"  
    xmlns="http://java.sun.com/xml/ns/j2ee"   
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
    
    <!-- SpringSecurity必须的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>/*</url-pattern>  
    </filter-mapping>  
    <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>  
        classpath:config/spring-security.xml
        classpath:config/applicationContext.xml
        </param-value>  
    </context-param>  
    <servlet>  
        <servlet-name>spring</servlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
        
        <init-param>
        	<param-name>contextConfigLocation</param-name>
            <param-value>classpath:config/spring-servlet.xml</param-value>
    	</init-param>
        <load-on-startup>1</load-on-startup>  
    </servlet>  
    <servlet-mapping>  
        <servlet-name>spring</servlet-name>  
        <url-pattern>/</url-pattern>  
    </servlet-mapping>  
    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    </listener>  
</web-app>  

其中这一段是配置 Spring Security过滤器

 <!-- SpringSecurity必须的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>/*</url-pattern>  
    </filter-mapping>  

maven之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>com.mybus</groupId>
  <artifactId>sec1</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>sec1 Maven Webapp</name>
  <url>http://maven.apache.org</url>
  
  <properties>
	<java.version>1.8</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.encoding>UTF-8</maven.compiler.encoding>  
  </properties>
	
  <dependencies>
  	<dependency>
		<groupId>c3p0</groupId>
		<artifactId>c3p0</artifactId>
		<version>0.9.1.2</version>
	</dependency>
	
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>5.1.22</version>
	</dependency>
	
	<!-- Spring 4.3.3 -->
	<!-- Core Container 核心容器 -->
	<!-- 核心工具类,Spring其它模块大量使用Spring-core -->
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-core</artifactId>
	    <version>4.3.3.RELEASE</version>
	</dependency>
	<!-- 运行时Spring容器 -->
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-context</artifactId>
	    <version>4.3.3.RELEASE</version>
	</dependency>
	<!-- Spring容器对第三方包的集成 -->
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-context-support</artifactId>
	    <version>4.3.3.RELEASE</version>
	</dependency>
	<!-- Spring定义Bean的支持 -->
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-beans</artifactId>
	    <version>4.3.3.RELEASE</version>
	</dependency>
	<!-- 使用表达式语言在运行时查询和操作对象 -->
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-expression</artifactId>
	    <version>4.3.3.RELEASE</version>
	</dependency>
	<!-- End Core Container 核心容器 -->
	
	<!-- AOP -->
	<!-- 基于代理的AOP支持 -->
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-aop</artifactId>
	    <version>4.3.3.RELEASE</version>
	</dependency>
	<!-- 基于AspectJ的AOP支持 -->
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-aspects</artifactId>
	    <version>4.3.3.RELEASE</version>
	</dependency>
	<!-- aspectj -->        
	<dependency>
	    <groupId>org.aspectj</groupId>
	    <artifactId>aspectjrt</artifactId>
	    <version>1.8.5</version>
	</dependency>
	<dependency>
	    <groupId>org.aspectj</groupId>
	    <artifactId>aspectjweaver</artifactId>
	    <version>1.8.5</version>
	</dependency>       
	<!-- End AOP -->
	
	<!-- 提供基于Servlet的SpringMVC -->
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-webmvc</artifactId>
	    <version>4.3.3.RELEASE</version>
	</dependency>
	
	<!-- 提供对 对象/关系映射技术的支持 -->
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-orm</artifactId>
	    <version>4.3.3.RELEASE</version>
	</dependency>
	
	<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-config -->
	<dependency>
	    <groupId>org.springframework.security</groupId>
	    <artifactId>spring-security-web</artifactId>
	    <version>4.2.3.RELEASE</version>
	</dependency>
	<dependency> 
	    <groupId>org.springframework.security</groupId> 
	    <artifactId>spring-security-config</artifactId> 
	    <version>4.2.3.RELEASE</version> 
	</dependency>
	<dependency>
	    <groupId>org.springframework.security</groupId>
	    <artifactId>spring-security-taglibs</artifactId>
	    <version>4.2.3.RELEASE</version>
	</dependency>
	<dependency>
		<groupId>org.mybatis.spring.boot</groupId>
		<artifactId>mybatis-spring-boot-starter</artifactId>
		<version>1.3.1</version>
	</dependency>
	
	<dependency>
	    <groupId>jstl</groupId>
	    <artifactId>jstl</artifactId>
	    <version>1.2</version>
	</dependency>
	
	<!-- https://mvnrepository.com/artifact/log4j/log4j -->
	<dependency>
	    <groupId>log4j</groupId>
	    <artifactId>log4j</artifactId>
	    <version>1.2.17</version>
	</dependency>
		
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>sec1</finalName>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.5.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-resources-plugin</artifactId>
            <version>3.0.1</version>
            <configuration>
                <encoding>UTF-8</encoding>
            </configuration>
        </plugin>
        
        
    </plugins>
    <resources>  
        <resource>   
            <directory>src/main/resources</directory>  
            <filtering>true</filtering>   
        </resource>
        <resource>
		    <directory>src/main/java</directory>
		    <includes>
		        <include>**/*.xml</include>
		    </includes>
		</resource>
    </resources>  
  </build>
</project>

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:p="http://www.springframework.org/schema/p"  
	xmlns:context="http://www.springframework.org/schema/context"  
	xmlns:aop="http://www.springframework.org/schema/aop"   
	xmlns:tx="http://www.springframework.org/schema/tx"  
	xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr"  
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	
	xsi:schemaLocation="http://www.springframework.org/schema/beans   
	http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  
	http://www.springframework.org/schema/context   
	http://www.springframework.org/schema/context/spring-context-3.2.xsd  
	http://www.springframework.org/schema/aop  
	http://www.springframework.org/schema/aop/spring-aop-3.2.xsd  
	http://www.springframework.org/schema/tx  
	http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
	http://www.springframework.org/schema/mvc
	http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">  
  
    <!-- 激活spring的注解. -->  
    <context:annotation-config />  
  
    <!-- 扫描注解组件并且自动的注入spring beans中.例如,他会扫描@Controller 和@Service下的文件.所以确保此base-package设置正确. -->  
    <context:component-scan base-package="com.*" />  
  
    <!-- 配置注解驱动的Spring MVC Controller 的编程模型.注:次标签只在 Servlet MVC工作! -->  
    <mvc:annotation-driven />  
  	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
		<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/sec?autoreconnect=true&amp;useUnicode=true" />
		<property name="user" value="root" />
		<property name="password" value="root" />
		<property name="acquireIncrement" value="3" />
		<property name="initialPoolSize" value="10" />
		<property name="minPoolSize" value="10" />
		<property name="maxPoolSize" value="20" />
		<property name="maxStatements" value="1000" />
		<property name="numHelperThreads" value="10" />
		<property name="maxIdleTime" value="600" />
	</bean> 
	
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">  
        <property name="dataSource">  
            <ref bean="dataSource" />  
        </property>  
    </bean>
	 
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 
		<!--dataSource属性指定要用到的连接池--> 
		<property name="dataSource" ref="dataSource"/> 
		<!--configLocation属性指定mybatis的核心配置文件--> 
		<property name="configLocation" value="classpath:config/Configuration.xml" /> 
		<!-- 所有配置的mapper文件 -->
		<property name="mapperLocations" value="classpath*:com/dbp/xml/*.xml" />
	</bean> 
  
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.dbp.dao" />
	</bean>
	
	<!-- 以下全部是事务配置(Service层事务) -->
	<!-- 事务管理器配置,单数据源事务 -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"/>
	</bean>
	<!-- 事务拦截规则 -->    
    <aop:config>
		<!-- 这里可配置多个 advice-ref 引用不用的 bean -->
        <aop:advisor id="managerTx" advice-ref="txAdvice" pointcut="execution(* *..service.*.*(..))" order="0"/>
    </aop:config>
	<!-- 使用annotation定义事务(必须和 aop:config 等标签 一起配置才能使用@T标签) -->
	<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="false"/>
    <!-- 事务 执行逻辑 -->
    <tx:advice id="txAdvice">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED" />
        </tx:attributes>
    </tx:advice> 
</beans>  

spring-servlet.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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    
    xsi:schemaLocation="http://www.springframework.org/schema/beans    
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd    
    http://www.springframework.org/schema/context    
    http://www.springframework.org/schema/context/spring-context-3.1.xsd    
    http://www.springframework.org/schema/mvc    
    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">  
  
	<!-- ①:对web包中的action类进行扫描,完成Bean创建和注入 -->
    <context:component-scan base-package="**.controller" />
    <!-- ②:启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
    <!-- ③:对模型视图名称的解析,在模型视图名称添加前后缀 -->
	<bean id="viewResolver" 
		class="org.springframework.web.servlet.view.InternalResourceViewResolver" 
		p:prefix="/jsp/" p:suffix=".jsp"></bean> 
  
</beans>  

Configuration.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>
    <typeAliases> 
    </typeAliases> 
</configuration>

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:aop="http://www.springframework.org/schema/aop"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:security="http://www.springframework.org/schema/security"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.2.xsd">
    
    <!-- 读取错误提示属性文件,实现自定义提示。
	原文件位置 spring-security-core-4.2.3.RELEASE.jar 包中 org/springframework/security/messages_zh_CN.properties 
         可以将其内容拷贝到自定义的属性文件中,修改相关的提示信息,将 basenames 属性值指向自定义属性文件
    -->
    <!-- <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basenames" value="classpath:org/springframework/security/messages_zh_CN"></property>
    </bean> -->
    
    <!-- security="none":对指定的 URL 放行,不拦截。如一些静态文件。另外放行登录 URL 避免拦截 -->
    <security:http security="none" pattern="/auth/login" />
    <security:http security="none" pattern="/js/**" />
    <security:http security="none" pattern="/image/**" />
    
    <security:http auto-config="false" use-expressions="true" access-decision-manager-ref="">
        <security:intercept-url pattern="/auth/login" access="permitAll"/>
        <security:csrf disabled="true"/>
        
    	<!--
        login-page:表示自定义登录页面
        login-processing-url:表示登录时提交的地址
        username-parameter:表示登录时用户名使用的是哪个参数
        password-parameter:表示登录时密码使用的是哪个参数
	    default-target-url:
	                默认情况下,在登录成功后会返回到原本受限制的页面
	                如果用户是直接请求登录页面,登录成功后默认情况下会跳转到当前应用的根路径,即欢迎页面
	    default-target-url 属性可以指定,用户直接访问登录页面并登陆成功后跳转的页面
	                如果想让用户不管是直接请求登录页面,还是通过 Spring Security 引导过来的,登录之后都跳转到指定的页面,可以使用 always-use-default-target 属性为 true 来达到这一效果
	    authentication-success-handler-ref:
	                对应一个 AuthencticationSuccessHandler 实现类的引用
	                登录认证成功后会调用指定 AuthenticationSuccessHandler 的 onAuthenticationSuccess 方法,在此方法中进行登陆成功后的处理
	                此时 default-target-url 失效
	    authentication-failure-url:
	                指定登录认证失败后跳转的页面
	                默认情况下登录失败后会返回登录页面
	                登录失败后跳转的页面,也需放行,否则又会被重定向到登录页面。
	    authentication-failure-handler-ref:
	                对应一个用于处理认证失败的 AuthenticationFailureHandler 实现类。
	                指定了该属性,Spring Security 在认证失败后会调用指定 AuthenticationFailureHandler 的 onAuthenticationFailure 方法对认证失败进行处理
	                此时 authentication-failure-url 属性将不再发生作用。
        -->
		<security:form-login 
			login-page="/auth/login"
			login-processing-url="/j_spring_security_check"
			username-parameter="username"
			password-parameter="password"
			default-target-url="/main/common"
			
            authentication-failure-url="/auth/login?error=true"
            
			authentication-success-handler-ref="authenticationSuccessHandlerImpl"
			authentication-failure-handler-ref="authenticationFailureHandlerImpl" />
			
		<security:logout 
			logout-success-url="/auth/login"
			logout-url="/auth/logout"
			invalidate-session="true" />
		
		<!-- 设置访问所有的 URL 都必须登录 -->
        <security:intercept-url pattern="/**" access="isAuthenticated()" />	
        
        <!-- 
       	access="hasRole('ROLE_ADMIN')":表示拥有 ADMIN 角色的用户可以访问,否则 403。
       	hasRole('ROLE_ADMIN') 为 SpEL 表达式,必须以 ROLE_ 开头
         -->
        <security:intercept-url pattern="/user/**" access="hasRole('ROLE_USER')"/>
        
        <!-- 指定登陆认证成功后,用户访问未授权的 URL 将跳转的 URL -->
        <security:access-denied-handler error-page="/error/403"/>
        
        <security:session-management session-fixation-protection="none">
	        <!-- 
	        max-sessions="1":同一用户只能在一个浏览器登录,当尝试在其他浏览器登陆时将被拒绝
	        error-if-maximum-exceeded="true":当设置了此属性,尝试在其他浏览器登录时,则原会话将被终止,将在新窗口建立新会话
	        -->
	        <security:concurrency-control max-sessions="1"/>
        </security:session-management>
        
    </security:http>
    
    <!-- 认证成功后的处理类 -->
    <bean id="authenticationSuccessHandlerImpl" class="com.security.auth.AuthenticationSuccessHandlerImpl"/>
    <!-- 认证失败后的处理类 -->
    <bean id="authenticationFailureHandlerImpl" class="com.security.auth.AuthenticationFailureHandlerImpl"/>
    
    <!-- 登录认证 -->
    <security:authentication-manager>
        <!-- 直接将用户名密码写在配置文件中
        <security:authentication-provider>
            <security:user-service>
                <security:user name="user" password="user" authorities="ROLE_USER" />
                <security:user name="admin" password="admin" authorities="ROLE_USER, ROLE_ADMIN" />
            </security:user-service> 
        </security:authentication-provider>
        -->
        <!-- 使用自定义的类对用户提交的密码进行加密操作,实现 AuthenticationSuccessHandler 接口 -->
        <security:authentication-provider user-service-ref="customUserDetailsService">
            <security:password-encoder ref="passwordEncoder"/>
        </security:authentication-provider>
    </security:authentication-manager>
    
    <!-- 对密码进行MD5编码 -->  
    <bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder"/>  

    <bean id="customUserDetailsService" class="com.security.service.CustomUserDetailsService"></bean>
    
</beans>  

sec.sql

这是一个本示例demo使用的数据库脚本文件,数据库名为sec,其中有一个sys_user表,表中一条数据,其中的用户名密码是admin/admin

DROP TABLE IF EXISTS `sys_user`;

CREATE TABLE `sys_user` (
  `uid` varchar(32) NOT NULL COMMENT '主键ID',
  `username` varchar(20) DEFAULT NULL COMMENT '系统账号',
  `password` varchar(32) DEFAULT NULL COMMENT '密码',
  `benabled` int(11) DEFAULT '0' COMMENT '状态(0:正常)',
  `sphone` varchar(20) DEFAULT NULL COMMENT '电话',
  `dcreatedate` date DEFAULT NULL COMMENT '创建时间',
  PRIMARY KEY (`uid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert  into `sys_user`(`uid`,`username`,`password`,`benabled`,`sphone`,`dcreatedate`) values ('admin','admin','21232f297a57a5a743894a0e4a801fc3',0,'',NULL);

java代码

mybatis实体映射类

com.dbp.dao.SysUserMapper.java

package com.dbp.dao;

import com.dbp.model.SysUser;
import com.dbp.model.SysUserExample;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface SysUserMapper {
    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table sys_user
     *
     * @mbggenerated
     */
    int countByExample(SysUserExample example);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table sys_user
     *
     * @mbggenerated
     */
    int deleteByPrimaryKey(String uid);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table sys_user
     *
     * @mbggenerated
     */
    int insert(SysUser record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table sys_user
     *
     * @mbggenerated
     */
    int insertSelective(SysUser record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table sys_user
     *
     * @mbggenerated
     */
    List<SysUser> selectByExample(SysUserExample example);
    
    SysUser selectByUsername(String username);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table sys_user
     *
     * @mbggenerated
     */
    SysUser selectByPrimaryKey(String uid);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table sys_user
     *
     * @mbggenerated
     */
    int updateByPrimaryKeySelective(SysUser record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table sys_user
     *
     * @mbggenerated
     */
    int updateByPrimaryKey(SysUser record);
}

com.dbp.model.SysUser.java

package com.dbp.model;

import java.util.Date;

public class SysUser {
    private String uid;
    private String username;
    private String password;
    private Integer benabled;
    private String sphone;
    private Date dcreatedate;

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid == null ? null : uid.trim();
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username == null ? null : username.trim();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

    public Integer getBenabled() {
        return benabled;
    }

    public void setBenabled(Integer benabled) {
        this.benabled = benabled;
    }

    public String getSphone() {
        return sphone;
    }

    public void setSphone(String sphone) {
        this.sphone = sphone == null ? null : sphone.trim();
    }

    public Date getDcreatedate() {
        return dcreatedate;
    }

    public void setDcreatedate(Date dcreatedate) {
        this.dcreatedate = dcreatedate;
    }
}

com.dbp.model.SysUserExample.java

package com.dbp.model;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

public class SysUserExample {
    protected String orderByClause;
    protected boolean distinct;
    protected List<Criteria> oredCriteria;
    protected Integer limitStart;
    protected Integer pageSize;
    
    public SysUserExample() {
        oredCriteria = new ArrayList<Criteria>();
    }
    
    public void setOrderByClause(String orderByClause) {
        this.orderByClause = orderByClause;
    }

    public String getOrderByClause() {
        return orderByClause;
    }

    public void setDistinct(boolean distinct) {
        this.distinct = distinct;
    }

    public boolean isDistinct() {
        return distinct;
    }

    public List<Criteria> getOredCriteria() {
        return oredCriteria;
    }

    public void or(Criteria criteria) {
        oredCriteria.add(criteria);
    }

    public Criteria or() {
        Criteria criteria = createCriteriaInternal();
        oredCriteria.add(criteria);
        return criteria;
    }

    public Criteria createCriteria() {
        Criteria criteria = createCriteriaInternal();
        if (oredCriteria.size() == 0) {
            oredCriteria.add(criteria);
        }
        return criteria;
    }

    protected Criteria createCriteriaInternal() {
        Criteria criteria = new Criteria();
        return criteria;
    }

    public void clear() {
        oredCriteria.clear();
        orderByClause = null;
        distinct = false;
    }

    public void setLimitStart(Integer limitStart) {
        this.limitStart=limitStart;
    }

    public Integer getLimitStart() {
        return limitStart;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize=pageSize;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    protected abstract static class GeneratedCriteria {
        protected List<Criterion> criteria;

        protected GeneratedCriteria() {
            super();
            criteria = new ArrayList<Criterion>();
        }

        public boolean isValid() {
            return criteria.size() > 0;
        }

        public List<Criterion> getAllCriteria() {
            return criteria;
        }

        public List<Criterion> getCriteria() {
            return criteria;
        }

        protected void addCriterion(String condition) {
            if (condition == null) {
                throw new RuntimeException("Value for condition cannot be null");
            }
            criteria.add(new Criterion(condition));
        }

        protected void addCriterion(String condition, Object value, String property) {
            if (value == null) {
                throw new RuntimeException("Value for " + property + " cannot be null");
            }
            criteria.add(new Criterion(condition, value));
        }

        protected void addCriterion(String condition, Object value1, Object value2, String property) {
            if (value1 == null || value2 == null) {
                throw new RuntimeException("Between values for " + property + " cannot be null");
            }
            criteria.add(new Criterion(condition, value1, value2));
        }

        protected void addCriterionForJDBCDate(String condition, Date value, String property) {
            if (value == null) {
                throw new RuntimeException("Value for " + property + " cannot be null");
            }
            addCriterion(condition, new java.sql.Date(value.getTime()), property);
        }

        protected void addCriterionForJDBCDate(String condition, List<Date> values, String property) {
            if (values == null || values.size() == 0) {
                throw new RuntimeException("Value list for " + property + " cannot be null or empty");
            }
            List<java.sql.Date> dateList = new ArrayList<java.sql.Date>();
            Iterator<Date> iter = values.iterator();
            while (iter.hasNext()) {
                dateList.add(new java.sql.Date(iter.next().getTime()));
            }
            addCriterion(condition, dateList, property);
        }

        protected void addCriterionForJDBCDate(String condition, Date value1, Date value2, String property) {
            if (value1 == null || value2 == null) {
                throw new RuntimeException("Between values for " + property + " cannot be null");
            }
            addCriterion(condition, new java.sql.Date(value1.getTime()), new java.sql.Date(value2.getTime()), property);
        }

        public Criteria andUidIsNull() {
            addCriterion("uid is null");
            return (Criteria) this;
        }

        public Criteria andUidIsNotNull() {
            addCriterion("uid is not null");
            return (Criteria) this;
        }

        public Criteria andUidEqualTo(String value) {
            addCriterion("uid =", value, "uid");
            return (Criteria) this;
        }

        public Criteria andUidNotEqualTo(String value) {
            addCriterion("uid <>", value, "uid");
            return (Criteria) this;
        }

        public Criteria andUidGreaterThan(String value) {
            addCriterion("uid >", value, "uid");
            return (Criteria) this;
        }

        public Criteria andUidGreaterThanOrEqualTo(String value) {
            addCriterion("uid >=", value, "uid");
            return (Criteria) this;
        }

        public Criteria andUidLessThan(String value) {
            addCriterion("uid <", value, "uid");
            return (Criteria) this;
        }

        public Criteria andUidLessThanOrEqualTo(String value) {
            addCriterion("uid <=", value, "uid");
            return (Criteria) this;
        }

        public Criteria andUidLike(String value) {
            addCriterion("uid like", value, "uid");
            return (Criteria) this;
        }

        public Criteria andUidNotLike(String value) {
            addCriterion("uid not like", value, "uid");
            return (Criteria) this;
        }

        public Criteria andUidIn(List<String> values) {
            addCriterion("uid in", values, "uid");
            return (Criteria) this;
        }

        public Criteria andUidNotIn(List<String> values) {
            addCriterion("uid not in", values, "uid");
            return (Criteria) this;
        }

        public Criteria andUidBetween(String value1, String value2) {
            addCriterion("uid between", value1, value2, "uid");
            return (Criteria) this;
        }

        public Criteria andUidNotBetween(String value1, String value2) {
            addCriterion("uid not between", value1, value2, "uid");
            return (Criteria) this;
        }

        public Criteria andUsernameIsNull() {
            addCriterion("username is null");
            return (Criteria) this;
        }

        public Criteria andUsernameIsNotNull() {
            addCriterion("username is not null");
            return (Criteria) this;
        }

        public Criteria andUsernameEqualTo(String value) {
            addCriterion("username =", value, "username");
            return (Criteria) this;
        }

        public Criteria andUsernameNotEqualTo(String value) {
            addCriterion("username <>", value, "username");
            return (Criteria) this;
        }

        public Criteria andUsernameGreaterThan(String value) {
            addCriterion("username >", value, "username");
            return (Criteria) this;
        }

        public Criteria andUsernameGreaterThanOrEqualTo(String value) {
            addCriterion("username >=", value, "username");
            return (Criteria) this;
        }

        public Criteria andUsernameLessThan(String value) {
            addCriterion("username <", value, "username");
            return (Criteria) this;
        }

        public Criteria andUsernameLessThanOrEqualTo(String value) {
            addCriterion("username <=", value, "username");
            return (Criteria) this;
        }

        public Criteria andUsernameLike(String value) {
            addCriterion("username like", value, "username");
            return (Criteria) this;
        }

        public Criteria andUsernameNotLike(String value) {
            addCriterion("username not like", value, "username");
            return (Criteria) this;
        }

        public Criteria andUsernameIn(List<String> values) {
            addCriterion("username in", values, "username");
            return (Criteria) this;
        }

        public Criteria andUsernameNotIn(List<String> values) {
            addCriterion("username not in", values, "username");
            return (Criteria) this;
        }

        public Criteria andUsernameBetween(String value1, String value2) {
            addCriterion("username between", value1, value2, "username");
            return (Criteria) this;
        }

        public Criteria andUsernameNotBetween(String value1, String value2) {
            addCriterion("username not between", value1, value2, "username");
            return (Criteria) this;
        }

        public Criteria andPasswordIsNull() {
            addCriterion("password is null");
            return (Criteria) this;
        }

        public Criteria andPasswordIsNotNull() {
            addCriterion("password is not null");
            return (Criteria) this;
        }

        public Criteria andPasswordEqualTo(String value) {
            addCriterion("password =", value, "password");
            return (Criteria) this;
        }

        public Criteria andPasswordNotEqualTo(String value) {
            addCriterion("password <>", value, "password");
            return (Criteria) this;
        }

        public Criteria andPasswordGreaterThan(String value) {
            addCriterion("password >", value, "password");
            return (Criteria) this;
        }

        public Criteria andPasswordGreaterThanOrEqualTo(String value) {
            addCriterion("password >=", value, "password");
            return (Criteria) this;
        }

        public Criteria andPasswordLessThan(String value) {
            addCriterion("password <", value, "password");
            return (Criteria) this;
        }

        public Criteria andPasswordLessThanOrEqualTo(String value) {
            addCriterion("password <=", value, "password");
            return (Criteria) this;
        }

        public Criteria andPasswordLike(String value) {
            addCriterion("password like", value, "password");
            return (Criteria) this;
        }

        public Criteria andPasswordNotLike(String value) {
            addCriterion("password not like", value, "password");
            return (Criteria) this;
        }

        public Criteria andPasswordIn(List<String> values) {
            addCriterion("password in", values, "password");
            return (Criteria) this;
        }

        public Criteria andPasswordNotIn(List<String> values) {
            addCriterion("password not in", values, "password");
            return (Criteria) this;
        }

        public Criteria andPasswordBetween(String value1, String value2) {
            addCriterion("password between", value1, value2, "password");
            return (Criteria) this;
        }

        public Criteria andPasswordNotBetween(String value1, String value2) {
            addCriterion("password not between", value1, value2, "password");
            return (Criteria) this;
        }

        public Criteria andBenabledIsNull() {
            addCriterion("benabled is null");
            return (Criteria) this;
        }

        public Criteria andBenabledIsNotNull() {
            addCriterion("benabled is not null");
            return (Criteria) this;
        }

        public Criteria andBenabledEqualTo(Integer value) {
            addCriterion("benabled =", value, "benabled");
            return (Criteria) this;
        }

        public Criteria andBenabledNotEqualTo(Integer value) {
            addCriterion("benabled <>", value, "benabled");
            return (Criteria) this;
        }

        public Criteria andBenabledGreaterThan(Integer value) {
            addCriterion("benabled >", value, "benabled");
            return (Criteria) this;
        }

        public Criteria andBenabledGreaterThanOrEqualTo(Integer value) {
            addCriterion("benabled >=", value, "benabled");
            return (Criteria) this;
        }

        public Criteria andBenabledLessThan(Integer value) {
            addCriterion("benabled <", value, "benabled");
            return (Criteria) this;
        }

        public Criteria andBenabledLessThanOrEqualTo(Integer value) {
            addCriterion("benabled <=", value, "benabled");
            return (Criteria) this;
        }

        public Criteria andBenabledIn(List<Integer> values) {
            addCriterion("benabled in", values, "benabled");
            return (Criteria) this;
        }

        public Criteria andBenabledNotIn(List<Integer> values) {
            addCriterion("benabled not in", values, "benabled");
            return (Criteria) this;
        }

        public Criteria andBenabledBetween(Integer value1, Integer value2) {
            addCriterion("benabled between", value1, value2, "benabled");
            return (Criteria) this;
        }

        public Criteria andBenabledNotBetween(Integer value1, Integer value2) {
            addCriterion("benabled not between", value1, value2, "benabled");
            return (Criteria) this;
        }

        public Criteria andSphoneIsNull() {
            addCriterion("sphone is null");
            return (Criteria) this;
        }

        public Criteria andSphoneIsNotNull() {
            addCriterion("sphone is not null");
            return (Criteria) this;
        }

        public Criteria andSphoneEqualTo(String value) {
            addCriterion("sphone =", value, "sphone");
            return (Criteria) this;
        }

        public Criteria andSphoneNotEqualTo(String value) {
            addCriterion("sphone <>", value, "sphone");
            return (Criteria) this;
        }

        public Criteria andSphoneGreaterThan(String value) {
            addCriterion("sphone >", value, "sphone");
            return (Criteria) this;
        }

        public Criteria andSphoneGreaterThanOrEqualTo(String value) {
            addCriterion("sphone >=", value, "sphone");
            return (Criteria) this;
        }

        public Criteria andSphoneLessThan(String value) {
            addCriterion("sphone <", value, "sphone");
            return (Criteria) this;
        }

        public Criteria andSphoneLessThanOrEqualTo(String value) {
            addCriterion("sphone <=", value, "sphone");
            return (Criteria) this;
        }

        public Criteria andSphoneLike(String value) {
            addCriterion("sphone like", value, "sphone");
            return (Criteria) this;
        }

        public Criteria andSphoneNotLike(String value) {
            addCriterion("sphone not like", value, "sphone");
            return (Criteria) this;
        }

        public Criteria andSphoneIn(List<String> values) {
            addCriterion("sphone in", values, "sphone");
            return (Criteria) this;
        }

        public Criteria andSphoneNotIn(List<String> values) {
            addCriterion("sphone not in", values, "sphone");
            return (Criteria) this;
        }

        public Criteria andSphoneBetween(String value1, String value2) {
            addCriterion("sphone between", value1, value2, "sphone");
            return (Criteria) this;
        }

        public Criteria andSphoneNotBetween(String value1, String value2) {
            addCriterion("sphone not between", value1, value2, "sphone");
            return (Criteria) this;
        }

        public Criteria andDcreatedateIsNull() {
            addCriterion("dcreatedate is null");
            return (Criteria) this;
        }

        public Criteria andDcreatedateIsNotNull() {
            addCriterion("dcreatedate is not null");
            return (Criteria) this;
        }

        public Criteria andDcreatedateEqualTo(Date value) {
            addCriterionForJDBCDate("dcreatedate =", value, "dcreatedate");
            return (Criteria) this;
        }

        public Criteria andDcreatedateNotEqualTo(Date value) {
            addCriterionForJDBCDate("dcreatedate <>", value, "dcreatedate");
            return (Criteria) this;
        }

        public Criteria andDcreatedateGreaterThan(Date value) {
            addCriterionForJDBCDate("dcreatedate >", value, "dcreatedate");
            return (Criteria) this;
        }

        public Criteria andDcreatedateGreaterThanOrEqualTo(Date value) {
            addCriterionForJDBCDate("dcreatedate >=", value, "dcreatedate");
            return (Criteria) this;
        }

        public Criteria andDcreatedateLessThan(Date value) {
            addCriterionForJDBCDate("dcreatedate <", value, "dcreatedate");
            return (Criteria) this;
        }

        public Criteria andDcreatedateLessThanOrEqualTo(Date value) {
            addCriterionForJDBCDate("dcreatedate <=", value, "dcreatedate");
            return (Criteria) this;
        }

        public Criteria andDcreatedateIn(List<Date> values) {
            addCriterionForJDBCDate("dcreatedate in", values, "dcreatedate");
            return (Criteria) this;
        }

        public Criteria andDcreatedateNotIn(List<Date> values) {
            addCriterionForJDBCDate("dcreatedate not in", values, "dcreatedate");
            return (Criteria) this;
        }

        public Criteria andDcreatedateBetween(Date value1, Date value2) {
            addCriterionForJDBCDate("dcreatedate between", value1, value2, "dcreatedate");
            return (Criteria) this;
        }

        public Criteria andDcreatedateNotBetween(Date value1, Date value2) {
            addCriterionForJDBCDate("dcreatedate not between", value1, value2, "dcreatedate");
            return (Criteria) this;
        }
    }

    /**
     * This class was generated by MyBatis Generator.
     * This class corresponds to the database table sys_user
     *
     * @mbggenerated do_not_delete_during_merge
     */
    public static class Criteria extends GeneratedCriteria {

        protected Criteria() {
            super();
        }
    }

    /**
     * This class was generated by MyBatis Generator.
     * This class corresponds to the database table sys_user
     *
     * @mbggenerated
     */
    public static class Criterion {
        private String condition;

        private Object value;

        private Object secondValue;

        private boolean noValue;

        private boolean singleValue;

        private boolean betweenValue;

        private boolean listValue;

        private String typeHandler;

        public String getCondition() {
            return condition;
        }

        public Object getValue() {
            return value;
        }

        public Object getSecondValue() {
            return secondValue;
        }

        public boolean isNoValue() {
            return noValue;
        }

        public boolean isSingleValue() {
            return singleValue;
        }

        public boolean isBetweenValue() {
            return betweenValue;
        }

        public boolean isListValue() {
            return listValue;
        }

        public String getTypeHandler() {
            return typeHandler;
        }

        protected Criterion(String condition) {
            super();
            this.condition = condition;
            this.typeHandler = null;
            this.noValue = true;
        }

        protected Criterion(String condition, Object value, String typeHandler) {
            super();
            this.condition = condition;
            this.value = value;
            this.typeHandler = typeHandler;
            if (value instanceof List<?>) {
                this.listValue = true;
            } else {
                this.singleValue = true;
            }
        }

        protected Criterion(String condition, Object value) {
            this(condition, value, null);
        }

        protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
            super();
            this.condition = condition;
            this.value = value;
            this.secondValue = secondValue;
            this.typeHandler = typeHandler;
            this.betweenValue = true;
        }

        protected Criterion(String condition, Object value, Object secondValue) {
            this(condition, value, secondValue, null);
        }
    }
}

com.dbp.xml.SysUserMapper.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="com.dbp.dao.SysUserMapper" >
  <resultMap id="BaseResultMap" type="com.dbp.model.SysUser" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    <id column="uid" property="uid" jdbcType="VARCHAR" />
    <result column="username" property="username" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
    <result column="benabled" property="benabled" jdbcType="INTEGER" />
    <result column="sphone" property="sphone" jdbcType="VARCHAR" />
    <result column="dcreatedate" property="dcreatedate" jdbcType="DATE" />
  </resultMap>
  <sql id="Example_Where_Clause" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    <where >
      <foreach collection="oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Base_Column_List" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    uid, username, password, benabled, sphone, dcreatedate
  </sql>
  <select id="selectByExample" resultMap="BaseResultMap" parameterType="com.dbp.model.SysUserExample" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    select
    <if test="distinct" >
      distinct
    </if>
    'false' as QUERYID,
    <include refid="Base_Column_List" />
    from sys_user
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null" >
      order by ${orderByClause}
    </if>
    <if test="limitStart != null and limitStart>=0" >
      limit #{limitStart} , #{pageSize}
    </if>
  </select>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    select 
    <include refid="Base_Column_List" />
    from sys_user
    where uid = #{uid,jdbcType=VARCHAR}
  </select>
  <select id="selectByUsername" resultMap="BaseResultMap" parameterType="java.lang.String" >
    select 
    <include refid="Base_Column_List" />
    from sys_user
    where uid = #{susername,jdbcType=VARCHAR}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.String" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    delete from sys_user
    where uid = #{uid,jdbcType=VARCHAR}
  </delete>
  <insert id="insert" parameterType="com.dbp.model.SysUser" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    insert into sys_user (uid, username, password, 
      benabled, sphone, dcreatedate
      )
    values (#{uid,jdbcType=VARCHAR}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 
      #{benabled,jdbcType=INTEGER}, #{sphone,jdbcType=VARCHAR}, #{dcreatedate,jdbcType=DATE}
      )
  </insert>
  <insert id="insertSelective" parameterType="com.dbp.model.SysUser" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    insert into sys_user
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="uid != null" >
        uid,
      </if>
      <if test="username != null" >
        username,
      </if>
      <if test="password != null" >
        password,
      </if>
      <if test="benabled != null" >
        benabled,
      </if>
      <if test="sphone != null" >
        sphone,
      </if>
      <if test="dcreatedate != null" >
        dcreatedate,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="uid != null" >
        #{uid,jdbcType=VARCHAR},
      </if>
      <if test="username != null" >
        #{username,jdbcType=VARCHAR},
      </if>
      <if test="password != null" >
        #{password,jdbcType=VARCHAR},
      </if>
      <if test="benabled != null" >
        #{benabled,jdbcType=INTEGER},
      </if>
      <if test="sphone != null" >
        #{sphone,jdbcType=VARCHAR},
      </if>
      <if test="dcreatedate != null" >
        #{dcreatedate,jdbcType=DATE},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="com.dbp.model.SysUserExample" resultType="java.lang.Integer" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    select count(*) from sys_user
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByPrimaryKeySelective" parameterType="com.dbp.model.SysUser" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    update sys_user
    <set >
      <if test="username != null" >
        username = #{username,jdbcType=VARCHAR},
      </if>
      <if test="password != null" >
        password = #{password,jdbcType=VARCHAR},
      </if>
      <if test="benabled != null" >
        benabled = #{benabled,jdbcType=INTEGER},
      </if>
      <if test="sphone != null" >
        sphone = #{sphone,jdbcType=VARCHAR},
      </if>
      <if test="dcreatedate != null" >
        dcreatedate = #{dcreatedate,jdbcType=DATE},
      </if>
    </set>
    where uid = #{uid,jdbcType=VARCHAR}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.dbp.model.SysUser" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    update sys_user
    set username = #{username,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR},
      benabled = #{benabled,jdbcType=INTEGER},
      sphone = #{sphone,jdbcType=VARCHAR},
      dcreatedate = #{dcreatedate,jdbcType=DATE}
    where uid = #{uid,jdbcType=VARCHAR}
  </update>
</mapper>

控制类

com.controller.LoginLogoutController.java

package com.controller;

import org.apache.log4j.Logger;  
import org.springframework.stereotype.Controller;  
import org.springframework.ui.ModelMap;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestMethod;  
import org.springframework.web.bind.annotation.RequestParam;  
  
@Controller  
@RequestMapping("auth")  
public class LoginLogoutController {  
  
    protected static Logger logger = Logger.getLogger("controller");  
  
    /** 
     * 指向登录页面 
     */    
    @RequestMapping(value = "/login")  
    public String getLoginPage(@RequestParam(value = "error", required = false) boolean error, ModelMap model) {  
        logger.debug("Received request to show login page");  

        if (error == true) {  
            //Assign an error message  
            model.put("error", "You have entered an invalid username or password!");  
        } else {  
            model.put("error", "");  
        }  
        return "loginpage";  
    }
    
    /** 
     * 取消登录 
     */    
    @RequestMapping(value = "/logout")  
    public String getLogoutPage(@RequestParam(value = "error", required = false) boolean error, ModelMap model) {  
        //添加自己的业务逻辑
    	
        return "loginpage";  
    } 
  
    /** 
     * 指定无访问权限页面 
     *  
     * @return 
     */   
    @RequestMapping(value = "/denied", method = RequestMethod.GET)  
    public String getDeniedPage() {  
  
        logger.debug("Received request to show denied page");  
  
        return "deniedpage";  
  
    }  
}  

com.controller.MainController.java

package com.controller;

import org.apache.log4j.Logger;  
import org.springframework.stereotype.Controller;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestMethod;  
  
@Controller  
@RequestMapping("/main")
public class MainController {
    protected static Logger logger = Logger.getLogger("controller");
  
    /** 
     * 跳转到commonpage页面
     *  
     * @return
     */
    @RequestMapping(value = "/common", method = RequestMethod.GET)
    public String getCommonPage() {
        logger.debug("Received request to show common page");
        return "commonpage";
    }
  
    /** 
     * 跳转到adminpage页面
     *  
     * @return
     */   
    @RequestMapping(value = "/admin", method = RequestMethod.GET)
    public String getAadminPage() {
        logger.debug("Received request to show admin page");
        return "adminpage";
  
    }  
  
}  

security权限控制相关类

com.security.auth.AuthenticationFailureHandlerImpl.java

package com.security.auth;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

/**
 * 用户登录认证失败后
 */
public class AuthenticationFailureHandlerImpl implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        //AuthenticationException 存放着异常信息,获取出来,放到 Request中,转发到登录页面。
        request.setAttribute("error", exception.getMessage());
        request.getRequestDispatcher("/auth/login?error=true").forward(request, response);
    }

}

com.security.auth.AuthenticationSuccessHandlerImpl.java

package com.security.auth;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import com.dbp.dao.SysUserMapper;
import com.dbp.model.SysUser;

/**
 * 登录认证成功后
 */
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {
    @Resource
    private SysUserMapper mapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
    	//UserDetails 中存放着用户名等信息
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        //获取该用户信息,根据自己的业务规则写
        SysUser sysuser = this.mapper.selectByUsername(userDetails.getUsername());
        //将用户放到 Session
        request.getSession().setAttribute("_sysuser", sysuser);
        //跳转到主页
        response.sendRedirect(request.getContextPath() + "/main/common");
    }

}

com.security.service.CustomUserDetailsService.java

package com.security.service;


import java.util.ArrayList;  
import java.util.Collection;  
import java.util.List;  
import javax.annotation.Resource;

import org.apache.log4j.Logger;  

import com.dbp.dao.SysUserMapper;
import com.dbp.model.SysUser;

import org.springframework.dao.DataAccessException;  
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;  
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;  
import org.springframework.security.core.userdetails.UserDetails;  
import org.springframework.security.core.userdetails.UserDetailsService;  
import org.springframework.security.core.userdetails.UsernameNotFoundException;  
import org.springframework.util.StringUtils;
  
/** 
 * 一个自定义的service用来和数据库进行操作. 即以后我们要通过数据库保存权限.则需要我们继承UserDetailsService 
 *  
 */  
public class CustomUserDetailsService implements UserDetailsService {  
    protected static Logger logger = Logger.getLogger("service");
    
    @Resource
    private SysUserMapper userMapper;
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {  
    	if(StringUtils.isEmpty(username)) {
            throw new BadCredentialsException("用户名不能为空");
        }
    	
    	UserDetails userdetails = null;  

        try {
	    	//根据用户名从数据库查询用户信息,根据自己的业务规则去写
	        SysUser sysuser = this.userMapper.selectByUsername(username);
	        if(sysuser == null) {
	            throw new BadCredentialsException("用户名不存在");
	        }
	        
	        userdetails = new User(
	        		sysuser.getUsername(),
	        		sysuser.getPassword(),
	        		true,               //激活状态,true:yes;false:no
	                true,               //账号过期状态,true:no;false;yes
	                true,               //证书过期状态,true:no;false;yes
	                true,               //账号锁定状态,true:no;false;yes
	                getAuthorities(1)
	                //AuthorityUtils.createAuthorityList("ROLE_USER")
	                );
  
        } catch (Exception e) {  
            logger.error("Error in retrieving user");  
            throw new UsernameNotFoundException("Error in retrieving user");  
        }  
  
        return userdetails;  
    }  
  
    /** 
     * 访问角色权限,可根据业务情况自行扩展
     *  
     * @param access 
     * @return 
     */  
    public Collection<GrantedAuthority> getAuthorities(Integer access) {  
  
        List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(2);  
  
        //所有的用户默认拥有ROLE_USER权限  
        logger.debug("Grant ROLE_USER to this user");  
        authList.add(new SimpleGrantedAuthority("ROLE_USER"));  
  
        //如果参数access为1.则拥有ROLE_ADMIN权限  
        if (access.compareTo(1) == 0) {
            logger.debug("Grant ROLE_ADMIN to this user");  
            authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));  
        }  
  
        return authList;  
    }  
}  

jsp文件

adminpage.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>admin</title>  
</head>  
<body>  
    <h1>Admin Page</h1>  
    <p>管理员页面</p>  
    <a href="/sec1/auth/login">退出登录</a>  
</body>  
</html>  

commonpage.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>common</title>  
</head>  
<body>  
    <h1>Common Page</h1>  
    <p>每个人都能访问的页面.</p>  
    <a href="/sec1/main/admin"> Go AdminPage </a>  
    <br />  
    <a href="/sec1/auth/login">退出登录</a>  
  
</body>  
</html>  

deniedpage.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>denied</title>  
</head>  
<body>  
    <h1>你的权限不够!</h1>  
    <p>只有拥有Admin权限才能访问!</p>  
    <a href="/sec1/auth/login">退出登录</a>  
</body>  
</html>  

loginpage.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>  

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>  
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>  
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>  
<%@ page isELIgnored="false"%>

<!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>  
  
    <h1>Login</h1>  
  
    <div id="login-error">${error}</div>  
  
    <form action="/sec1/j_spring_security_check" method="post">  
        <p>  
            <label for="username">Username</label> <input id="username" name="username" type="text" />  
        </p>  
  
        <p>  
            <label for="password">Password</label> <input id="password" name="password" type="password" />  
        </p>  
  
        <input type="submit" value="Login" />  

    </form>  
  
</body>  
</html>  

启动并访问

在这里插入图片描述

OK!

到这儿就结束了,以上包含了整个项目的所有代码,下面提供了github的下载链接,拷贝粘贴只是开始,只是希望能够抛砖引玉,希望对寻求入门的同学有所帮助,更深层次的问题还希望大家去查阅更多的技术文档。

代码篇幅有点长,出于Ctrl C Ctrl V即可运行的考虑,为了大家方便还是贴到了这儿。

如有不恰当的地方还请大家指正,并多多提出建议,一起讨论,共同进步。

github中是一个完整的eclipse(luna)项目,包含了项目自身的配置文件,是可以直接运行并看到效果的
github下载地址

最后:
项目中的示例代码,部分copy了热心网友的,时间比较久了,也找不到原地址,还不只是一个帖子,而手上的项目涉及的东西比较多,也不好直接拿出来,只能搞一个简化版的跟大家共享,在此感谢网上各位道友的技术分享,如有冒犯请指出并修改!

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值