一、SSH框架简介
SSH是struts+spring+hibernate集成的web应用程序开源框架。
Struts:用来控制的,核心控制器是Controller。
Spring:对Struts和Hibernate进行管理,整合的。
Hiernate:操控数据库
struts标签库:Struts2默认的表达式语言是OGNL(Object-Graph Navigation Language),通过它可以存取对象的任意属性、调用对象的方法、遍历整个对象的结构图、实现字段类型转换等功能。
JSP: HTML文件中插入Java程序段和JSP标记。
web.xml: Struts2核心过滤器和监听器
struts.xml: 管理应用中的Action映射,及Action处理结果和物理资源之间的映射。
applicationContext.xml: 整合了struts和Hibernate。
*.hbm.xml:O/R Mapping(Object Relational Mapping)映射文件,实体和表的映射关系通过XML来描述的文件。在项目启动的时候加载到内存中。
PO:Persistent Object,持久化对象
整体的调用关系:JSP–Action–Service–DAO–PO–数据库
在表示层中,首先通过JSP页面实现交互,负责接收请求(request)和传送请求(response),Struts根据配置文件(struts.xml)将ActionServlet(Struts的内置核心控制器组件)接收到的Request请求委派给Action处理。
在业务层中,管理服务器组建的Spring IOC容器负责向Action提供业务模型(Model)组件和该组件的协作对象数据处理(DAO)组建完成业务逻辑,并提供事务处理、缓冲池等容器组件以提升和保持数据的完整性。
在持久层,依赖于Hibernate的对象化映射和数据库交互,处理DAO组建请求的数据,并返回处理结果。
SSH框架优点:
1.spring管理对象的实例化,把对象的创建和获取放到外部,更加的灵活方便。
2.Hibernate避免了JDBC连接数据库的冗余繁杂。
3.各层分工明细,实现了各层之间的解耦,代码更加灵活。
二、环境搭建
1.IDEA新建maven-webapp项目
2.Maven配置Struts,Spring,Hibernate依赖组件
<properties>
<project.build.sourceEncoding>UTF-</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-</project.reporting.outputEncoding>
<junit.version>4.12</junit.version>
<!--JSONObject-->
<json-lib.version>2.4</json-lib.version>
<commons-lang.version>2.5</commons-lang.version>
<commons-collections.version>3.2.</commons-collections.version>
<commons-beanutils.version>1.8.</commons-beanutils.version>
<commons-logging.version>1.2</commons-logging.version>
<ezmorph.version>1.0.</ezmorph.version>
</properties> <dependencies>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!--JSONObject-->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>${json-lib.version}</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>${commons-beanutils.version}</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>${commons-logging.version}</version>
</dependency>
<dependency>
<groupId>net.sf.ezmorph</groupId>
<artifactId>ezmorph</artifactId>
<version>${ezmorph.version}</version>
</dependency> <!--Struts 依赖组件-->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.5.14.1</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-convention-plugin</artifactId>
<version>2.5.14.1</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-spring-plugin</artifactId>
<version>2.5.14.1</version>
</dependency> <dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>5.2</version>
</dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm-commons</artifactId>
<version>5.2</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>.1_3</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>ognl</groupId>
<artifactId>ognl</artifactId>
<version>3.1.</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.6</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.9.</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.9.</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts-annotations</artifactId>
<version>1.0.</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.-incubating</version>
</dependency>
<!--Spring dependencies-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1..RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.1..RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.1..RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1..RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1..RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.1..RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1..RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>4.1..RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.1..RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1..RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.1..RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1..RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.</version>
</dependency>
<!--Hibernate Dependencies-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3..Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>4.3..Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3..Final</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.</version>
</dependency>
<dependency>
<groupId>antlr</groupId>
<artifactId>antlr</artifactId>
<version>2.7.</version>
</dependency>
<dependency>
<groupId>com.fasterxml</groupId>
<artifactId>classmate</artifactId>
<version>1.3.</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.</version>
</dependency>
<dependency>
<groupId>org.hibernate.common</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>4.0..Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0..Final</version>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.18.-GA</version>
</dependency>
<dependency>
<groupId>org.jboss</groupId>
<artifactId>jandex</artifactId>
<version>1.1..Final</version>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.8.</version>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.1..GA</version>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging-annotations</artifactId>
<version>1.2..Beta1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.spec.javax.transaction</groupId>
<artifactId>jboss-transaction-api_1.2_spec</artifactId>
<version>1.0..Final</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.</version>
</dependency>
<dependency>
<groupId>org.jboss.spec.javax.transaction</groupId>
<artifactId>jboss-transaction-api_1.2_spec</artifactId>
<version>1.0..Final</version>
</dependency>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<!--MySQL Driver-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.-dmr</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
</dependencies>
pom.xml
3.配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
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>ssh</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- spring -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:struts/applicationContext.xml</param-value>
</context-param>
<!-- spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- struts拦截器 -->
<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>/*</url-pattern>
</filter-mapping>
<!-- 解决post乱码 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--为解决lazy=true在jsp页面上遍历数据,此时相关类(one2many)再查找,没有session的情况 -->
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>
org.springframework.orm.hibernate4.support.OpenSessionInViewFilter
</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
web.xml
4.配置struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<!-- 上面的头,注意版本,从样例里复制过来 showcase.war\WEB-INF\src\java\struts.xml --> <struts>
<!-- 告知Struts2运行时使用Spring来创建对象 -->
<constant name="struts.objectFactory" value="spring"/> <!--<constant name="struts.convention.package.locators" value="controller"/>-->
<!-- 自动扫描action包 -->
<!-- 注解需要的jar包:struts2-convention-plugin -->
<!--<constant name="struts.convention.default.parent.package" value="default"/>-->
<!--<constant name="struts.convention.package.locators.basePackage" value="com.zsm.ssh.action" />-->
<!--<constant name="struts.convention.package.locators" value="action"/>-->
<!--<constant name="struts.conventresultJsonsult.path" value="/WEB-INF/jsp/"/>-->
<!--<constant name="struts.convention.classes.reload" value="true"/>-->
<constant name="struts.i18n.encoding" value="utf-8" />
<!--<constant name="struts.enable.DynamicMethodInvocation" value="true"/>--> <!-- 第1步:先定义一个包 namespace="/login"用于区别不同Action,需要添加到url中 采用注解不需配置-->
<!--<package name="default" extends="struts-default">
<!– 第2步:定义一个action,配置跳转信息 name 类似于Servlet @WebServlet("/IndexServlet")
http://xxxx/xxx/Index.action http://xxxx/xxx/Index class 对应于自己写的Action类 当不写method属性时,默认调用的是execute
class="com.zsm.ssh.action.UserAction" ** new com.zsm.ssh.action.UserAction()
设计思想:关心了具体的实现类必须改为不要关注那个实现类 加入spring后,struts的action节点的class属性意义发生变化,
直接引用spring帮忙创建的实例 –>
<action name="login" class="com.zsm.ssh.action.UserAction">
<!– 跳转是forward/WEB-INF/是防止jsp不经过action就可以访问–>
<!– result接收返回的字符串,然后做对应的事情 –>
<!– 跳转是forward/WEB-INF/是防止jsp不经过action就可以访问–>
<!– result接收返回的字符串,然后做对应的事情 –>
resultJsonsult name="index" type="json">/index.jresultJsonsult>
resultJsonsult name="success" type="json">/success.jresultJsonsult>
resultJsonsult name="error">/error.jresultJsonsult>
</action>
</package>--> <!-- 所有匹配*.action的请求都由struts2处理 -->
<constant name="struts.action.extension" value="action"/>
<!-- 是否启用开发模式 -->
<constant name="struts.devMode" value="true"/>
<!-- struts配置文件改动后,是否重新加载 -->
<constant name="struts.configuration.xml.reload" value="true"/>
<!-- 设置浏览器是否缓存静态内容 -->
<constant name="struts.serve.static.browserCache" value="false"/>
<!-- 请求参数的编码方式 -->
<constant name="struts.i18n.encoding" value="utf-8"/>
<!-- 每次HTTP请求系统都重新加载资源文件,有助于开发 -->
<constant name="struts.i18n.reload" value="true"/>
<!-- 文件上传最大值 -->
<constant name="struts.multipart.maxSize" value=""/>
<!-- 让struts2支持动态方法调用 -->
<constant name="struts.enable.DynamicMethodInvocation" value="true"/>
<!-- Action名称中是否还是用斜线 -->
<constant name="struts.enable.SlashesInActionNames" value="false"/>
<!-- 允许标签中使用表达式语法 -->
<constant name="struts.tag.altSyntax" value="true"/>
<!-- 对于WebLogic,Orion,OC4J此属性应该设置成true -->
<constant name="struts.dispatcher.parametersWorkaround" value="false"/>
<package name="basePackage" extends="struts-default"/>
</struts>
struts.xml
5.配置applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns: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/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd"
default-autowire="byName"> <!--default-lazy-init="true" 配置懒加载-->
<!--自动扫描(实体类)注解包:实体类位置为:com.spring.mvc.entities.User,不能写成:com.spring.mvc.entities,而要写成:com.spring.mvc,packagesToScan要比实际上前一层-->
<!--采用注解的方式注入action,service,dao -->
<context:component-scan base-package="com.zsm.ssh.action"/>
<context:component-scan base-package="com.zsm.ssh.service"/>
<context:component-scan base-package="com.zsm.ssh.dao"/>
<!-- 开启SpringMVC注解模式 -->
<!--<mvc:annotation-driven/>-->
<!-- location值为参数配置文件的位置 -->
<context:property-placeholder location="classpath:properties/db-config.properties"/>
<!-- 属性配置文件 -->
<!--<bean id="propertyConfigeurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:properties/db-config.properties</value>
</property>
</bean>--> <!-- 数据库配置 -->
<!-- 数据库连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxPoolSize" value="${maxPoolSize}"/>
<property name="minPoolSize" value="${minPoolSize}"/>
<property name="autoCommitOnClose" value="${autoCommitOnClose}"/>
<property name="checkoutTimeout" value="${checkoutTimeout}"/>
<property name="acquireRetryAttempts" value="${acquireIncrement}"/>
</bean> <!-- sessionFactory配置 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="configLocation">
<!--mapper实例映射关系文件配置在cfg文件里-->
<value>classpath:struts/hibernate.cfg.xml</value>
</property>
</bean> <!--spring对hibernate的事务管理 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<aop:config proxy-target-class="true">
<aop:pointcut expression="execution(* com.zsm.ssh.service..*(..))" id="serviceMethod"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod"/>
</aop:config> <tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--默认:
isolation:DEFAULT
propagation:REQUIRED
timeout:- 事物超时时间由底层事物系统决定
read-only:false
rollback-for:所有允许异常回滚
no-rollback-for:所有检查异常不回滚 -->
<tx:method name="get*" read-only="true"/>
<tx:method name="do*"/>
</tx:attributes>
</tx:advice>
</beans>
applicationContext.xml
6.配置hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 数据库连接配置 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3066/personal_test?characterEncoding=utf-8</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<!-- 每个数据库都有1个,针对特定的关系型数据库生成优化的SQL -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- 设置默认的数据库连接池 -->
<property name="connection.pool_size"></property>
<!-- 显示SQL -->
<property name="show_sql">true</property>
<!-- 格式化SQL -->
<property name="format_sql">true</property>
<!-- 根据schema更新数据表的工具 -->
<property name="hbm2ddl.auto">update</property>
<!-- 开启二级缓存 -->
<property name="cache.use_second_level_cache">true</property>
<!-- 开启查询二级缓存 -->
<property name="cache.use_query_cache">true</property>
<!-- Hibernate4.0以上设置factory 缓存工具 -->
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory
</property>
<!-- 二级缓存 ehcache的配置文件位置 -->
<property name="hibernate.cache.provider_configuration_file_resource_path">struts/ehcache.xm</property>
<!-- 数据表映射配置文件 -->
<mapping resource="hibernate-mapper/User.hbm.xml"/>
<!-- 需要缓存的类 read-only 无需修改,那么就可以对其进行只读 缓存;read-write需要更新数据,那么使用读/写缓存 比较合适,
前提:数据库不可以为serializable transaction isolation level(序列化事务隔离级别);nonstrice-read-write 只偶尔需要更新数据-->
<!-- 需要缓存的类 -->
<class-cache usage="read-only" class="com.zsm.ssh.model.User"/>
</session-factory>
</hibernate-configuration>
hibernate.cfg.xml
7.配置 .hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.zsm.ssh.model">
<class name="com.zsm.ssh.model.User" table="student">
<id name="id" type="java.lang.Integer">
<column name="id"/>
<generator class="native"/>
</id>
<property name="user_no" type="java.lang.String">
<column name="user_no">
<comment>学号</comment>
</column>
</property>
<property name="user_name" type="java.lang.String">
<column name="user_name">
<comment>名字</comment>
</column>
</property>
<property name="password" type="java.lang.String">
<column name="password">
<comment>密码</comment>
</column>
</property>
<property name="user_sex" type="java.lang.String">
<column name="user_sex">
<comment>性别</comment>
</column>
</property>
<property name="user_birthday" type="java.util.Date">
<column name="user_birthday">
<comment>生日</comment>
</column>
</property>
<property name="user_class" type="java.lang.String">
<column name="user_class">
<comment>班级</comment>
</column>
</property>
<property name="createtime" type="java.util.Date">
<column name="createtime">
<comment>创建时间</comment>
</column>
</property>
<property name="updatetime" type="java.util.Date">
<column name="updatetime">
<comment>更新时间</comment>
</column>
</property> <!--<!– 编号 –>-->
<!--<id name="id" column="id" type="int">-->
<!--<generator class="native"></generator>-->
<!--</id>-->
<!--<property name="user_no" column="user_no" type="java.lang.String" not-null="true"></property>-->
<!--<!– 姓名 –>-->
<!--<property name="user_name" column="user_name" type="java.lang.String"></property>-->
<!--<!– 密码 –>-->
<!--<property name="password" column="password" type="java.lang.String"></property>-->
<!--<!– 性别 –>-->
<!--<property name="user_sex" column="user_sex" type="java.lang.String"></property>-->
<!--<!– 生日 –>-->
<!--<property name="user_birthday" column="user_birthday" type="java.util.Date"></property>-->
<!--<!– 班级 –>-->
<!--<property name="user_class" column="user_class" type="java.lang.String"></property>-->
<!--<!– 创建时间 –>-->
<!--<property name="createtime" column="createtime" type="java.util.Date"></property>-->
<!--<!– 更新时间 –>-->
<!--<property name="updatetime" column="updatetime" type="java.util.Date"></property>-->
</class>
</hibernate-mapping>
.hbm.xml
8.数据库连接
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/webapp?characterEncoding=utf-8&serverTimezone=GMT%2B8&useUnicode=true&useSSL=false
jdbc.username=root
jdbc.password=
#最大连接数
maxPoolSize=
#最小连接数
minPoolSize=
#关闭连接后不自动commit
autoCommitOnClose=false
#获取连接超时时间
checkoutTimeout=
#当获取连接失败重试次数
acquireIncrement=
db-config.properties
三、框架分析
1.建立Action
package com.zsm.ssh.action; import com.opensymphony.xwork2.ActionSupport;
import com.zsm.ssh.model.User;
import com.zsm.ssh.service.UserService;
import net.sf.json.JSONObject;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter; /**
* @Author: zengsm.
* @Description:
* @Date:Created in 2017/12/6 15:45.
* @Modified By:
*/
//默认可以不写
@ParentPackage("struts-default")
//根命名空间,可以不写
@Namespace("/")
//全局配置,如果方法上不指定result,则使用该Result
//@Results({@Result(name="success",location="/success.jsp"),
// @Result(name="error",location="/error.jsp")})
public class UserAction extends ActionSupport
{
//前台传到后台需要set,后台传到前台需要get
// 用户名-必须与页面请求的对应表单username值相同
private String username; // 密码必须与页面请求的对应表单password值相同
private String password; private String resultJson; /*
* struts 接收参数三种方式:属性方式接收,JavaBean方式接收,ModelDriven方式接收参数,前两种都必须设置get和set方法
* */
//Spring 注入方式
@Autowired
private UserService userService; //@Action(value="login")
@Action(value = "login", results = {
@Result(name = "success", location = "/success.jsp", params = {"resultJson", "resultJson"}),
@Result(name = "error", location = "/error.jsp")})
public String execute() throws Exception
{
HttpServletResponse response = ServletActionContext.getResponse();
HttpServletRequest request = ServletActionContext.getRequest(); JSONObject result = new JSONObject();
User user = userService.getByName(username);
result.put("user", user); if (user != null && user.getUser_name().equals(username) && user.getPassword().equals(password))
{
result.put("message", "登录成功");
result.put("status", "true");
resultJson = result.toString();
request.setAttribute("resultJson", resultJson);
writeResponseData(request, response, result);
return "success";
}
result.put("message", "登录失败");
result.put("status", "false");
resultJson = result.toString();
writeResponseData(request, response, result);
return "error";
} private void writeResponseData(HttpServletRequest request, HttpServletResponse response, Object data)
{
response.setContentType("text/html;charset=utf-8");
try
{
PrintWriter out = response.getWriter();
out.println(data.toString());
}
catch (Exception e)
{
e.printStackTrace();
}
} public String getUsername()
{
return username;
} public void setUsername(String username)
{
this.username = username;
} public void setPassword(String password)
{
this.password = password;
} public String getResultJson()
{
return resultJson;
} public void setResultJson(String resultJson)
{
this.resultJson = resultJson;
}
}
2.建立Service接口和实现类
package com.zsm.ssh.service; import com.zsm.ssh.model.User; import java.util.List; /**
* @Author: zengsm.
* @Description:
* @Date:Created in 2017/12/6 15:30.
* @Modified By:
*/
public interface UserService
{
List<User> findAllUser(); int saveEntity(User user); boolean saveOrUpdateEntity(User user); boolean updateEntity(User user); User getByName(String name); User getByNo(String no); boolean deleteUserById(Integer id); boolean deleteUserByNo(String no); boolean deleteUserByEntity(User user);
}
package com.zsm.ssh.service.impl; import com.zsm.ssh.dao.UserDao;
import com.zsm.ssh.model.User;
import com.zsm.ssh.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import java.util.List; /**
* @Author: zengsm.
* @Description:
* @Date:Created in 2017/12/6 15:31.
* @Modified By:
*/
@Service("userService")
@Transactional
public class UserServiceImpl implements UserService
{
@Autowired
private UserDao userDao; @Override
public List<User> findAllUser()
{
List<User> allUser = userDao.findAllUser();
return allUser;
} @Override
public int saveEntity(User user)
{
int id = userDao.saveEntity(user);
return id;
} @Override
public boolean saveOrUpdateEntity(User user)
{
try
{
userDao.saveOrUpdateEntity(user);
return true;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
} @Override
public boolean updateEntity(User user)
{
try
{
userDao.updateEntity(user);
return true;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
} @Override
public User getByName(String name)
{
try
{
User user = userDao.getByName(name);
return user;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
} @Override
public User getByNo(String no)
{
try
{
User user = userDao.getByNo(no);
return user;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
} @Override
public boolean deleteUserById(Integer id)
{
try
{
userDao.deleteUserById(id);
return true;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
} @Override
public boolean deleteUserByNo(String no)
{
try
{
userDao.deleteUserByNo(no);
return true;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
} @Override
public boolean deleteUserByEntity(User user)
{
try
{
userDao.deleteUserByEntity(user);
return true;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}
}
3.建立Dao接口和实现类
package com.zsm.ssh.dao; import com.zsm.ssh.model.User; import java.util.List; /**
* @Author: zengsm.
* @Description:
* @Date:Created in 2017/12/6 15:32.
* @Modified By:
*/
public interface UserDao
{
List<User> findAllUser(); int saveEntity(User user); void saveOrUpdateEntity(User user); void updateEntity(User user); User getByName(String name); User getByNo(String no); void deleteUserById(Integer id); void deleteUserByNo(String no); void deleteUserByEntity(User user);
}
package com.zsm.ssh.dao.impl; import com.zsm.ssh.dao.UserDao;
import com.zsm.ssh.model.User;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional; import java.util.List; /**
* @Author: zengsm.
* @Description:
* @Date:Created in 2017/12/6 15:36.
* @Modified By:
*/
@Repository("userDao")
public class UserDaoImpl extends HibernateDaoSupport implements UserDao
{
//这里的属性名一定要和配置中的属性名一致
@Autowired
private SessionFactory sessionFactory; @Override
@Transactional(propagation = Propagation.REQUIRED)
public List<User> findAllUser()
{
Session session = sessionFactory.openSession();
//将所有的数据查询出来并放到List集合里 User是表对应的实例名称
List<User> list = session.createQuery("from User").list();
session.close();
return list;
} @Override
@Transactional(propagation = Propagation.REQUIRED)
public int saveEntity(User user)
{
Session session = sessionFactory.getCurrentSession();
//返回插入数据id
Object id = session.save(user);
return Integer.valueOf(id.toString());
} @Override
@Transactional(propagation = Propagation.REQUIRED)
public void saveOrUpdateEntity(User user)
{
Session session = sessionFactory.getCurrentSession();
session.saveOrUpdate(user);
} @Override
@Transactional(propagation = Propagation.REQUIRED)
public void updateEntity(User user)
{
Session session = sessionFactory.getCurrentSession();
session.update(user);
} @Override
@Transactional(propagation = Propagation.REQUIRED)
public User getByName(String name)
{
Session session = sessionFactory.getCurrentSession();
//根据id查询,结果返回 User.class
User user = (User)session.get(User.class, );
//将所有的数据查询出来并放到List集合里 User是表对应的实例名称
List users = session.createQuery("from User where user_name='" + name + "'").list();
return (User)users.get();
} @Override
@Transactional(propagation = Propagation.REQUIRED)
public User getByNo(String no)
{
Session session = sessionFactory.getCurrentSession();
List users = session.createQuery("from User where user_no='" + no + "'").list();
return (User)users.get();
} @Override
@Transactional(propagation = Propagation.REQUIRED)
public void deleteUserById(Integer id)
{
Session session = sessionFactory.getCurrentSession();
String sql = "delete from User where id=:id";
Query query = session.createQuery(sql);
query.setParameter("id", id);
query.executeUpdate();
} @Override
@Transactional(propagation = Propagation.REQUIRED)
public void deleteUserByNo(String no)
{
Session session = sessionFactory.getCurrentSession();
String sql = "delete from User where user_no=:no";
Query query = session.createQuery(sql);
query.setParameter("no", no);
query.executeUpdate();
} @Override
@Transactional(propagation = Propagation.REQUIRED)
public void deleteUserByEntity(User user)
{
Session session = sessionFactory.getCurrentSession();
//传入实例对象,比较id删除对应行,,没有id匹配就不删除
session.delete(User.class.getName(), user);
}
}
四、源码分享
欢迎Star个人GitHub:https://github.com/lovelifeming/Resource/tree/master/SSH
备注:
作者:Shengming Zeng
博客:http://www.cnblogs.com/zengming/
本文是原创,欢迎大家转载;但转载时必须注明文章来源,且在文章开头明显处给明链接。
<欢迎有不同想法或见解的同学一起探讨,共同进步>