SSH整合(二)

[亡魂溺海] 提交于 2019-11-28 17:39:15

SSH框架实现登录、新闻增删改查、树形菜单

项目结构

pom.xml 网不好不要一次引入太多,容易下不全

  1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3   <modelVersion>4.0.0</modelVersion>
  4   <groupId>com.lww</groupId>
  5   <artifactId>T224_SSH</artifactId>
  6   <packaging>war</packaging>
  7   <version>0.0.1-SNAPSHOT</version>
  8   <name>T224_SSH Maven Webapp</name>
  9   <url>http://maven.apache.org</url>
 10   <properties>
 11         <hibernate.version>5.2.12.Final</hibernate.version>
 12         <mysql.version>5.1.44</mysql.version>
 13         <spring.version>5.0.1.RELEASE</spring.version>
 14         <struts2.version>2.5.13</struts2.version>
 15         <slf4j.version>1.7.7</slf4j.version>
 16         <log4j2.version>2.9.1</log4j2.version>
 17         <disruptor.version>3.2.0</disruptor.version>
 18         <junit.version>4.12</junit.version>
 19         <javax.servlet.version>4.0.0</javax.servlet.version>
 20         <jstl.version>1.2</jstl.version>
 21         <standard.version>1.1.2</standard.version>
 22         <tomcat-jsp-api.version>8.0.47</tomcat-jsp-api.version>
 23     </properties>
 24   
 25   <dependencies>
 26    <!-- 1、导入hibernate依赖 -->
 27            <!-- 核心包 -->
 28         <dependency>
 29             <groupId>org.hibernate</groupId>
 30             <artifactId>hibernate-core</artifactId>
 31             <version>${hibernate.version}</version>
 32         </dependency>
 33         <!-- 桥接包 -->
 34         <dependency>
 35             <groupId>org.hibernate</groupId>
 36             <artifactId>hibernate-c3p0</artifactId>
 37             <version>${hibernate.version}</version>
 38         </dependency>
 39         <!-- 缓存的桥接包 -->
 40         <dependency>
 41             <groupId>org.hibernate</groupId>
 42             <artifactId>hibernate-ehcache</artifactId>
 43             <version>${hibernate.version}</version>
 44         </dependency>
 45         <!-- 数据库驱动包 -->
 46         <dependency>
 47             <groupId>mysql</groupId>
 48             <artifactId>mysql-connector-java</artifactId>
 49             <version>${mysql.version}</version>
 50         </dependency>
 51         
 52         <!-- 2、导入spring依赖 -->
 53         <!-- spring核心包 -->
 54         <dependency>
 55             <groupId>org.springframework</groupId>
 56             <artifactId>spring-context</artifactId>
 57             <version>${spring.version}</version>
 58         </dependency>
 59         <!-- 桥接包 -->
 60         <dependency>
 61             <groupId>org.springframework</groupId>
 62             <artifactId>spring-orm</artifactId>
 63             <version>${spring.version}</version>
 64         </dependency>
 65         <!-- 桥接包  -->
 66         <dependency>
 67             <groupId>org.springframework</groupId>
 68             <artifactId>spring-web</artifactId>
 69             <version>${spring.version}</version>
 70         </dependency>
 71         <!-- spring aop -->
 72         <dependency>
 73             <groupId>org.springframework</groupId>
 74             <artifactId>spring-aspects</artifactId>
 75             <version>${spring.version}</version>
 76         </dependency>
 77         
 78         <!-- 3、导入struts2依赖 -->
 79         <!-- 核心包 -->
 80         <dependency>
 81             <groupId>org.apache.struts</groupId>
 82             <artifactId>struts2-core</artifactId>
 83             <version>${struts2.version}</version>
 84         </dependency>
 85         <!-- struts2-spring整合包 -->
 86         <dependency>
 87             <groupId>org.apache.struts</groupId>
 88             <artifactId>struts2-spring-plugin</artifactId>
 89             <version>${struts2.version}</version>
 90         </dependency>
 91         
 92         <!-- 4、导入日志系统依赖 -->
 93         <!-- log配置:Log4j2 + Slf4j -->
 94         <!-- slf4j核心包 -->
 95         <dependency>
 96             <groupId>org.slf4j</groupId>
 97             <artifactId>slf4j-api</artifactId>
 98             <version>${slf4j.version}</version>
 99         </dependency>
100         <dependency>
101             <groupId>org.slf4j</groupId>
102             <artifactId>jcl-over-slf4j</artifactId>
103             <version>${slf4j.version}</version>
104             <scope>runtime</scope>
105         </dependency>
106 
107         <!--用于与slf4j保持桥接 -->
108         <dependency>
109             <groupId>org.apache.logging.log4j</groupId>
110             <artifactId>log4j-slf4j-impl</artifactId>
111             <version>${log4j2.version}</version>
112         </dependency>
113 
114         <!--核心log4j2jar包 -->
115         <dependency>
116             <groupId>org.apache.logging.log4j</groupId>
117             <artifactId>log4j-api</artifactId>
118             <version>${log4j2.version}</version>
119         </dependency>
120         <dependency>
121             <groupId>org.apache.logging.log4j</groupId>
122             <artifactId>log4j-core</artifactId>
123             <version>${log4j2.version}</version>
124         </dependency>
125 
126         <!--web工程需要包含log4j-web,非web工程不需要 -->
127         <dependency>
128             <groupId>org.apache.logging.log4j</groupId>
129             <artifactId>log4j-web</artifactId>
130             <version>${log4j2.version}</version>
131             <scope>runtime</scope>
132         </dependency>
133         <!--需要使用log4j2的AsyncLogger需要包含disruptor -->
134         <dependency>
135             <groupId>com.lmax</groupId>
136             <artifactId>disruptor</artifactId>
137             <version>${disruptor.version}</version>
138         </dependency>
139     
140     <!-- 5、other -->
141         <!-- 5.1、junit -->
142         <!-- 测试 -->
143         <dependency>
144             <groupId>junit</groupId>
145             <artifactId>junit</artifactId>
146             <version>${junit.version}</version>
147             <scope>test</scope>
148         </dependency>
149 
150         <!-- 5.2、servlet -->
151         <!-- Tomcat依赖 -->
152         <dependency>
153             <groupId>javax.servlet</groupId>
154             <artifactId>javax.servlet-api</artifactId>
155             <version>${javax.servlet.version}</version>
156             <scope>provided</scope>
157         </dependency>
158 
159         <!-- 5.3、jstl、standard -->
160         <!-- C标签库 -->
161         <dependency>
162             <groupId>jstl</groupId>
163             <artifactId>jstl</artifactId>
164             <version>${jstl.version}</version>
165         </dependency>
166         <dependency>
167             <groupId>taglibs</groupId>
168             <artifactId>standard</artifactId>
169             <version>${standard.version}</version>
170         </dependency>
171 
172         <!-- 5.4、tomcat-jsp-api -->
173         <dependency>
174             <groupId>org.apache.tomcat</groupId>
175             <artifactId>tomcat-jsp-api</artifactId>
176             <version>${tomcat-jsp-api.version}</version>
177         </dependency>
178     
179   </dependencies>
180   <build>
181     <finalName>T224_SSH</finalName>
182     <plugins>
183             <plugin>
184                 <groupId>org.apache.maven.plugins</groupId>
185                 <artifactId>maven-compiler-plugin</artifactId>
186                 <version>3.7.0</version>
187                 <configuration>
188                     <source>1.8</source>
189                     <target>1.8</target>
190                     <encoding>UTF-8</encoding>
191                 </configuration>
192             </plugin>
193         </plugins>
194   </build>
195 </project>

