首页 > 其他 > 详细

SSH集成开发应用(基于注解的Demo实例详细)

时间:2020-10-24 23:07:07      阅读:43      评论:0      收藏:0      [点我收藏+]

为什么要用SSH框架?

在这我不做过多解释,有兴趣可以移步:使用SSH框架的意义

第一步配置pom.xml

要注意的是struts2要使用注解必须引入注解相关依赖(不只是core):

技术分享图片
<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.zking</groupId>
    <artifactId>SSH_project</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>SSH_project Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <!-- 1.hibernate -->
        <hibernate.version>5.2.12.Final</hibernate.version>
        <!-- mysql -->
        <mysql.version>5.1.44</mysql.version>
        <!-- ehcache -->
        <ehcache.version>2.10.0</ehcache.version>
        <!-- 2.spring -->
        <spring.version>5.0.1.RELEASE</spring.version>
        <!-- 3.struts2 -->
        <struts2.version>2.5.13</struts2.version>
        <!-- 4.log日志(log4j2+slf4j) -->
        <slf4j.version>1.7.7</slf4j.version>
        <log4j2.version>2.9.1</log4j2.version>
        <log4j2.disruptor.version>3.2.0</log4j2.disruptor.version>
        <!-- 5.junit+servlet -->
        <junit.version>4.12</junit.version>
        <servlet.version>4.0.1</servlet.version>
        <!-- 6.jstl+standard -->
        <jstl.version>1.2</jstl.version>
        <standard.version>1.1.2</standard.version>
        <!-- 7.tomcat-jsp -->
        <tomcat.jsp.version>8.5.30</tomcat.jsp.version>
        <!-- 8.jackson -->
        <jackson.version>2.10.0</jackson.version>
        <!-- 9.jwt -->
        <jwt.version>0.9.1</jwt.version>
        <java.jwt.version>3.4.0</java.jwt.version>
    </properties>


    <dependencies>
        <!-- 1.hibernate相关 -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-c3p0</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>${ehcache.version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-c3p0</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-ehcache</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>

        <!-- 2.spring相关 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</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-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- 3.struts2相关 -->
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-core</artifactId>
            <version>${struts2.version}</version>
        </dependency>
        <!-- 注解相关包 -->
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-convention-plugin</artifactId>
            <version>${struts2.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-json-plugin</artifactId>
            <version>${struts2.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-spring-plugin</artifactId>
            <version>${struts2.version}</version>
        </dependency>

        <!-- 4.log4j2+slf4j配置 -->
        <!-- slf4j核心包 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${slf4j.version}</version>
            <scope>runtime</scope>
        </dependency>

        <!--用于与slf4j保持桥接 -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <version>${log4j2.version}</version>
        </dependency>

        <!--核心log4j2jar包 -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>${log4j2.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>${log4j2.version}</version>
        </dependency>

        <!--web工程需要包含log4j-web,非web工程不需要 -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-web</artifactId>
            <version>${log4j2.version}</version>
            <scope>runtime</scope>
        </dependency>
        <!--需要使用log4j2的AsyncLogger需要包含disruptor -->
        <dependency>
            <groupId>com.lmax</groupId>
            <artifactId>disruptor</artifactId>
            <version>${log4j2.disruptor.version}</version>
        </dependency>

        <!-- 5.junit+servlet -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${servlet.version}</version>
            <scope>provided</scope>
        </dependency>

        <!-- 6.jstl+standard -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstl.version}</version>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>${standard.version}</version>
        </dependency>

        <!-- 7.tomcat-jsp-api -->
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jsp-api</artifactId>
            <version>${tomcat.jsp.version}</version>
        </dependency>

        <!-- 8.jackson -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        
        <!-- 9.jwt -->
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>${jwt.version}</version>
        </dependency>
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>${java.jwt.version}</version>
        </dependency>
    </dependencies>
    
    
    <build>
        <finalName>SSH_project</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
    
</project>
View Code

第二步ssh集成配置文件

 技术分享图片

 (1)applicationContext.xml

最核心的部分就是hibernate与spring的集成相关了,包括数据库连接池c3p0的配置以及事务配置(必须的)。

技术分享图片
<?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:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

    <!-- 使用注解 -->
    <context:annotation-config />
    <!-- 扫描包 -->
    <context:component-scan base-package="com.zking.*" />

    <!-- 1.注入数据库配置文件db.properties -->
    <context:property-placeholder
        location="classpath:db.properties" />

    <!-- 2.配置c3p0连接池 -->
    <bean id="dataSource"
        class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${db.username}"></property>
        <property name="password" value="${db.password}"></property>
        <property name="driverClass" value="${db.driverClass}"></property>
        <property name="jdbcUrl" value="${db.jdbcUrl}"></property>
        <!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
        <property name="initialPoolSize"
            value="${db.initialPoolSize}"></property>
        <!--连接池中保留的最大连接数。Default: 15 -->
        <property name="maxPoolSize" value="${db.maxPoolSize}"></property>
        <!--连接池中保留的最小连接数。 -->
        <property name="minPoolSize" value="${db.minPoolSize}" />
        <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
        <property name="maxIdleTime" value="${db.maxIdleTime}" />
        <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
        <property name="acquireIncrement"
            value="${db.acquireIncrement}" />
        <!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements 属于单个connection而不是整个连接池。 
            所以设置这个参数需要考虑到多方面的因素。如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 
            0 -->
        <property name="maxStatements" value="${db.maxStatements}" />
        <!--每60秒检查所有连接池中的空闲连接。Default: 0 -->
        <property name="idleConnectionTestPeriod"
            value="${db.idleConnectionTestPeriod}" />
        <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->
        <property name="acquireRetryAttempts"
            value="${db.acquireRetryAttempts}" />
        <!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效 保留,并在下次调用getConnection()的时候继续尝试获取连接。 
            如果设为true,那么在尝试 获取连接失败后该数据源将申明已断开并永久关闭。Default: false -->
        <property name="breakAfterAcquireFailure"
            value="${db.breakAfterAcquireFailure}" />
        <!--因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的 时候都将校验其有效性。建议使用idleConnectionTestPeriod 
            或automaticTestTable 等方法来提升连接测试的性能。Default: false -->
        <property name="testConnectionOnCheckout"
            value="${db.breakAfterAcquireFailure}" />
    </bean>

    <!-- 3.注册LocalSessionFactoryBean,spring与hibernate集成,舍弃hibernate.cfg.xml核心配置文件 -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <!-- 数据源 -->
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>
        <!-- hibernate相关属性 -->
        <property name="hibernateProperties">
            <props>
                <prop key="dialect">org.hibernate.dialect.MySQLDialect</prop>
                <!--spring与Hibernate集成无法显示sql语句问题,请见集成后hibernate无法显示sql语句.txt -->
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.connection.autocommit">false</prop>
                <!-- 开启hibernate的二级缓存 -->
                <prop key="hibernate.cache.use_second_level_cache">    true</prop>
                <!-- 开启查询缓存 -->
                <prop key="hibernate.cache.use_query_cache">true</prop>
                <!-- EhCache驱动 -->
                <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
            </props>
        </property>
        <!-- 实体映射文件 -->
        <property name="packagesToScan">
            <list>
                <value>com.zking.*</value>
            </list>
        </property>
    </bean>

    <!-- 4.spring声明式事物 -->
    <!--1) 开启自动代理 -->
    <!-- 代理对象=目标+通知 , -->
    <aop:aspectj-autoproxy />

    <!--2) 事务管理器 -->
    <!-- Session session=SessionFactoryUtils.openSession(); Transaction trans=session.beginTransaction(); 
        // CRUD session.save() trans.commit(); SessionFactoryUtils.closeSession(); -->
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <!--3) 定义事务特性 (环绕通知) -->
    <tx:advice id="txAdvice"
        transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />

            <tx:method name="edit*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />

            <tx:method name="del*" propagation="REQUIRED" />
            <tx:method name="remove*" propagation="REQUIRED" />

            <tx:method name="load*" propagation="REQUIRED"
                read-only="true" />
            <tx:method name="list*" propagation="REQUIRED"
                read-only="true" />
            <tx:method name="select*" propagation="REQUIRED"
                read-only="true" />
            <tx:method name="query*" propagation="REQUIRED"
                read-only="true" />

            <tx:method name="do*" propagation="REQUIRED" />
        </tx:attributes>
    </tx:advice>

    <!--4) 定义切入点 -->
    <!-- 适配器=通知+切入点 通知:环绕事物管理通知 切入点: -->
    <aop:config>
        <!-- pointcut属性用来定义一个切入点,分成四个部分理解 [* ][*..][*Biz][.*(..)] -->
        <!-- A: 返回类型,*表示返回类型不限 -->
        <!-- B: 包名,*..表示包名不限 -->
        <!-- C: 类或接口名,*Biz表示类或接口必须以Biz结尾 -->
        <!-- D: 方法名和参数,*(..)表示方法名不限,参数类型和个数不限 -->

        <!-- 返回类型不限、包名不限、必须Biz结尾的类或接口、方法名和参数类型及个数不限 例如: IBookBiz *Biz BookBizImpl 
            com.zking.ssh.biz.BookBiz *(..) com.zking.ssh.biz.OrderBiz *(..) Biz和Dao区别 
            User -> UserDao -> addUser User_Role -> UserRoleDao -> addUserRole Biz -> 
            UserBiz -> UserDao和UserRoleDao ..... -->
        <aop:advisor advice-ref="txAdvice"
            pointcut="execution(* *..*Biz.*(..))" />
    </aop:config>

    <!-- 5.注入HibernateTemplate模板 -->
    <bean id="hibernateTemplate"
        class="org.springframework.orm.hibernate5.HibernateTemplate">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <!-- 6.分包分模块开发 -->
     <bean id="baseDao" class="com.zking.base.dao.BaseDao"
        abstract="true">
        <property name="hibernateTemplate" ref="hibernateTemplate" />
    </bean> 

    <!-- BaseBiz -->
    <bean id="baseBiz" class="com.zking.base.biz.BaseBiz"
        abstract="true">
    </bean>

    <!-- BaseAction -->
    <bean id="baseAction" class="com.zking.base.action.BaseAction"
        abstract="true">
    </bean>