一、框架配置文件

web.xml

 1 <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 2          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3          xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
 4          version="3.1">
 5   <display-name>Archetype Created Web Application</display-name>
 6       <!-- 
 7           spring与web整合需要监听器    spring    ioc   spring-web.jar
 8           整合struts框架,配置strutsPreapareAndExecuteFilter
 9           要处理jsp传递到后台的中文乱码问题 配置过滤器  spring提供的过滤器
10           防止内存溢出配置
11        -->
12       <!-- 1、整合spring -->
13     <context-param>
14         <param-name>contextConfigLocation</param-name>
15         <param-value>classpath:spring-context.xml</param-value>
16     </context-param>
17     <listener>
18         <listener-class>
19             org.springframework.web.context.ContextLoaderListener
20         </listener-class>
21     </listener>
22     <!-- 2、整合struts2 -->
23     <filter>
24         <filter-name>struts2</filter-name>
25         <filter-class>
26             org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter
27         </filter-class>
28     </filter>
29     <filter-mapping>
30         <filter-name>struts2</filter-name>
31         <url-pattern>*.action</url-pattern>
32     </filter-mapping>
33 
34     <!-- 3、添加过滤器 -->
35     <filter>
36         <filter-name>encodingFilter</filter-name>
37         <filter-class>
38             org.springframework.web.filter.CharacterEncodingFilter
39         </filter-class>
40         <async-supported>true</async-supported>
41         <init-param>
42             <param-name>encoding</param-name>
43             <param-value>UTF-8</param-value>
44         </init-param>
45     </filter>
46     <filter-mapping>
47         <filter-name>encodingFilter</filter-name>
48         <url-pattern>/*</url-pattern>
49     </filter-mapping>
50       
51 </web-app>

 数据库db.properties

 1 db.username=root
 2 db.password=123
 3 db.driverClass=com.mysql.jdbc.Driver
 4 db.jdbcUrl=jdbc:mysql://localhost:3306/t224?useUnicode=true&characterEncoding=UTF-8&useSSL=true
 5 db.initialPoolSize=10
 6 db.maxPoolSize=20
 7 db.minPoolSize=5
 8 db.maxIdleTime=60
 9 db.acquireIncrement=5
10 db.maxStatements=0
11 db.idleConnectionTestPeriod=60
12 db.acquireRetryAttempts=30
13 db.breakAfterAcquireFailure=true
14 db.testConnectionOnCheckout=false

log4j2.xml

  1 <?xml version="1.0" encoding="UTF-8"?>
  2 
  3 <!-- status : 指定log4j本身的打印日志的级别.ALL< Trace < DEBUG < INFO < WARN < ERROR 
  4     < FATAL < OFF。 monitorInterval : 用于指定log4j自动重新配置的监测间隔时间,单位是s,最小是5s. -->
  5 <Configuration status="WARN" monitorInterval="30">
  6     <Properties>
  7         <!-- 配置日志文件输出目录 ${sys:user.home} -->
  8         <Property name="LOG_HOME">/root/workspace/lucenedemo/logs</Property>
  9         <property name="ERROR_LOG_FILE_NAME">/root/workspace/lucenedemo/logs/error</property>
 10         <property name="WARN_LOG_FILE_NAME">/root/workspace/lucenedemo/logs/warn</property>
 11         <property name="PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} [%t-%L] %-5level %logger{36} - %msg%n</property>
 12     </Properties>
 13 
 14     <Appenders>
 15         <!--这个输出控制台的配置 -->
 16         <Console name="Console" target="SYSTEM_OUT">
 17             <!-- 控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) -->
 18             <ThresholdFilter level="trace" onMatch="ACCEPT"
 19                 onMismatch="DENY" />
 20             <!-- 输出日志的格式 -->
 21             <!-- %d{yyyy-MM-dd HH:mm:ss, SSS} : 日志生产时间 %p : 日志输出格式 %c : logger的名称 
 22                 %m : 日志内容,即 logger.info("message") %n : 换行符 %C : Java类名 %L : 日志输出所在行数 %M 
 23                 : 日志输出所在方法名 hostName : 本地机器名 hostAddress : 本地ip地址 -->
 24             <PatternLayout pattern="${PATTERN}" />
 25         </Console>
 26 
 27         <!--文件会打印出所有信息,这个log每次运行程序会自动清空,由append属性决定,这个也挺有用的,适合临时测试用 -->
 28         <!--append为TRUE表示消息增加到指定文件中,false表示消息覆盖指定的文件内容,默认值是true -->
 29         <File name="log" fileName="logs/test.log" append="false">
 30             <PatternLayout
 31                 pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
 32         </File>
 33         <!-- 这个会打印出所有的info及以下级别的信息,每次大小超过size, 则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档 -->
 34         <RollingFile name="RollingFileInfo" fileName="${LOG_HOME}/info.log"
 35             filePattern="${LOG_HOME}/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log">
 36             <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) -->
 37             <ThresholdFilter level="info" onMatch="ACCEPT"
 38                 onMismatch="DENY" />
 39             <PatternLayout
 40                 pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
 41             <Policies>
 42                 <!-- 基于时间的滚动策略,interval属性用来指定多久滚动一次,默认是1 hour。 modulate=true用来调整时间:比如现在是早上3am,interval是4,那么第一次滚动是在4am,接着是8am,12am...而不是7am. -->
 43                 <!-- 关键点在于 filePattern后的日期格式,以及TimeBasedTriggeringPolicy的interval, 日期格式精确到哪一位,interval也精确到哪一个单位 -->
 44                 <!-- log4j2的按天分日志文件 : info-%d{yyyy-MM-dd}-%i.log -->
 45                 <TimeBasedTriggeringPolicy interval="1"
 46                     modulate="true" />
 47                 <!-- SizeBasedTriggeringPolicy:Policies子节点, 基于指定文件大小的滚动策略,size属性用来定义每个日志文件的大小. -->
 48                 <!-- <SizeBasedTriggeringPolicy size="2 kB" /> -->
 49             </Policies>
 50         </RollingFile>
 51 
 52         <RollingFile name="RollingFileWarn" fileName="${WARN_LOG_FILE_NAME}/warn.log"
 53             filePattern="${WARN_LOG_FILE_NAME}/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log">
 54             <ThresholdFilter level="warn" onMatch="ACCEPT"
 55                 onMismatch="DENY" />
 56             <PatternLayout
 57                 pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
 58             <Policies>
 59                 <TimeBasedTriggeringPolicy />
 60                 <SizeBasedTriggeringPolicy size="2 kB" />
 61             </Policies>
 62             <!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件,这里设置了20 -->
 63             <DefaultRolloverStrategy max="20" />
 64         </RollingFile>
 65 
 66         <RollingFile name="RollingFileError" fileName="${ERROR_LOG_FILE_NAME}/error.log"
 67             filePattern="${ERROR_LOG_FILE_NAME}/$${date:yyyy-MM}/error-%d{yyyy-MM-dd-HH-mm}-%i.log">
 68             <ThresholdFilter level="error" onMatch="ACCEPT"
 69                 onMismatch="DENY" />
 70             <PatternLayout
 71                 pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
 72             <Policies>
 73                 <!-- log4j2的按分钟 分日志文件 : warn-%d{yyyy-MM-dd-HH-mm}-%i.log -->
 74                 <TimeBasedTriggeringPolicy interval="1"
 75                     modulate="true" />
 76                 <!-- <SizeBasedTriggeringPolicy size="10 MB" /> -->
 77             </Policies>
 78         </RollingFile>
 79 
 80     </Appenders>
 81 
 82     <!--然后定义logger,只有定义了logger并引入的appender,appender才会生效 -->
 83     <Loggers>
 84         <!--过滤掉spring和mybatis的一些无用的DEBUG信息 -->
 85         <logger name="org.springframework" level="INFO"></logger>
 86         <logger name="org.mybatis" level="INFO"></logger>
 87 
 88         <!-- 第三方日志系统 -->
 89         <logger name="org.springframework" level="ERROR" />
 90         <logger name="org.hibernate" level="ERROR" />
 91         <logger name="org.apache.struts2" level="ERROR" />
 92         <logger name="com.opensymphony.xwork2" level="ERROR" />
 93         <logger name="org.jboss" level="ERROR" />
 94 
 95 
 96         <!-- 配置日志的根节点 -->
 97         <root level="all">
 98             <appender-ref ref="Console" />
 99             <appender-ref ref="RollingFileInfo" />
100             <appender-ref ref="RollingFileWarn" />
101             <appender-ref ref="RollingFileError" />
102         </root>
103 
104     </Loggers>
105 
106 </Configuration>

spring-vue.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:aop="http://www.springframework.org/schema/aop"
 5     xmlns:context="http://www.springframework.org/schema/context"
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 7         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd 
 8         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
 9     
10     <!-- user -->
11     <bean id="userDao" class="com.liuwenwu.user.dao.UserDao" parent="baseDao"></bean>
12     <bean id="userBiz" class="com.liuwenwu.user.biz.impl.UserBizImpl" parent="baseBiz">
13         <property name="userDao" ref="userDao"></property>
14     </bean>
15     <bean id="userAction" class="com.liuwenwu.user.web.UserAction"  parent="baseAction">
16         <property name="userBiz" ref="userBiz"></property>
17     </bean>
18     
19     
20     <!-- Articles -->
21     <bean id="articlesDao" class="com.liuwenwu.articles.dao.ArticlesDao" parent="baseDao"></bean>
22     <bean id="articlesBiz" class="com.liuwenwu.articles.biz.impl.ArticlesBizImpl" parent="baseBiz">
23         <property name="articlesDao" ref="articlesDao"></property>
24     </bean>
25     <bean id="articlesAction" class="com.liuwenwu.articles.web.ArticlesAction" parent="baseAction">
26         <property name="articlesBiz" ref="articlesBiz"></property>
27     </bean>
28     
29     
30     <!--TreeNode-->
31     <bean id="treeNodeDao" class="com.liuwenwu.tree_node.dao.TreeNodeDao" parent="baseDao"></bean>
32     <bean id="treeNodeBiz" class="com.liuwenwu.tree_node.biz.impl.TreeNodBizImpl" parent="baseBiz">
33         <property name="treeNodeDao" ref="treeNodeDao"></property>
34     </bean>
35     <bean id="treeNodeAction" class="com.liuwenwu.tree_node.web.TreeNodeAction" parent="baseAction">
36         <property name="treeNodeBiz" ref="treeNodeBiz"></property>
37     </bean>
38     
39 </beans>

spring-hibernate.xml

  1 <?xml version="1.0" encoding="UTF-8"?>
  2 <beans xmlns="http://www.springframework.org/schema/beans"
  3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
  4     xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
  5     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  6         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
  7         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
  8         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
  9     
 10     <!-- 1、注册jdbc相关的配置文件 -->
 11     <!-- 2、配置数据库连接池C3P0 -->
 12     <!-- 注册数据库连接文件db.properties -->
 13     <context:property-placeholder location="classpath:db.properties" />
 14 
 15     <!-- 配置c3p0连接池 -->
 16     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
 17         <property name="user" value="${db.username}"></property>
 18         <property name="password" value="${db.password}"></property>
 19         <property name="driverClass" value="${db.driverClass}"></property>
 20         <property name="jdbcUrl" value="${db.jdbcUrl}"></property>
 21 
 22         <!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
 23         <property name="initialPoolSize" value="${db.initialPoolSize}"></property>
 24         <!--连接池中保留的最大连接数。Default: 15 -->
 25         <property name="maxPoolSize" value="${db.maxPoolSize}"></property>
 26         <!--连接池中保留的最小连接数。 -->
 27         <property name="minPoolSize" value="${db.minPoolSize}" />
 28         <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
 29         <property name="maxIdleTime" value="${db.maxIdleTime}" />
 30 
 31         <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
 32         <property name="acquireIncrement" value="${db.acquireIncrement}" />
 33 
 34         <!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements 属于单个connection而不是整个连接池。 
 35             所以设置这个参数需要考虑到多方面的因素。如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 
 36 -->
 37         <property name="maxStatements" value="${db.maxStatements}" />
 38 
 39         <!--每60秒检查所有连接池中的空闲连接。Default: 0 -->
 40         <property name="idleConnectionTestPeriod" value="${db.idleConnectionTestPeriod}" />
 41 
 42         <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->
 43         <property name="acquireRetryAttempts" value="${db.acquireRetryAttempts}" />
 44 
 45         <!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效 保留,并在下次调用getConnection()的时候继续尝试获取连接。 
 46             如果设为true,那么在尝试 获取连接失败后该数据源将申明已断开并永久关闭。Default: false -->
 47         <property name="breakAfterAcquireFailure" value="${db.breakAfterAcquireFailure}" />
 48 
 49         <!--因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的 时候都将校验其有效性。建议使用idleConnectionTestPeriod 
 50             或automaticTestTable 等方法来提升连接测试的性能。Default: false -->
 51         <property name="testConnectionOnCheckout" value="${db.breakAfterAcquireFailure}" />
 52     </bean>
 53 
 54     <!-- 3、配置sessionfactory相关信息 -->
 55     <bean id="sessionFactory"
 56         class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
 57         <!-- 数据源 -->
 58         <property name="dataSource">
 59             <ref bean="dataSource" />
 60         </property>
 61         <!-- hibernate相关属性 -->
 62         <property name="hibernateProperties">
 63             <props>
 64                 <prop key="dialect">org.hibernate.dialect.MySQLDialect</prop>
 65                 <!--spring与Hibernate集成无法显示sql语句问题,请见集成后hibernate无法显示sql语句.txt -->
 66                 <prop key="hibernate.show_sql">true</prop>
 67                 <prop key="hibernate.format_sql">true</prop>
 68             </props>
 69         </property>
 70         <!-- 实体映射文件 -->
 71         <property name="mappingResources">
 72             <list>
 73                 <value>com/liuwenwu/articles/entity/articles.hbm.xml</value>
 74                 <value>com/liuwenwu/tree_node/entity/treeNode.hbm.xml</value>
 75                 <value>com/liuwenwu/user/entity/user.hbm.xml</value>
 76             </list>
 77         </property>
 78     </bean>
 79 
 80     <!-- 4、配置事务 -->
 81     <!--声明式事务配置开始 -->
 82     <!-- 
 83         静态代理:
 84             一个代理对象->一个目标对象
 85             BookProxy(BookBizImpl+myMethodBeforeAdvice)->bookBiz
 86             OrderProxy(OrderBizImpl+myMethodBeforeAdvice2)->    OrderBiz
 87         
 88         动态代理:
 89             一个代理对象->多个目标对象
 90      -->
 91     
 92     <!--1) 开启自动代理 -->
 93     <aop:aspectj-autoproxy />
 94 
 95     <!--2) 事务管理器 -->
 96     <bean id="transactionManager"
 97         class="org.springframework.orm.hibernate5.HibernateTransactionManager">
 98         <property name="sessionFactory" ref="sessionFactory" />
 99     </bean>
100 
101     <!--3) 定义事务特性 -->
102     <!-- 下面定义了增删改查的事物规则,意味着只有符合下面命名规则的方法,才会获取到session,以及提交事物 -->
103     <tx:advice id="txAdvice" transaction-manager="transactionManager">
104         <tx:attributes>
105             <tx:method name="add*" propagation="REQUIRED" />
106             <tx:method name="save*" propagation="REQUIRED" />
107             <tx:method name="insert*" propagation="REQUIRED" />
108 
109             <tx:method name="edit*" propagation="REQUIRED" />
110             <tx:method name="update*" propagation="REQUIRED" />
111 
112             <tx:method name="del*" propagation="REQUIRED" />
113             <tx:method name="remove*" propagation="REQUIRED" />
114 
115             <tx:method name="load*" propagation="REQUIRED" read-only="true" />
116             <tx:method name="list*" propagation="REQUIRED" read-only="true" />
117             <tx:method name="select*" propagation="REQUIRED" read-only="true" />
118             <tx:method name="query*" propagation="REQUIRED" read-only="true" />
119             <tx:method name="login*" propagation="REQUIRED" read-only="true" />
120     
121             <tx:method name="do*" propagation="REQUIRED" />
122         </tx:attributes>
123     </tx:advice>
124 
125     <!--4) 定义切入点 -->
126     <aop:config>
127         <!-- pointcut属性用来定义一个切入点,分成四个部分理解 [* ][*..][*Biz][.*(..)] -->
128         <!-- A: 返回类型,*表示返回类型不限 -->
129         <!-- B: 包名,*..表示包名不限 -->
130         <!-- C: 类或接口名,*Biz表示类或接口必须以Biz结尾 -->
131         <!-- D: 方法名和参数,*(..)表示方法名不限,参数类型和个数不限 -->
132         <aop:advisor advice-ref="txAdvice" pointcut="execution(* *..*Biz.*(..))" />
133         <!-- 为什么一定要切在biz对应的借口上 -->
134     </aop:config>
135     <!-- 声明式事务配置结束 -->
136 
137     <!-- 5、配置HibernateTemplate  session-->
138     <bean class="org.springframework.orm.hibernate5.HibernateTemplate" id="hibernateTemplate">
139         <property name="sessionFactory" ref="sessionFactory"></property>
140     </bean>
141     <!-- 6、分模块开发(只配置base模块) -->
142     <bean class="com.liuwenwu.base.entity.BaseEntity" abstract="true" id="baseEntity"></bean>
143     <bean class="com.liuwenwu.base.dao.BaseDao" abstract="true" id="baseDao" >
144         <property name="hibernateTemplate" ref="hibernateTemplate"></property>
145     </bean>
146     <bean class="com.liuwenwu.base.biz.BaseBiz" abstract="true" id="baseBiz"></bean>
147     <bean class="com.liuwenwu.base.web.BaseAction" abstract="true" id="baseAction"></bean>
148     
149 </beans>

spring-context.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:aop="http://www.springframework.org/schema/aop"
 5     xmlns:context="http://www.springframework.org/schema/context"
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 7         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd 
 8         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
 9     
10     <import resource="spring-hibernate.xml"/>
11     <import resource="spring-vue.xml"/>
12 </beans>

struts-base.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>
    <constant name="struts.i18n.encoding" value="UTF-8" />
    <constant name="struts.devMode" value="true" />
    <constant name="struts.configuration.xml.reload" value="true" />
    <constant name="struts.i18n.reload" value="true" />
    <constant name="struts.enable.DynamicMethodInvocation" value="true" />

    <package name="base" extends="struts-default" abstract="true">
        <global-allowed-methods>regex:.*</global-allowed-methods>
    </package>
</struts>

struts-sy.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE struts PUBLIC
 3     "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
 4     "http://struts.apache.org/dtds/struts-2.5.dtd">
 5 <struts>
 6     <package name="sy" extends="base" namespace="/sy">
 7     <!-- 这里的class不再是全路径名了,而是spring所管理的Bean的id -->
 8         <action name="/user_*" class="userAction" method="{1}"></action>
 9         
10         <action name="/articles_*" class="articlesAction" method="{1}"></action>
11         
12         <action name="/treeNode_*" class="treeNodeAction" method="{1}"></action>
13         
14     </package>
15 </struts>

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>
    <include file="struts-default.xml"></include>
    <include file="struts-base.xml"></include>
    <include file="struts-sy.xml"></include>
</struts>

 

二、基础base模块

BaseDao

 1 package com.liuwenwu.base.dao;
 2 
 3 import java.io.Serializable;
 4 import java.util.Collection;
 5 import java.util.List;
 6 import java.util.Map;
 7 
 8 import org.hibernate.Session;
 9 import org.hibernate.query.Query;
10 import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
11 
12 import com.liuwenwu.base.util.PageBean;
13 
14 public class BaseDao extends HibernateDaoSupport implements Serializable{
15 
16     private static final long serialVersionUID = 5427369434249665701L;
17     
18     public void setParam(Query query,Map<String, Object> map) {
19         if(map == null || map.size() < 1) {
20             return;
21         }
22         Object value = null;
23         for(Map.Entry<String, Object> entry:map.entrySet()) {
24             value = entry.getValue();
25             if(value instanceof Collection) {
26                 query.setParameterList(entry.getKey(), (Collection) value);
27             }else if(value instanceof Object[]) {
28                 query.setParameterList(entry.getKey(), (Object[]) value);
29             }else {
30                 query.setParameter(entry.getKey(), value);
31             }
32         }
33     }
34     
35     public String getCountHql(String hql) {
36         int index = hql.toUpperCase().indexOf("FROM");
37         return "select count(*) "+hql.substring(index);
38     }
39     
40     /**
41      * 
42      * @param hql    已经拼装好的
43      * @param map
44      * @param pageBean
45      * @return
46      */
47     public List executeQuery(Session session, String hql,Map<String, Object> map,PageBean pageBean) {
48         if(pageBean !=null && pageBean.isPagination()) {
49             String countHql = getCountHql(hql);
50             Query countQuery = session.createQuery(countHql);
51             this.setParam(countQuery, map);
52             pageBean.setTotal(countQuery.getSingleResult().toString());
53             
54             Query query = session.createQuery(hql);
55             this.setParam(query, map);
56             query.setFirstResult(pageBean.getStartIndex());
57             query.setMaxResults(pageBean.getRows());
58             List list = query.list();
59             
60             return list;
61         }else {
62             Query query = session.createQuery(hql);
63             this.setParam(query, map);
64             List list = query.list();
65             
66             return list;
67         }    
68     }
69 }

BaseAction

 

 1 package com.liuwenwu.base.web;
 2 
 3 import java.io.Serializable;
 4 
 5 import javax.servlet.ServletContext;
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletResponse;
 8 import javax.servlet.http.HttpSession;
 9 
10 import org.apache.struts2.interceptor.ServletRequestAware;
11 import org.apache.struts2.interceptor.ServletResponseAware;
12 
13 public class BaseAction implements ServletRequestAware, ServletResponseAware,Serializable{
14     private static final long serialVersionUID = -7110462505161900879L;
15     /**
16      * 为了传值使用
17      */
18     protected HttpServletResponse response;
19     protected HttpServletRequest request;
20     protected HttpSession session;
21     protected ServletContext application;
22     
23     /**
24      * 为了配置跳转页面所用
25      */
26     protected final static String SUCCESS = "success";
27     protected final static String FAIL = "fail";
28     protected final static String LIST = "list";
29     protected final static String ADD = "add";
30     protected final static String EDIT = "edit";
31     protected final static String DETAIL = "detail";
32     
33     /**
34      * 具体传值字段    后端向jsp页面传值所用字段
35      */
36     protected Object result;
37     protected Object msg;
38     protected int code;
39 
40     public Object getResult() {
41         return result;
42     }
43 
44     public Object getMsg() {
45         return msg;
46     }
47 
48     public int getCode() {
49         return code;
50     }
51 
52     @Override
53     public void setServletResponse(HttpServletResponse arg0) {
54         this.response = arg0;
55         
56     }
57 
58     @Override
59     public void setServletRequest(HttpServletRequest arg0) {
60         this.request = arg0;
61         this.session = arg0.getSession();
62         this.application = arg0.getServletContext();
63     }
64 }

 