</beans>
View Code

(2)db.properties(需要修改自己的用户名和mysql密码,以及要连接的数据库URL)

技术分享图片
db.username=root
db.password=123456
db.driverClass=com.mysql.jdbc.Driver
db.jdbcUrl=jdbc:mysql://localhost:3306/crm?useSSL=false
db.initialPoolSize=10
db.maxPoolSize=20
db.minPoolSize=5
db.maxIdleTime=60
db.acquireIncrement=5
db.maxStatements=0
db.idleConnectionTestPeriod=60
db.acquireRetryAttempts=30
db.breakAfterAcquireFailure=true
db.testConnectionOnCheckout=false
View Code

(3)struts.xml(里面讲的很详细了)

技术分享图片
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
    "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
    <!-- 开启struts2的开发者模式,错误信息提示详细 -->
    <constant name="struts.devMode" value="true"></constant>
    <!-- 启用struts2配置文件自动加载模式 -->
    <constant name="struts.configuration.xml.reload" value="true"></constant>
    <!-- 将action创建交由spring容器来管理 -->
      <constant name="struts.objectFactory" value="spring"></constant>
      <!-- 打开动态方法调用 -->
      <constant name="struts.enable.DynamicMethodInvocation" value="true" /> 
    <!-- 指定资源编码类型 -->
    <constant name="struts.i18n.encoding" value="UTF-8" /> 
    <!-- 指定每次请求到达,重新加载资源文件 -->
    <constant name="struts.i18n.reload" value="false" />
    <!--  启动注解要求的约定包名  -->
    <constant name="struts.convention.package.locators" value="action,actions" />
    <!-- 拦截请求后缀配置 -->
    <constant name="struts.action.extension" value="action,do" />
    <!-- 扫描包下的所有Action -->
     <constant name="struts.convention.action.packages" value="com.zking" />
     <!-- 配置默认继承包 -->
     <constant name="struts.convention.default.parent.package" value="struts-default" />  
    
    <package name="struts-base" abstract="true"  extends="struts-default">
        <!-- 开启struts2动态方法调用 -->
        <global-allowed-methods>regex:.*</global-allowed-methods>
    </package>