PageBean

 

  1 package com.zking.util;
  2 
  3 import java.util.Map;
  4 
  5 import javax.servlet.http.HttpServletRequest;
  6 
  7 /**
  8  * 分页工具类
  9  *
 10  */
 11 public class PageBean {
 12 
 13     private int page = 1;// 页码
 14 
 15     private int rows = 10;// 页大小
 16 
 17     private int total = 0;// 总记录数
 18 
 19     private boolean pagination = true;// 是否分页
 20     // 获取前台向后台提交的所有参数
 21     private Map<String, String[]> parameterMap;
 22     // 获取上一次访问后台的url
 23     private String url;
 24 
 25     /**
 26      * 初始化pagebean
 27      * 
 28      * @param req
 29      */
 30     public void setRequest(HttpServletRequest req) {
 31         this.setPage(req.getParameter("page"));
 32         this.setRows(req.getParameter("rows"));
 33         // 只有jsp页面上填写pagination=false才是不分页
 34         this.setPagination(!"fasle".equals(req.getParameter("pagination")));
 35         this.setParameterMap(req.getParameterMap());
 36         this.setUrl(req.getRequestURL().toString());
 37     }
 38 
 39     public int getMaxPage() {
 40         return this.total % this.rows == 0 ? this.total / this.rows : this.total / this.rows + 1;
 41     }
 42 
 43     public int nextPage() {
 44         return this.page < this.getMaxPage() ? this.page + 1 : this.getMaxPage();
 45     }
 46 
 47     public int previousPage() {
 48         return this.page > 1 ? this.page - 1 : 1;
 49     }
 50 
 51     public PageBean() {
 52         super();
 53     }
 54 
 55     public int getPage() {
 56         return page;
 57     }
 58 
 59     public void setPage(int page) {
 60         this.page = page;
 61     }
 62 
 63     public void setPage(String page) {
 64         this.page = StringUtils.isBlank(page) ? this.page : Integer.valueOf(page);
 65     }
 66 
 67     public int getRows() {
 68         return rows;
 69     }
 70 
 71     public void setRows(int rows) {
 72         this.rows = rows;
 73     }
 74 
 75     public void setRows(String rows) {
 76         this.rows = StringUtils.isBlank(rows) ? this.rows : Integer.valueOf(rows);
 77     }
 78 
 79     public int getTotal() {
 80         return total;
 81     }
 82 
 83     public void setTotal(int total) {
 84         this.total = total;
 85     }
 86 
 87     public void setTotal(String total) {
 88         this.total = Integer.parseInt(total);
 89     }
 90 
 91     public boolean isPagination() {
 92         return pagination;
 93     }
 94 
 95     public void setPagination(boolean pagination) {
 96         this.pagination = pagination;
 97     }
 98 
 99     public Map<String, String[]> getParameterMap() {
100         return parameterMap;
101     }
102 
103     public void setParameterMap(Map<String, String[]> parameterMap) {
104         this.parameterMap = parameterMap;
105     }
106 
107     public String getUrl() {
108         return url;
109     }
110 
111     public void setUrl(String url) {
112         this.url = url;
113     }
114 
115     /**
116      * 获得起始记录的下标
117      * 
118      * @return
119      */
120     public int getStartIndex() {
121         return (this.page - 1) * this.rows;
122     }
123 
124     @Override
125     public String toString() {
126         return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination
127                 + ", parameterMap=" + parameterMap + ", url=" + url + "]";
128     }
129 }

 