</struts>
View Code

(4)ehcache.xml(一个缓存框架,可选)

技术分享图片
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">
    <!--磁盘存储:将缓存中暂时不使用的对象,转移到硬盘,类似于Windows系统的虚拟内存-->
    <!--path:指定在硬盘上存储对象的路径-->
    <!--java.io.tmpdir 是默认的临时文件路径。 可以通过如下方式打印出具体的文件路径 System.out.println(System.getProperty("java.io.tmpdir"));-->
    <diskStore path="java.io.tmpdir"/>


    <!--defaultCache:默认的管理策略-->
    <!--eternal:设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断-->
    <!--maxElementsInMemory:在内存中缓存的element的最大数目-->
    <!--overflowToDisk:如果内存中数据超过内存限制,是否要缓存到磁盘上-->
    <!--diskPersistent:是否在磁盘上持久化。指重启jvm后,数据是否有效。默认为false-->
    <!--timeToIdleSeconds:对象空闲时间(单位:秒),指对象在多长时间没有被访问就会失效。只对eternal为false的有效。默认值0,表示一直可以访问-->
    <!--timeToLiveSeconds:对象存活时间(单位:秒),指对象从创建到失效所需要的时间。只对eternal为false的有效。默认值0,表示一直可以访问-->
    <!--memoryStoreEvictionPolicy:缓存的3 种清空策略-->
    <!--FIFO:first in first out (先进先出)-->
    <!--LFU:Less Frequently Used (最少使用).意思是一直以来最少被使用的。缓存的元素有一个hit 属性,hit 值最小的将会被清出缓存-->
    <!--LRU:Least Recently Used(最近最少使用). (ehcache 默认值).缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存-->
    <defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false"
                  timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU"/>
    

    <!--name: Cache的名称,必须是唯一的(ehcache会把这个cache放到HashMap里)-->
      <cache name="dictCache" eternal="false" maxElementsInMemory="300"
           overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"
           timeToLiveSeconds="3000" memoryStoreEvictionPolicy="LRU"></cache>
</ehcache>
View Code

(5)log4j2.xml(日志调试相关)

技术分享图片
<?xml version="1.0" encoding="UTF-8"?>

<!-- status : 指定log4j本身的打印日志的级别.ALL< Trace < DEBUG < INFO < WARN < ERROR 
    < FATAL < OFF。 monitorInterval : 用于指定log4j自动重新配置的监测间隔时间,单位是s,最小是5s. -->
<Configuration status="WARN" monitorInterval="30">
    <Properties>
        <!-- 配置日志文件输出目录 ${sys:user.home} -->
        <Property name="LOG_HOME">/root/workspace/lucenedemo/logs</Property>
        <property name="ERROR_LOG_FILE_NAME">/root/workspace/lucenedemo/logs/error</property>
        <property name="WARN_LOG_FILE_NAME">/root/workspace/lucenedemo/logs/warn</property>
        <property name="PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} [%t-%L] %-5level %logger{36} - %msg%n</property>
    </Properties>

    <Appenders>
        <!--这个输出控制台的配置 -->
        <Console name="Console" target="SYSTEM_OUT">
            <!-- 控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) -->
            <ThresholdFilter level="trace" onMatch="ACCEPT"
                onMismatch="DENY" />
            <!-- 输出日志的格式 -->
            <!-- %d{yyyy-MM-dd HH:mm:ss, SSS} : 日志生产时间 %p : 日志输出格式 %c : logger的名称 
                %m : 日志内容,即 logger.info("message") %n : 换行符 %C : Java类名 %L : 日志输出所在行数 %M 
                : 日志输出所在方法名 hostName : 本地机器名 hostAddress : 本地ip地址 -->
            <PatternLayout pattern="${PATTERN}" />
        </Console>

        <!--文件会打印出所有信息,这个log每次运行程序会自动清空,由append属性决定,这个也挺有用的,适合临时测试用 -->
        <!--append为TRUE表示消息增加到指定文件中,false表示消息覆盖指定的文件内容,默认值是true -->
        <File name="log" fileName="logs/test.log" append="false">
            <PatternLayout
                pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </File>
        <!-- 这个会打印出所有的info及以下级别的信息,每次大小超过size, 则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档 -->
        <RollingFile name="RollingFileInfo" fileName="${LOG_HOME}/info.log"
            filePattern="${LOG_HOME}/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log">
            <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) -->
            <ThresholdFilter level="info" onMatch="ACCEPT"
                onMismatch="DENY" />
            <PatternLayout
                pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
            <Policies>
                <!-- 基于时间的滚动策略,interval属性用来指定多久滚动一次,默认是1 hour。 modulate=true用来调整时间:比如现在是早上3am,interval是4,那么第一次滚动是在4am,接着是8am,12am...而不是7am. -->
                <!-- 关键点在于 filePattern后的日期格式,以及TimeBasedTriggeringPolicy的interval, 日期格式精确到哪一位,interval也精确到哪一个单位 -->
                <!-- log4j2的按天分日志文件 : info-%d{yyyy-MM-dd}-%i.log -->
                <TimeBasedTriggeringPolicy interval="1"
                    modulate="true" />
                <!-- SizeBasedTriggeringPolicy:Policies子节点, 基于指定文件大小的滚动策略,size属性用来定义每个日志文件的大小. -->
                <!-- <SizeBasedTriggeringPolicy size="2 kB" /> -->
            </Policies>
        </RollingFile>

        <RollingFile name="RollingFileWarn" fileName="${WARN_LOG_FILE_NAME}/warn.log"
            filePattern="${WARN_LOG_FILE_NAME}/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log">
            <ThresholdFilter level="warn" onMatch="ACCEPT"
                onMismatch="DENY" />
            <PatternLayout
                pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
            <Policies>
                <TimeBasedTriggeringPolicy />
                <SizeBasedTriggeringPolicy size="2 kB" />
            </Policies>
            <!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件,这里设置了20 -->
            <DefaultRolloverStrategy max="20" />
        </RollingFile>

        <RollingFile name="RollingFileError" fileName="${ERROR_LOG_FILE_NAME}/error.log"
            filePattern="${ERROR_LOG_FILE_NAME}/$${date:yyyy-MM}/error-%d{yyyy-MM-dd-HH-mm}-%i.log">
            <ThresholdFilter level="error" onMatch="ACCEPT"
                onMismatch="DENY" />
            <PatternLayout
                pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
            <Policies>
                <!-- log4j2的按分钟 分日志文件 : warn-%d{yyyy-MM-dd-HH-mm}-%i.log -->
                <TimeBasedTriggeringPolicy interval="1"
                    modulate="true" />
                <!-- <SizeBasedTriggeringPolicy size="10 MB" /> -->
            </Policies>
        </RollingFile>

    </Appenders>

    <!--然后定义logger,只有定义了logger并引入的appender,appender才会生效 -->
    <Loggers>
        <!--过滤掉spring和mybatis的一些无用的DEBUG信息 -->
        <logger name="org.springframework" level="INFO"></logger>
        <logger name="org.mybatis" level="INFO"></logger>

        <!-- 第三方日志系统 -->
        <logger name="org.springframework" level="ERROR" />
        <logger name="org.hibernate" level="ERROR" />
        <logger name="org.apache.struts2" level="ERROR" />
        <logger name="com.opensymphony.xwork2" level="ERROR" />
        <logger name="org.jboss" level="ERROR" />


        <!-- 配置日志的根节点 -->
        <root level="all">
            <appender-ref ref="Console" />
            <appender-ref ref="RollingFileInfo" />
            <appender-ref ref="RollingFileWarn" />
            <appender-ref ref="RollingFileError" />
        </root>

    </Loggers>

</Configuration>
View Code

第三步编写基础代码

首先是自定义的业务BaseDao(数据查询操作):

技术分享图片
package com.zking.base.dao;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.orm.hibernate5.HibernateTemplate;

import com.zking.base.util.PageBean;

public abstract class BaseDao{
    @Autowired
    protected  HibernateTemplate hibernateTemplate;
    
    /**
     * 设置Query的查询参数
     * @param params
     * @param query
     * @return
     */
    @SuppressWarnings("rawtypes")
    protected void setParamters(Map<String,Object> params,Query query) {
        if(null==params||0==params.size())
            return;
        
        Set<Entry<String, Object>> set = params.entrySet();
        String name=null;
        Object value=null;
        for (Entry<String, Object> entry : set) {
            name=entry.getKey();
            value=entry.getValue();
            //判断参数是否是Collection,一般用于List/Set集合参数时使用
            if(value instanceof Collection)
                query.setParameterList(name, (Collection)value);
            //判断参数是否是Object[]
            else if(value instanceof Object[]) 
                query.setParameterList(name, (Object[])value);
            else 
                query.setParameter(name, value);
        }
    }
    
    /**
     * 将普通hql语句转换成查询总记录数的hql语句
     * @param hql
     * @return
     */
    public String countSql(String hql) {
        int start=hql.toUpperCase().indexOf("FROM");
        return "select count(1) "+hql.substring(start);
    }
    
    public String getCountSql(String sql) {
        return "select count(1) from ("+sql+") temp";
    }
    /**
     * 通用分页的原生sql查询
     * @param sql 查询语句
     * @param params 查询参数map
     * @param pageBean 分页对象
     * @return
     */
    public List<Map<String,Object>> executeQueryMap(String sql,
            Map<String,Object> params,PageBean pageBean){
        return hibernateTemplate.execute(new HibernateCallback<List<Map<String,Object>>>() {
            @SuppressWarnings({ "deprecation", "unchecked" })
            @Override
            public List<Map<String, Object>> doInHibernate(Session session) throws HibernateException {
                @SuppressWarnings("rawtypes")
                Query query=null;
                if(null!=pageBean&&pageBean.isPagintaion()) {
                    String countSql=getCountSql(sql);
                    query=session.createNativeQuery(countSql);
                    setParamters(params, query);
                    List<Object> list = query.list();
                    pageBean.setTotal(Integer.parseInt(list.get(0).toString()));
                }
                query=session.createNativeQuery(sql);
                if(null!=pageBean&&pageBean.isPagintaion()) {
                    query.setFirstResult(pageBean.getStartIndex());
                    query.setMaxResults(pageBean.getRows());
                }
                setParamters(params, query);
                query.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                return query.list();
            }
        });
    }
    
    /**
     * 查询(支持分页)
     * @param hql       普通hql语句
     * @param params    请求参数
     * @param pageBean  分页对象
     * @return
     */
    @SuppressWarnings("rawtypes")
    public List executeQuery(String hql,Map<String,Object> params,PageBean pageBean) {
        return hibernateTemplate.execute(new HibernateCallback<List>() {
            @Override
            public List doInHibernate(Session session) throws HibernateException {
                Query query=null;
                //1.根据满足条件查询总记录数
                if(null!=pageBean&&pageBean.isPagintaion()) {
                    String countHql=countSql(hql);
                    Query createQuery = session.createQuery(countHql);
                    setParamters(params, createQuery);
                    List list = createQuery.list();
                    pageBean.setTotal(Integer.parseInt(list.get(0).toString()));
                }
                query=session.createQuery(hql);
                //2.根据满足条件查询分页记录
                if(null!=pageBean&&pageBean.isPagintaion()) {
                    query.setFirstResult(pageBean.getStartIndex());
                    query.setMaxResults(pageBean.getRows());
                }
                setParamters(params, query);
                System.out.println(query.getQueryString());
                return query.list();
            }
        });
    }
    
}
View Code

BaseAction(操作servlet):

技术分享图片
package com.zking.base.action;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.fasterxml.jackson.databind.ObjectMapper;

public abstract class BaseAction implements ServletRequestAware, ServletResponseAware {

    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected HttpSession session;
    protected ServletContext application;
    //响应json
    private ObjectMapper mapper=new ObjectMapper();    

    @Override
    public void setServletResponse(HttpServletResponse response) {
        this.response=response;
        // 设置浏览器字符集编码. 
        this.response.setContentType("application/json;charset=UTF-8");
        // 设置response的缓冲区的编码.
        this.response.setCharacterEncoding("UTF-8");
    }