三、articles模块

ArticlesBiz

 

 1 package com.liuwenwu.articles.biz;
 2 
 3 import java.util.List;
 4 
 5 import com.liuwenwu.articles.entity.Articles;
 6 import com.liuwenwu.base.util.PageBean;
 7 
 8 public interface ArticlesBiz {
 9 
10     /**
11      * 新增
12      * @param articles
13      * @return
14      */
15     public int add(Articles articles);
16     
17     /**
18      * 修改
19      * @param articles
20      */
21     public void update(Articles articles);
22     
23     /**
24      * 删除
25      * @param articles
26      */
27     public void del(Articles articles);
28     
29     /**
30      * 查询
31      * @param articles
32      * @param pageBean
33      * @return
34      */
35     public List<Articles> list(Articles articles,PageBean pageBean);
36     
37 }

 

ArticlesBizImpl

 

 1 package com.liuwenwu.articles.biz.impl;
 2 
 3 import java.util.List;
 4 
 5 import com.liuwenwu.articles.biz.ArticlesBiz;
 6 import com.liuwenwu.articles.dao.ArticlesDao;
 7 import com.liuwenwu.articles.entity.Articles;
 8 import com.liuwenwu.base.util.PageBean;
 9 
10 public class ArticlesBizImpl implements ArticlesBiz {
11 
12     private ArticlesDao articlesDao;
13 
14     public ArticlesDao getArticlesDao() {
15         return articlesDao;
16     }
17 
18     public void setArticlesDao(ArticlesDao articlesDao) {
19         this.articlesDao = articlesDao;
20     }
21 
22     @Override
23     public int add(Articles articles) {
24         return articlesDao.add(articles);
25     }
26 
27     @Override
28     public void update(Articles articles) {
29         articlesDao.update(articles);
30 
31     }
32 
33     @Override
34     public void del(Articles articles) {
35         articlesDao.del(articles);
36 
37     }
38 
39     @Override
40     public List<Articles> list(Articles articles, PageBean pageBean) {
41         // TODO Auto-generated method stub
42         return articlesDao.list(articles, pageBean);
43     }
44 }

 

ArticlesDao

 

 1 package com.liuwenwu.articles.dao;
 2 
 3 import java.util.List;
 4 
 5 import com.liuwenwu.articles.entity.Articles;
 6 import com.liuwenwu.base.dao.BaseDao;
 7 import com.liuwenwu.base.util.PageBean;
 8 import org.hibernate.Session;
 9 
10 public class ArticlesDao extends BaseDao{
11 
12     private static final long serialVersionUID = -6077790395680289782L;
13 
14     /**
15      * 新增
16      * @param articles
17      * @return
18      */
19     public int add(Articles articles) {
20         return (int) this.getHibernateTemplate().save(articles);
21         
22     }
23     
24     /**
25      * 
26      * 删除
27      * @param articles
28      */
29     public void del(Articles articles) {
30         this.getHibernateTemplate().delete(articles);
31     }
32     
33     /**
34      * 修改
35      * @param articles
36      */
37     public void update(Articles articles) {
38         this.getHibernateTemplate().update(articles);
39     }
40     
41     /**
42      * 查询
43      * @param articles
44      * @param pageBean
45      * @return
46      */
47     public List<Articles> list(Articles articles, PageBean pageBean){
48         Session session = this.getHibernateTemplate().getSessionFactory().openSession();
49         session.beginTransaction();
50         return super.executeQuery(session, "from Articles", null,pageBean);
51      }    
52 }

 

实体类Articles

 

 1 package com.liuwenwu.articles.entity;
 2 
 3 public class Articles {
 4     private Integer id;
 5     private String title;
 6     private String body;
 7     
 8     public Integer getId() {
 9         return id;
10     }
11     public void setId(Integer id) {
12         this.id = id;
13     }
14     public String getTitle() {
15         return title;
16     }
17     public void setTitle(String title) {
18         this.title = title;
19     }
20     public String getBody() {
21         return body;
22     }
23     public void setBody(String body) {
24         this.body = body;
25     }
26     @Override
27     public String toString() {
28         return "Articles [id=" + id + ", title=" + title + ", body=" + body + "]";
29     }    
30 }

 

实体类映射 articles.hbm.xml

 

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE hibernate-mapping PUBLIC 
 3     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 4     "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
 5 <hibernate-mapping>
 6     <class table="t_vue_articles" name="com.liuwenwu.articles.entity.Articles">
 7         <id name="id" type="java.lang.Integer" column="id">
 8             <generator class="increment"></generator>
 9         </id>