    @Override
    public void setServletRequest(HttpServletRequest request) {
        this.request=request;
        this.session=request.getSession();
        this.application=request.getServletContext();
    }
    
    /**
     *  响应更新数据消息
     * @param msg
     * @param success
     */
    public void toJSONMessage(String msg,boolean success){
        try {
            Map<String,Object> json=new HashMap<String,Object>();
            json.put("msg", msg);
            json.put("success", success);
            mapper.writeValue(response.getOutputStream(), json);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    
    /**
     * 分页查询数据
     * @param msg 消息
     * @param success 成功标记
     * @param total 总记录数
     * @param data 数据
     */
    public void toJSONPager(String msg,boolean success,
            int total,Object data){
        try {
            Map<String,Object> json=new HashMap<String,Object>();
            json.put("msg", msg);
            json.put("success", success);
            json.put("total", total);
            json.put("rows", data);
            mapper.writeValue(response.getOutputStream(),json);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    /**
     * 普通数据响应
     * @param success
     * @param data
     * @param msg
     */
    public void toJSONObject(boolean success,Object data,String msg){
        try {
            Map<String,Object> json=new HashMap<String,Object>();
            json.put("success", success);
            json.put("msg", msg);
            json.put("data", data);
            mapper.writeValue(response.getOutputStream(),json);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
View Code

 第四步编写业务代码

(1)User实体类:

技术分享图片
package com.zking.system.entity;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.*;

import org.hibernate.annotations.GenericGenerator;

@Entity //表明实体
@Table(name="t_user") //连接表名
public class User implements Serializable{
    /**
     * 序列化id
     */
    private static final long serialVersionUID = -2631210706189779079L;
    
    @Column(name="user_id") //对应表中的列
    @Id  //ID主键
    @GeneratedValue(generator = "myuuid") //主键生成策略
    @GenericGenerator(name="myuuid",strategy="uuid")//主键为uuid时的定义方式
    private String userId;
    
    @Column(name = "user_name")
    private String userName;
    
    @Column(name = "user_pwd")
    private String userPwd;
    
    @Column(name = "user_roleid")
    private String userRoleid;
    
    @Basic(fetch = FetchType.EAGER,optional = true)//立即加载,防止懒加载报错的方式
    @Column(name = "user_flag")
    private Integer userFlag;
    
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "user_create")
    private Date userCreate;//可用通过注解切换类型
    
    @Transient
    private Role role;//序列化时忽略此属性
    
    public Role getRole() {
        return role;
    }
    public void setRole(Role role) {
        this.role = role;
    }
    public Date getUserCreate() {
        return userCreate;
    }
    public void setUserCreate(Date userCreate) {
        this.userCreate = userCreate;
    }
    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getUserPwd() {
        return userPwd;
    }
    public void setUserPwd(String userPwd) {
        this.userPwd = userPwd;
    }
    public String getUserRoleid() {
        return userRoleid;
    }
    public void setUserRoleid(String userRoleid) {
        this.userRoleid = userRoleid;
    }
    public Integer getUserFlag() {
        return userFlag;
    }
    public void setUserFlag(Integer userFlag) {
        this.userFlag = userFlag;
    }
    public static long getSerialversionuid() {
        return serialVersionUID;
    }
    @Override
    public String toString() {
        return "User [userId=" + userId + ", userName=" + userName + ", userPwd=" + userPwd + ", userRoleid="
                + userRoleid + ", userFlag=" + userFlag + ", userCreate=" + userCreate + "]";
    }
    public User() {
        // TODO Auto-generated constructor stub
    }
}
User

(2)定义接口及实现:

技术分享图片
package com.zking.system.dao;

import java.util.List;
import java.util.Map;

import com.zking.base.util.PageBean;
import com.zking.system.entity.User;

public interface IUserDao {
    /**
     * 根据条件分页查询用户列表
     * 
     * @param User 用户信息
     * @return 用户信息集合信息
     */
    public List<Map<String, Object>> selectUserList(User User,PageBean pg);
    /**
     * 查询所有的角色为客户经理的用户
     * @return
     */
    List<Map<String, Object>> queryCustomerManagerUser();

    /**
     * 通过用户名查询用户
     * 
     * @param userName 用户名
     * @return 用户对象信息
     */
    public User selectUserByUserName(String userName);

    /**
     * 通过用户ID查询用户
     * 
     * @param userId 用户ID
     * @return 用户对象信息
     */
    public User selectUserById(String userId);

    /**
     * 新增用户信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    public int addUser(User user);
    /**
     * 更新用户状态
     * @param user
     */
    void updateUserState(User user);

    /**
     * 修改用户信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    public int updateUser(User user);

    /**
     * 修改用户头像
     * 
     * @param userName 用户名
     * @param avatar 头像地址
     * @return 结果
     */
    public int updateUserAvatar(String userName, String avatar);

    /**
     * 重置用户密码
     * 
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    public int resetUserPwd(User user);

    /**
     * 通过用户ID删除用户
     * 
     * @param userId 用户ID
     * @return 结果
     */
    public int deleteUserById(String userId);

    /**
     * 批量删除用户信息
     * 
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    public int deleteUserByIds(String[] userIds);

    /**
     * 校验用户名称是否唯一
     * 
     * @param userName 用户名称
     * @return 结果
     */
    public boolean checkUserNameUnique(String userName);

    /**
     * 校验手机号码是否唯一
     *
     * @param phonenumber 手机号码
     * @return 结果
     */
    public boolean checkPhoneUnique(String phonenumber);

    /**
     * 校验email是否唯一
     *
     * @param email 用户邮箱
     * @return 结果
     */
    public boolean checkEmailUnique(String email);
}
IuserDao
技术分享图片
package com.zking.system.dao.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.query.NativeQuery;
import org.hibernate.query.Query;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.zking.base.dao.BaseDao;
import com.zking.base.util.PageBean;
import com.zking.base.util.StringUtils;
import com.zking.system.dao.IUserDao;
import com.zking.system.entity.User;

@Repository("userDao") //声明spring注解,与Component等价
public class UserDaoImpl extends BaseDao implements IUserDao {

    @Override
    public int addUser(User user) {
        int n = 0;
        try {
            super.hibernateTemplate.save(user);
            n = 1;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return n;
    }

    @Override
    public List<Map<String,Object>> selectUserList(User user, PageBean pageBean){
        String sql="select u.user_id userId,u.user_name userName,u.user_pwd userPwd,u.user_roleid userRoleid,u.user_flag userFlag,u.user_create userCreate,r.role_name roleName from t_user u left join t_role r on u.user_roleid=r.role_id where 1=1";
        Map<String,Object> params=new HashMap<String,Object>();
        if(StringUtils.isNotBlank(user.getUserName())) {
            sql+=" and u.user_name like :username";
            params.put("username", "%"+user.getUserName()+"%");
        }
        if(user.getUserFlag()!=null&&user.getUserFlag()>-1) {
            sql += " and u.user_flag = :flag";
            params.put("flag", user.getUserFlag());
        }
        System.out.println(sql);
        return this.executeQueryMap(sql, params, pageBean);
    }

    @Override
    public User selectUserByUserName(String username) {
        System.out.println(super.hibernateTemplate);
        System.out.println(this.hibernateTemplate);
         return  this.hibernateTemplate.execute(new HibernateCallback<User>() {

            @SuppressWarnings("rawtypes")
            @Override
            public User doInHibernate(Session session) throws HibernateException {
                String hql = "from User where userName = :name";
                Query query = session.createQuery(hql);
                query.setParameter("name", username);
                return (User) query.list().get(0);
            }
        });
    }
    /**
     * 重置密码操作
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    public int resetUserPwd(User user) {
        // TODO Auto-generated method stub
        int n = 0;
        try {
            super.hibernateTemplate.execute(new HibernateCallback() {

                @Override
                public Object doInHibernate(Session session) throws HibernateException {
                    // TODO Auto-generated method stub
                    String sql = "update t_user set user_pwd = :pwd  where user_name = :uname";
                    NativeQuery query = session.createNativeQuery(sql);
                    query.setParameter("pwd", user.getUserPwd());
                    query.setParameter("uname", user.getUserName());
                    return query.executeUpdate();
                }
            });
            n = 1;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return n;
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    public void updateUserState(User user) {
        // TODO Auto-generated method stub
        Object execute = super.hibernateTemplate.execute(new HibernateCallback() {

            @Override
            public Object doInHibernate(Session session) throws HibernateException {
                // TODO Auto-generated method stub
                String sql = "update t_user set user_flag = :flag where user_id = :uid";
                NativeQuery query = session.createNativeQuery(sql);
                query.setParameter("flag", user.getUserFlag());
                query.setParameter("uid", user.getUserId());
                return query.executeUpdate();
            }
        });
        System.out.println("用户状态更新结果:"+execute);
    }

    @Override
    public List<Map<String, Object>> queryCustomerManagerUser() {
        // TODO Auto-generated method stub
        String sql = "select ur.user_id userId,ur.user_name userName from t_user ur left join t_role ro on ur.user_roleid = ro.role_id where ro.role_name = ‘客户经理‘ and ur.user_flag = 1";
        return super.executeQueryMap(sql, null, null);
    }

    @Override
    public User selectUserById(String userId) {
        // TODO Auto-generated method stub
        return super.hibernateTemplate.execute(new HibernateCallback<User>() {

            @Override
            public User doInHibernate(Session session) throws HibernateException {
                // TODO Auto-generated method stub
                String sql = "select *  from t_user  where user_id = :uid";
                NativeQuery<User> query = session.createNativeQuery(sql,User.class);
                query.setParameter("uid", userId);
                return query.list().get(0);
            }
        });
    }

    @Override
    public int updateUser(User user) {
        // TODO Auto-generated method stub
        int n = 0;
        try {
            User u = super.hibernateTemplate.get(User.class,user.getUserId());
            if(null!=u) {
                u.setUserName(user.getUserName());
                u.setUserRoleid(user.getUserRoleid());
                u.setUserFlag(user.getUserFlag());
                super.hibernateTemplate.update(u);
                n = 1;
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return n;
    }

    @Override
    public int updateUserAvatar(String userName, String avatar) {
        // TODO Auto-generated method stub
        return 0;
    }


    @Override
    public int deleteUserById(String userId) {
        int n = 0;
        User u = super.hibernateTemplate.get(User.class, userId);
        if(u!=null) {
            super.hibernateTemplate.delete(u);
            n = 1;
        }
        return n;
    }

    @Override
    public int deleteUserByIds(String[] userIds) {
        int n = 0;
        try {
            List<String> list = new ArrayList<>(Arrays.asList(userIds));
            list.forEach(obj ->{
                deleteUserById(obj);
            });
            n = 1;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return n;
    }

    @SuppressWarnings("rawtypes")
    @Override
    public boolean checkUserNameUnique(String userName) {
        // TODO Auto-generated method stub
        String  sql = "select user_name from t_user where user_name = :username";
        List list = super.hibernateTemplate.execute(new HibernateCallback<List>() {

            @Override
            public List doInHibernate(Session session) throws HibernateException {
                // TODO Auto-generated method stub
                NativeQuery query = session.createNativeQuery(sql);
                query.setParameter("username", userName);
                return query.list();
            }
        });
        return list!=null&&list.size()>0?true:false;//true可以插入,false不行
    }

    @Override
    public boolean checkPhoneUnique(String phonenumber) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean checkEmailUnique(String email) {
        // TODO Auto-generated method stub
        return false;
    }
}
UserDaoImpl

(3)定义逻辑层(Biz或Service):

技术分享图片
package com.zking.system.biz;

import java.util.List;
import java.util.Map;

import com.zking.base.util.PageBean;
import com.zking.system.entity.User;
public interface IUserBiz {
    /**
     * 根据条件分页查询用户列表
     * 
     * @param User 用户信息
     * @return 用户信息集合信息
     */
    public List<Map<String, Object>> selectUserList(User User,PageBean pg);
    /**
     * 查询所有的角色为客户经理的用户
     * @return
     */
    List<Map<String, Object>> queryCustomerManagerUser();

    /**
     * 通过用户名查询用户
     * 
     * @param userName 用户名
     * @return 用户对象信息
     */
    public User selectUserByUserName(String userName);

    /**
     * 通过用户ID查询用户
     * 
     * @param userId 用户ID
     * @return 用户对象信息
     */
    public User selectUserById(String userId);

    /**
     * 新增用户信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    public int addUser(User user);
    /**
     * 更新用户状态
     * @param user
     */
    void updateUserState(User user);

    /**
     * 修改用户信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    public int updateUser(User user);

    /**
     * 修改用户头像
     * 
     * @param userName 用户名
     * @param avatar 头像地址
     * @return 结果
     */
    public int updateUserAvatar(String userName, String avatar);

    /**
     * 重置用户密码
     * 
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    public int resetUserPwd(User user);

    /**
     * 通过用户ID删除用户
     * 
     * @param userId 用户ID
     * @return 结果
     */
    public int deleteUserById(String userId);

    /**
     * 批量删除用户信息
     * 
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    public int deleteUserByIds(String[] userIds);

    /**
     * 校验用户名称是否唯一
     * 
     * @param userName 用户名称
     * @return 结果
     */
    public boolean checkUserNameUnique(String userName);

    /**
     * 校验手机号码是否唯一
     *
     * @param phonenumber 手机号码
     * @return 结果
     */
    public boolean checkPhoneUnique(String phonenumber);

    /**
     * 校验email是否唯一
     *
     * @param email 用户邮箱
     * @return 结果
     */
    public boolean checkEmailUnique(String email);
}
IuserBiz
技术分享图片
package com.zking.system.biz.impl;

import java.util.List;

import java.util.Map;

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

import com.zking.base.util.PageBean;
import com.zking.system.biz.IUserBiz;
import com.zking.system.dao.IRoleDao;
import com.zking.system.dao.IUserDao;
import com.zking.system.entity.User;

@SuppressWarnings("all")
@Service("userBiz") //等价与Component注解,名字必须唯一
public class UserBizImpl implements IUserBiz {
    
    @Autowired 
    private IUserDao userDao;//自动装配依赖
    
    @Override
    public List<Map<String, Object>> selectUserList(User user, PageBean pg) {
        // TODO Auto-generated method stub
        return userDao.selectUserList(user, pg);
    }
    @Override
    public List<Map<String, Object>> queryCustomerManagerUser() {
        // TODO Auto-generated method stub
        return userDao.queryCustomerManagerUser();
    }
    @Override
    public User selectUserByUserName(String userName) {
        // TODO Auto-generated method stub
        return userDao.selectUserByUserName(userName);
    }
    @Override
    public User selectUserById(String userId) {
        // TODO Auto-generated method stub
        return userDao.selectUserById(userId);
    }
    @Override
    public int addUser(User user) {
        // TODO Auto-generated method stub
        int n = userDao.addUser(user);//新增用户
        return n;
    }
    @Override
    public void updateUserState(User user) {
        // TODO Auto-generated method stub
        userDao.updateUserState(user);
    }
    @Override
    public int updateUser(User user) {
        // TODO Auto-generated method stub
        return userDao.updateUser(user);
    }
    @Override
    public int updateUserAvatar(String userName, String avatar) {
        // TODO Auto-generated method stub
        return 0;
    }
    @Override
    public int resetUserPwd(User user) {
        // TODO Auto-generated method stub
        return userDao.resetUserPwd(user);
    }
    @Override
    public int deleteUserById(String userId) {
        // TODO Auto-generated method stub
        return userDao.deleteUserById(userId);
    }
    @Override
    public int deleteUserByIds(String[] userIds) {
        // TODO Auto-generated method stub
        return userDao.deleteUserByIds(userIds);
    }
    @Override
    public boolean checkUserNameUnique(String userName) {
        // TODO Auto-generated method stub
        return userDao.checkUserNameUnique(userName);
    }
    @Override
    public boolean checkPhoneUnique(String phonenumber) {
        // TODO Auto-generated method stub
        return false;
    }
    @Override
    public boolean checkEmailUnique(String email) {
        // TODO Auto-generated method stub
        return false;
    }


}
IuserBizImpl

(4)定义控制层(Controller),注意命名空间的限制百度有很多,这里不做过多解释:

技术分享图片
package com.zking.system.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ModelDriven;
import com.zking.base.action.BaseAction;
import com.zking.base.entity.StrEnum;
import com.zking.base.jwt.JwtUtils;
import com.zking.base.util.MD5;
import com.zking.base.util.PageBean;
import com.zking.system.biz.IUserBiz;
import com.zking.system.entity.User;

@Controller("userAction")
@Scope("prototype") //多例的
@Namespace("/")
public class UserAction extends BaseAction implements ModelDriven<User>{

    private static final Integer MODULE_ID = 1501;
    private User user = new User();
    @Autowired
    private IUserBiz userBiz;
    
    @Override
    public User getModel() {
        // TODO Auto-generated method stub
        return user;
    }
    /**
     * 用户登录的方法
     * @return
     */
    @Action(value="userAction_userLogin")
    public String userLogin() {
        User u = userBiz.selectUserByUserName(user.getUserName());
        try {
            String msg = "";
            boolean f = false;
            if(null==u) {
                msg = "用户名不存在,登录失败!";
            }else if(u.getUserPwd().equals(new MD5().getMD5ofStr(user.getUserPwd()))) {
                //生成令牌
                Map<String, Object> json = new HashMap<String, Object>();
                json.put("userName",user.getUserName());
                json.put("userId", user.getUserId());
                json.put("roleId", user.getUserRoleid());
                json.put("loginTime", System.currentTimeMillis());
                String jwt=JwtUtils.createJwt(json, JwtUtils.JWT_WEB_TTL);
                response.setHeader(JwtUtils.JWT_HEADER_KEY, jwt);
                msg = "用户登录成功";
                f = true;
            }else {
                msg = "用户密码错误,登录失败!";
            }
            super.toJSONObject(f, u,msg);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            super.toJSONMessage("系统错误,请重新登陆", false);
        }
        return null;
    }
    /**
     * 添加用户
     * @return
     */
    @Action(value="userAction_addUser")
    public String addUser() {
        //jwt令牌校验,并且获取当前登录对象
        User u = JwtUtils.getUser(response.getHeader(JwtUtils.JWT_HEADER_KEY));
        try {
            if(null==u) {
                super.toJSONMessage("添加用户失败", false);
                throw new RuntimeException("用户未登录!");
            }
            user.setUserId(UUID.randomUUID().toString().replace("-", ""));
            user.setUserPwd(new MD5().getMD5ofStr(user.getUserPwd()));
            userBiz.addUser(user);
            super.toJSONMessage("添加用户成功",true);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            super.toJSONMessage("添加用户失败", false);
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 删除用户
     * @return
     */
    @Action(value="userAction_delUser")
    public String delUser() {
        User u = JwtUtils.getUser(response.getHeader(JwtUtils.JWT_HEADER_KEY));
        boolean f=  false;
        String str = "删除用户失败";
        try {
            int n = userBiz.deleteUserById(user.getUserId());
            if(n>0) {
                f = true;
                str = "删除用户成功!";
            }
            super.toJSONMessage(str,f);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            super.toJSONMessage(str, f);
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 编辑用户
     * @return
     */
    @Action(value="userAction_editUser")
    public String editUser() {
        User u = JwtUtils.getUser(response.getHeader(JwtUtils.JWT_HEADER_KEY));
        boolean f=  false;
        String str = StrEnum.EDIT.getName()+"用户失败";
        try {
            int n = userBiz.deleteUserById(user.getUserId());
            if(n>0) {
                f = true;
                str.replaceAll("失败", "成功");
            }
            super.toJSONMessage(str,f);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            super.toJSONMessage(str, f);
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 分页查询用户
     * @return
     */
    @Action(value="userAction_queryUserPager")
    public String queryUserPager() {
        User u = JwtUtils.getUser(response.getHeader(JwtUtils.JWT_HEADER_KEY));
        try {
            PageBean pg = new PageBean();
            pg.setRequest(request);
            List<Map<String,Object>> list = userBiz.selectUserList(user, pg);
            super.toJSONPager("分页查询用户成功", true, pg.getTotal(), list);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            super.toJSONPager("分页查询用户失败", false, 0, null);
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 重置用户密码
     * @return
     */
    @Action(value="userAction_resetUserPwd")
    public String resetUserPwd() {
        User u = JwtUtils.getUser(response.getHeader(JwtUtils.JWT_HEADER_KEY));
        try {
            if(null==u) {
                super.toJSONMessage("重置密码失败", false);
                throw new RuntimeException("用户未登录!");
            }
            userBiz.resetUserPwd(user);
            super.toJSONMessage("重置用户密码成功",true);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            super.toJSONMessage("重置用户密码失败", false);
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 重置用户状态
     * @return
     */
    @Action(value="userAction_updateUserState")
    public String updateUserState() {
        User u = JwtUtils.getUser(response.getHeader(JwtUtils.JWT_HEADER_KEY));
        try {
            if("admin".equals(u.getUserName())) {
                userBiz.updateUserState(user);
                super.toJSONMessage("更新用户状态成功",true);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            super.toJSONMessage("更新用户状态失败", false);
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 查询所有的客户经理并且状态正常
     * @return
     */
    @Action(value="userAction_queryCustomerManagerUser")
    public String queryCustomerManagerUser() {
        User u = JwtUtils.getUser(response.getHeader(JwtUtils.JWT_HEADER_KEY));
        String str = StrEnum.SELECT.getName()+"所有的状态正常的客户经理数据";
        try {
            if(null==u) {
                super.toJSONMessage(str+"失败", false);
                throw new RuntimeException("用户未登录!");
            }
            List<Map<String, Object>> list = userBiz.queryCustomerManagerUser();
            super.toJSONObject(true, list, str+"成功!");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            super.toJSONObject(false, null, str+"失败!");
            e.printStackTrace();
        }
        return null;
    }
    
    
}
;
UserAction

第五步配置web.xml文件

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
  <display-name>Archetype Created Web Application</display-name>
  
    <!-- 1.Spring上下文ApplicationContext.xml的加载 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
    <!-- 2.启动Web容器时,自动装配ApplicationContext.xml的配置信息 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
    <!-- 3.spring自带中文乱码过滤器 -->
   <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <async-supported>true</async-supported>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
    <!-- 4.防止内存泄露、缓存清除监听器 -->
  <listener>
    <listener-class>
        org.springframework.web.util.IntrospectorCleanupListener
    </listener-class>
  </listener>
  
  <!-- 5.用于支持3种Bean的作用域:request,session和globalSession -->
  <listener>
    <listener-class>
    org.springframework.web.context.request.RequestContextListener
    </listener-class>
  </listener>
  
  <!--6. 解决跨域问题,前后分离时解决,普通项目可不用 -->
   <filter>
      <filter-name>corsFilter</filter-name>
      <filter-class>com.zking.base.util.CorsFilter</filter-class>
  </filter>
  <filter-mapping>
      <filter-name>corsFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping> 
  <!-- 7.配置jwt令牌过滤器,可选 -->
    <filter>
      <filter-name>jwtFilter</filter-name>
      <filter-class>com.zking.base.jwt.JwtFilter</filter-class>
  </filter>
  <filter-mapping>
      <filter-name>jwtFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <!-- 8.struts2核心过滤器 -->
  <filter>
      <filter-name>struts2</filter-name>
      <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>*.action</url-pattern>
  </filter-mapping>
  
</web-app>

第六步启动tomcat浏览器访问

服务器启动成功应该是这样的:

技术分享图片

 

 然后在浏览器输入你的项目地址(注意你的端口号,我的是80,这里截图时浏览器省略了端口):

技术分享图片

 

可以看到请求状态码200,成功访问。

控制台应该有hibernate的sql输出:

技术分享图片

 

 以上就是SSH集成(基于注解)相关的实例展示。

转载注明出处,谢谢。

SSH集成开发应用(基于注解的Demo实例详细)

原文:https://www.cnblogs.com/StarChen20/p/13870284.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!