10         
11         <property name="title" type="java.lang.String" column="title"></property>
12         <property name="body" type="java.lang.String" column="body"></property>
13     </class>
14 </hibernate-mapping>

 

ArticlesAction

 

 1 package com.liuwenwu.articles.web;
 2 
 3 import com.liuwenwu.articles.biz.ArticlesBiz;
 4 import com.liuwenwu.articles.entity.Articles;
 5 import com.liuwenwu.base.web.BaseAction;
 6 import com.opensymphony.xwork2.ModelDriven;
 7 
 8 public class ArticlesAction extends BaseAction implements ModelDriven<Articles>{
 9     
10     private static final long serialVersionUID = 5943402081349505372L;
11     
12     private ArticlesBiz articlesBiz;
13     private Articles articles =new Articles();
14     
15     public ArticlesBiz getArticlesBiz() {
16         return articlesBiz;
17     }
18 
19     public void setArticlesBiz(ArticlesBiz articlesBiz) {
20         this.articlesBiz = articlesBiz;
21     }
22     
23     /**
24      * 查询
25      * @return
26      */
27     public String list() {
28         System.out.println(articlesBiz.list(articles, null));
29         return null;
30     }
31 
32     /**
33      * 删除
34      */
35     public void del() {
36         articlesBiz.del(articles);
37     }
38 
39     /**
40      * 修改
41      * @return
42      */
43     public String update() {
44         articlesBiz.update(articles);
45         return null;        
46     }
47     
48     /**
49      * 新增
50      * @return
51      */
52     public String add() {
53         articlesBiz.add(articles);
54         return null;
55         
56     }
57     
58 
59     @Override
60     public Articles getModel() {
61         // TODO Auto-generated method stub
62         return articles;
63     }
64 }

 

四、tree_node模块

TreeNodeBiz

 1 package com.liuwenwu.tree_node.biz;
 2 
 3 import java.util.List;
 4 
 5 import com.liuwenwu.tree_node.entity.TreeNode;
 6 
 7 public interface TreeNodeBiz {
 8 
 9     /**
10      * 加载树
11      * @return
12      */
13     public List<TreeNode> list();
14 }

TreeNodBizImpl

 1 package com.liuwenwu.tree_node.biz.impl;
 2 
 3 import java.util.List;
 4 
 5 import com.liuwenwu.tree_node.biz.TreeNodeBiz;
 6 import com.liuwenwu.tree_node.dao.TreeNodeDao;
 7 import com.liuwenwu.tree_node.entity.TreeNode;
 8 
 9 public class TreeNodBizImpl implements TreeNodeBiz{
10     
11     private TreeNodeDao treeNodeDao;
12     
13 
14     public TreeNodeDao getTreeNodeDao() {
15         return treeNodeDao;
16     }
17 
18 
19     public void setTreeNodeDao(TreeNodeDao treeNodeDao) {
20         this.treeNodeDao = treeNodeDao;
21     }
22 
23 
24     @Override
25     public List<TreeNode> list() {
26         // TODO Auto-generated method stub
27         return treeNodeDao.list();
28     }
29 
30 }

TreeNodeDao

 1 package com.liuwenwu.tree_node.dao;
 2 
 3 import java.util.List;
 4 
 5 import org.hibernate.Hibernate;
 6 import org.hibernate.Session;
 7 
 8 import com.liuwenwu.base.dao.BaseDao;
 9 import com.liuwenwu.tree_node.entity.TreeNode;
10 
11 public class TreeNodeDao extends BaseDao{
12 
13     private static final long serialVersionUID = -4339387396332761044L;
14 
15     public List<TreeNode> list(){
16         Session session = this.getHibernateTemplate().getSessionFactory().openSession();
17         session.beginTransaction();
18         //这是最好的做做法 非常好 使用 hql语句进行查询
19         List<TreeNode> treeNodes =  super.executeQuery(session, "from TreeNode where treeNodeType = 1", null,null);
20         //进行强子加载子节点
21         if (treeNodes != null && treeNodes.size() > 0) {
22             for (TreeNode t : treeNodes) {
23                 //强制加载子节点
24                 Hibernate.initialize(t.getChildren());
25             }
26         }
27         return treeNodes;
28     }
29 }

实体类 TreeNode

 1 package com.liuwenwu.tree_node.entity;
 2 
 3 import java.util.HashSet;
 4 import java.util.Set;
 5 
 6 public class TreeNode {
 7 
 8         private Integer nodeId;
 9         private String nodeName;
10         private Integer treeNodeType;
11         private Integer position;
12         private String url;
13         //关联父节点
14         private TreeNode parent;
15         //关联子节点"们"
16         private Set<TreeNode> children = new HashSet<TreeNode>();
17         //加载方式(1强制加载关联,0懒加载)
18         private Integer initChildren = 0;
19      
20         public Integer getNodeId() {
21             return nodeId;
22         }
23 
24         public void setNodeId(Integer nodeId) {
25             this.nodeId = nodeId;
26         }
27 
28         public String getNodeName() {
29             return nodeName;
30         }
31 
32         public void setNodeName(String nodeName) {
33             this.nodeName = nodeName;
34         }
35 
36         public Integer getTreeNodeType() {
37             return treeNodeType;
38         }
39 
40         public void setTreeNodeType(Integer treeNodeType) {
41             this.treeNodeType = treeNodeType;
42         }
43 
44         public Integer getPosition() {
45             return position;
46         }
47 
48         public void setPosition(Integer position) {
49             this.position = position;
50         }
51 
52         public String getUrl() {
53             return url;
54         }
55 
56         public void setUrl(String url) {
57             this.url = url;
58         }
59 
60         public TreeNode getParent() {
61             return parent;
62         }
63 
64         public void setParent(TreeNode parent) {
65             this.parent = parent;
66         }
67 
68         public Set<TreeNode> getChildren() {
69             return children;
70         }
71 
72         public void setChildren(Set<TreeNode> children) {
73             this.children = children;
74         }
75 
76         public Integer getInitChildren() {
77             return initChildren;
78         }
79 
80         public void setInitChildren(Integer initChildren) {
81             this.initChildren = initChildren;
82         }
83      
84         
85 }

实体映射 treeNode.hbm.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE hibernate-mapping PUBLIC 
 3     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 4     "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
 5 <hibernate-mapping>
 6     <class table="t_vue_tree_node" name="com.liuwenwu.tree_node.entity.TreeNode">
 7          <id name="nodeId" type="java.lang.Integer" column="tree_node_id">
 8             <generator class="increment" />
 9         </id>
10         <property name="nodeName" type="java.lang.String"
11                   column="tree_node_name">
12         </property>
13         <property name="treeNodeType" type="java.lang.Integer"
14                   column="tree_node_type">
15         </property>
16         <property name="position" type="java.lang.Integer"
17                   column="position">
18         </property>
19         <property name="url" type="java.lang.String"
20                   column="url">
21         </property>
22         <!--
23             parent定义了管理树形
24             column中指定了通过那个列段来关联 对应的是当前表的主键
25          -->
26         <many-to-one name="parent" class="com.liuwenwu.tree_node.entity.TreeNode" column="parent_node_id"/>
27 
28         <!--
29             这是定义子节点关联
30          -->
31         <set name="children" cascade="save-update" inverse="true">
32             <!--凡是parent_node_id是当前节点的tree_node_id的就统统加入集合-->
33             <key column="parent_node_id"></key>
34             <one-to-many class="com.liuwenwu.tree_node.entity.TreeNode"/>
35         </set>
36 
37     </class>
38 </hibernate-mapping>

TreeNodeAction

 1 package com.liuwenwu.tree_node.web;
 2 
 3 import java.util.List;
 4 
 5 import com.liuwenwu.base.web.BaseAction;
 6 import com.liuwenwu.tree_node.biz.TreeNodeBiz;
 7 import com.liuwenwu.tree_node.entity.TreeNode;
 8 
 9 
10 public class TreeNodeAction extends BaseAction{
11 
12     private static final long serialVersionUID = -6038611615430719428L;
13     
14     private TreeNodeBiz treeNodeBiz;
15     
16     
17     public TreeNodeBiz getTreeNodeBiz() {
18         return treeNodeBiz;
19     }
20 
21 
22     public void setTreeNodeBiz(TreeNodeBiz treeNodeBiz) {
23         this.treeNodeBiz = treeNodeBiz;
24     }
25 
26     public String list() {
27          List<TreeNode> list = treeNodeBiz.list();
28          System.out.println("我是长度" + list.size());
29          TreeNode node = list.get(0);
30          System.out.println(node);
31          System.out.println(node.getChildren());
32          for (TreeNode n: node.getChildren()) {
33              System.out.println("我是子节点:" + n.getNodeName());
34          }
35         return null;    
36     }    
37 }

五、user模块

UserBiz

 1 package com.liuwenwu.user.biz;
 2 
 3 import com.liuwenwu.user.entity.User;
 4 
 5 public interface UserBiz {
 6 
 7     /**
 8      * 登录
 9      * @param user
10      * @return
11      */
12     public User login(User user);
13     
14     /**
15      * 注册
16      * @param user
17      * @return
18      */
19     public int addUser(User user);
20 }

UserBizImpl

 1 package com.liuwenwu.user.biz.impl;
 2 
 3 import com.liuwenwu.user.biz.UserBiz;
 4 import com.liuwenwu.user.dao.UserDao;
 5 import com.liuwenwu.user.entity.User;
 6 
 7 public class UserBizImpl implements UserBiz{
 8     
 9     private UserDao userDao;
10     
11 
12     public UserDao getUserDao() {
13         return userDao;
14     }
15 
16     public void setUserDao(UserDao userDao) {
17         this.userDao = userDao;
18     }
19 
20     @Override
21     public User login(User user) {
22         return userDao.login(user);
23     }
24 
25     @Override
26     public int addUser(User user) {
27         return userDao.addUser(user);
28     }
29 }

UserDao

 1 package com.liuwenwu.user.dao;
 2 
 3 import org.hibernate.HibernateException;
 4 import org.hibernate.Session;
 5 import org.springframework.orm.hibernate5.HibernateCallback;
 6 
 7 import com.liuwenwu.base.dao.BaseDao;
 8 import com.liuwenwu.user.entity.User;
 9 
10 public class UserDao extends BaseDao{
11 
12     private static final long serialVersionUID = 3670806315799801488L;
13 
14     public User login(User user) {
15         return this.getHibernateTemplate().execute(new HibernateCallback<User>() {
16 
17             @Override
18             public User doInHibernate(Session session) throws HibernateException {
19                 return (User) session.createQuery("from User where uname= '"+user.getUname()+"' and pwd= "+user.getPwd()).list();
20             }
21         });
22     }
23     
24     public int addUser(User user) {
25         return (int) this.getHibernateTemplate().save(user);
26     }   
27 }
 1 package com.liuwenwu.user.entity;
 2 
 3 public class User {
 4 
 5     private String uname;
 6     private String pwd;
 7     public String getUname() {
 8         return uname;
 9     }
10     public void setUname(String uname) {
11         this.uname = uname;
12     }
13     public String getPwd() {
14         return pwd;
15     }
16     public void setPwd(String pwd) {
17         this.pwd = pwd;
18     }
19     @Override
20     public String toString() {
21         return "User [uname=" + uname + ", pwd=" + pwd + "]";
22     }
23     
24 }

实体映射 user.hbm.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE hibernate-mapping PUBLIC 
 3     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 4     "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
 5 <hibernate-mapping>
 6     <class table="t_vue_user" name="com.liuwenwu.user.entity.User">
 7         
 8         <id name="uname" type="java.lang.String" column="uname">
 9             <generator class="assigned"></generator>
10         </id>
11         <property name="pwd" type="java.lang.String" column="pwd"></property>
12     </class>
13 </hibernate-mapping>

UserAction

 

 1 package com.liuwenwu.user.web;
 2 
 3 import com.liuwenwu.base.web.BaseAction;
 4 import com.liuwenwu.user.biz.UserBiz;
 5 import com.liuwenwu.user.entity.User;
 6 import com.opensymphony.xwork2.ModelDriven;
 7 
 8 public class UserAction extends BaseAction implements ModelDriven<User>{
 9     
10     private static final long serialVersionUID = 4244808665377509950L;
11     
12     private UserBiz userBiz;
13     private User user=new User();
14     
15     
16     public UserBiz getUserBiz() {
17         return userBiz;
18     }
19 
20 
21     public void setUserBiz(UserBiz userBiz) {
22         this.userBiz = userBiz;
23     }
24 
25     /**
26      * 登录
27      * @return
28      */
29     public String login() {
30         userBiz.login(user);
31         return null;
32     }
33     
34     /**
35      * 注册
36      * @return
37      */
38     public String addUser() {
39         userBiz.addUser(user);
40         return null;    
41     }
42 
43     @Override
44     public User getModel() {
45         // TODO Auto-generated method stub
46         return user;
47     }
48 }

 

新闻查看

 

 

 

 

树形菜单

 

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!