一、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-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</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.1</commons-collections.version> <commons-beanutils.version>1.8.0</commons-beanutils.version> <commons-logging.version>1.2</commons-logging.version> <ezmorph.version>1.0.6</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>2.1_3</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.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.15</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.1</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.9.1</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts-annotations</artifactId> <version>1.0.6</version> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.26-incubating</version> </dependency> <!--Spring dependencies--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.1.9.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>4.1.9.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>4.1.9.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.1.9.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.1.9.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>4.1.9.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.1.9.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>4.1.9.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>4.1.9.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.1.9.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.1.9.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.1.9.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.7</version> </dependency> <!--Hibernate Dependencies--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.3.11.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> <version>4.3.11.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>4.3.11.Final</version> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.10.3</version> </dependency> <dependency> <groupId>antlr</groupId> <artifactId>antlr</artifactId> <version>2.7.7</version> </dependency> <dependency> <groupId>com.fasterxml</groupId> <artifactId>classmate</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>org.hibernate.common</groupId> <artifactId>hibernate-commons-annotations</artifactId> <version>4.0.5.Final</version> </dependency> <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.1-api</artifactId> <version>1.0.0.Final</version> </dependency> <dependency> <groupId>org.javassist</groupId> <artifactId>javassist</artifactId> <version>3.18.1-GA</version> </dependency> <dependency> <groupId>org.jboss</groupId> <artifactId>jandex</artifactId> <version>1.1.0.Final</version> </dependency> <dependency> <groupId>org.apache.ant</groupId> <artifactId>ant</artifactId> <version>1.8.1</version> </dependency> <dependency> <groupId>org.jboss.logging</groupId> <artifactId>jboss-logging</artifactId> <version>3.1.3.GA</version> </dependency> <dependency> <groupId>org.jboss.logging</groupId> <artifactId>jboss-logging-annotations</artifactId> <version>1.2.0.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.0.Final</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.2</version> </dependency> <dependency> <groupId>org.jboss.spec.javax.transaction</groupId> <artifactId>jboss-transaction-api_1.2_spec</artifactId> <version>1.0.1.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.8-dmr</version> </dependency> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.2</version> </dependency> </dependencies>
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>
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.warWEB-INFsrcjavastruts.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="104857600"/> <!-- 让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>
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:-1 事物超时时间由底层事物系统决定 read-only:false rollback-for:所有允许异常回滚 no-rollback-for:所有检查异常不回滚 --> <tx:method name="get*" read-only="true"/> <tx:method name="do*"/> </tx:attributes> </tx:advice> </beans>
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">123456</property> <!-- 每个数据库都有1个,针对特定的关系型数据库生成优化的SQL --> <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property> <!-- 设置默认的数据库连接池 --> <property name="connection.pool_size">5</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>
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>
8.数据库连接
1 jdbc.driver=com.mysql.jdbc.Driver 2 jdbc.url=jdbc:mysql://localhost:3306/webapp?characterEncoding=utf-8&serverTimezone=GMT%2B8&useUnicode=true&useSSL=false 3 jdbc.username=root 4 jdbc.password=123456 5 #最大连接数 6 maxPoolSize=30 7 #最小连接数 8 minPoolSize=10 9 #关闭连接后不自动commit 10 autoCommitOnClose=false 11 #获取连接超时时间 12 checkoutTimeout=10000 13 #当获取连接失败重试次数 14 acquireIncrement=2
三、框架分析
1.建立Action
1 package com.zsm.ssh.action; 2 3 import com.opensymphony.xwork2.ActionSupport; 4 import com.zsm.ssh.model.User; 5 import com.zsm.ssh.service.UserService; 6 import net.sf.json.JSONObject; 7 import org.apache.struts2.ServletActionContext; 8 import org.apache.struts2.convention.annotation.Action; 9 import org.apache.struts2.convention.annotation.Namespace; 10 import org.apache.struts2.convention.annotation.ParentPackage; 11 import org.apache.struts2.convention.annotation.Result; 12 import org.springframework.beans.factory.annotation.Autowired; 13 14 import javax.servlet.http.HttpServletRequest; 15 import javax.servlet.http.HttpServletResponse; 16 import java.io.PrintWriter; 17 18 19 /** 20 * @Author: zengsm. 21 * @Description: 22 * @Date:Created in 2017/12/6 15:45. 23 * @Modified By: 24 */ 25 //默认可以不写 26 @ParentPackage("struts-default") 27 //根命名空间,可以不写 28 @Namespace("/") 29 //全局配置,如果方法上不指定result,则使用该Result 30 //@Results({@Result(name="success",location="/success.jsp"), 31 // @Result(name="error",location="/error.jsp")}) 32 public class UserAction extends ActionSupport 33 { 34 //前台传到后台需要set,后台传到前台需要get 35 // 用户名-必须与页面请求的对应表单username值相同 36 private String username; 37 38 // 密码必须与页面请求的对应表单password值相同 39 private String password; 40 41 private String resultJson; 42 43 /* 44 * struts 接收参数三种方式:属性方式接收,JavaBean方式接收,ModelDriven方式接收参数,前两种都必须设置get和set方法 45 * */ 46 //Spring 注入方式 47 @Autowired 48 private UserService userService; 49 50 //@Action(value="login") 51 @Action(value = "login", results = { 52 @Result(name = "success", location = "/success.jsp", params = {"resultJson", "resultJson"}), 53 @Result(name = "error", location = "/error.jsp")}) 54 public String execute() throws Exception 55 { 56 HttpServletResponse response = ServletActionContext.getResponse(); 57 HttpServletRequest request = ServletActionContext.getRequest(); 58 59 JSONObject result = new JSONObject(); 60 User user = userService.getByName(username); 61 result.put("user", user); 62 63 if (user != null && user.getUser_name().equals(username) && user.getPassword().equals(password)) 64 { 65 result.put("message", "登录成功"); 66 result.put("status", "true"); 67 resultJson = result.toString(); 68 request.setAttribute("resultJson", resultJson); 69 writeResponseData(request, response, result); 70 return "success"; 71 } 72 result.put("message", "登录失败"); 73 result.put("status", "false"); 74 resultJson = result.toString(); 75 writeResponseData(request, response, result); 76 return "error"; 77 } 78 79 private void writeResponseData(HttpServletRequest request, HttpServletResponse response, Object data) 80 { 81 response.setContentType("text/html;charset=utf-8"); 82 try 83 { 84 PrintWriter out = response.getWriter(); 85 out.println(data.toString()); 86 } 87 catch (Exception e) 88 { 89 e.printStackTrace(); 90 } 91 } 92 93 public String getUsername() 94 { 95 return username; 96 } 97 98 public void setUsername(String username) 99 { 100 this.username = username; 101 } 102 103 public void setPassword(String password) 104 { 105 this.password = password; 106 } 107 108 public String getResultJson() 109 { 110 return resultJson; 111 } 112 113 public void setResultJson(String resultJson) 114 { 115 this.resultJson = resultJson; 116 } 117 }
2.建立Service接口和实现类
1 package com.zsm.ssh.service; 2 3 import com.zsm.ssh.model.User; 4 5 import java.util.List; 6 7 8 /** 9 * @Author: zengsm. 10 * @Description: 11 * @Date:Created in 2017/12/6 15:30. 12 * @Modified By: 13 */ 14 public interface UserService 15 { 16 List<User> findAllUser(); 17 18 int saveEntity(User user); 19 20 boolean saveOrUpdateEntity(User user); 21 22 boolean updateEntity(User user); 23 24 User getByName(String name); 25 26 User getByNo(String no); 27 28 boolean deleteUserById(Integer id); 29 30 boolean deleteUserByNo(String no); 31 32 boolean deleteUserByEntity(User user); 33 }
1 package com.zsm.ssh.service.impl; 2 3 import com.zsm.ssh.dao.UserDao; 4 import com.zsm.ssh.model.User; 5 import com.zsm.ssh.service.UserService; 6 import org.springframework.beans.factory.annotation.Autowired; 7 import org.springframework.stereotype.Service; 8 import org.springframework.transaction.annotation.Transactional; 9 10 import java.util.List; 11 12 13 /** 14 * @Author: zengsm. 15 * @Description: 16 * @Date:Created in 2017/12/6 15:31. 17 * @Modified By: 18 */ 19 @Service("userService") 20 @Transactional 21 public class UserServiceImpl implements UserService 22 { 23 @Autowired 24 private UserDao userDao; 25 26 @Override 27 public List<User> findAllUser() 28 { 29 List<User> allUser = userDao.findAllUser(); 30 return allUser; 31 } 32 33 @Override 34 public int saveEntity(User user) 35 { 36 int id = userDao.saveEntity(user); 37 return id; 38 } 39 40 @Override 41 public boolean saveOrUpdateEntity(User user) 42 { 43 try 44 { 45 userDao.saveOrUpdateEntity(user); 46 return true; 47 } 48 catch (Exception e) 49 { 50 e.printStackTrace(); 51 return false; 52 } 53 } 54 55 @Override 56 public boolean updateEntity(User user) 57 { 58 try 59 { 60 userDao.updateEntity(user); 61 return true; 62 } 63 catch (Exception e) 64 { 65 e.printStackTrace(); 66 return false; 67 } 68 } 69 70 @Override 71 public User getByName(String name) 72 { 73 try 74 { 75 User user = userDao.getByName(name); 76 return user; 77 } 78 catch (Exception e) 79 { 80 e.printStackTrace(); 81 return null; 82 } 83 } 84 85 @Override 86 public User getByNo(String no) 87 { 88 try 89 { 90 User user = userDao.getByNo(no); 91 return user; 92 } 93 catch (Exception e) 94 { 95 e.printStackTrace(); 96 return null; 97 } 98 } 99 100 @Override 101 public boolean deleteUserById(Integer id) 102 { 103 try 104 { 105 userDao.deleteUserById(id); 106 return true; 107 } 108 catch (Exception e) 109 { 110 e.printStackTrace(); 111 return false; 112 } 113 } 114 115 @Override 116 public boolean deleteUserByNo(String no) 117 { 118 try 119 { 120 userDao.deleteUserByNo(no); 121 return true; 122 } 123 catch (Exception e) 124 { 125 e.printStackTrace(); 126 return false; 127 } 128 } 129 130 @Override 131 public boolean deleteUserByEntity(User user) 132 { 133 try 134 { 135 userDao.deleteUserByEntity(user); 136 return true; 137 } 138 catch (Exception e) 139 { 140 e.printStackTrace(); 141 return false; 142 } 143 } 144 }
3.建立Dao接口和实现类
1 package com.zsm.ssh.dao; 2 3 import com.zsm.ssh.model.User; 4 5 import java.util.List; 6 7 8 /** 9 * @Author: zengsm. 10 * @Description: 11 * @Date:Created in 2017/12/6 15:32. 12 * @Modified By: 13 */ 14 public interface UserDao 15 { 16 List<User> findAllUser(); 17 18 int saveEntity(User user); 19 20 void saveOrUpdateEntity(User user); 21 22 void updateEntity(User user); 23 24 User getByName(String name); 25 26 User getByNo(String no); 27 28 void deleteUserById(Integer id); 29 30 void deleteUserByNo(String no); 31 32 void deleteUserByEntity(User user); 33 }
1 package com.zsm.ssh.dao.impl; 2 3 import com.zsm.ssh.dao.UserDao; 4 import com.zsm.ssh.model.User; 5 import org.hibernate.Query; 6 import org.hibernate.Session; 7 import org.hibernate.SessionFactory; 8 import org.springframework.beans.factory.annotation.Autowired; 9 import org.springframework.orm.hibernate4.support.HibernateDaoSupport; 10 import org.springframework.stereotype.Repository; 11 import org.springframework.transaction.annotation.Propagation; 12 import org.springframework.transaction.annotation.Transactional; 13 14 import java.util.List; 15 16 17 /** 18 * @Author: zengsm. 19 * @Description: 20 * @Date:Created in 2017/12/6 15:36. 21 * @Modified By: 22 */ 23 @Repository("userDao") 24 public class UserDaoImpl extends HibernateDaoSupport implements UserDao 25 { 26 //这里的属性名一定要和配置中的属性名一致 27 @Autowired 28 private SessionFactory sessionFactory; 29 30 @Override 31 @Transactional(propagation = Propagation.REQUIRED) 32 public List<User> findAllUser() 33 { 34 Session session = sessionFactory.openSession(); 35 //将所有的数据查询出来并放到List集合里 User是表对应的实例名称 36 List<User> list = session.createQuery("from User").list(); 37 session.close(); 38 return list; 39 } 40 41 @Override 42 @Transactional(propagation = Propagation.REQUIRED) 43 public int saveEntity(User user) 44 { 45 Session session = sessionFactory.getCurrentSession(); 46 //返回插入数据id 47 Object id = session.save(user); 48 return Integer.valueOf(id.toString()); 49 } 50 51 @Override 52 @Transactional(propagation = Propagation.REQUIRED) 53 public void saveOrUpdateEntity(User user) 54 { 55 Session session = sessionFactory.getCurrentSession(); 56 session.saveOrUpdate(user); 57 } 58 59 @Override 60 @Transactional(propagation = Propagation.REQUIRED) 61 public void updateEntity(User user) 62 { 63 Session session = sessionFactory.getCurrentSession(); 64 session.update(user); 65 } 66 67 @Override 68 @Transactional(propagation = Propagation.REQUIRED) 69 public User getByName(String name) 70 { 71 Session session = sessionFactory.getCurrentSession(); 72 //根据id查询,结果返回 User.class 73 User user = (User)session.get(User.class, 2); 74 //将所有的数据查询出来并放到List集合里 User是表对应的实例名称 75 List users = session.createQuery("from User where user_name='" + name + "'").list(); 76 return (User)users.get(0); 77 } 78 79 @Override 80 @Transactional(propagation = Propagation.REQUIRED) 81 public User getByNo(String no) 82 { 83 Session session = sessionFactory.getCurrentSession(); 84 List users = session.createQuery("from User where user_no='" + no + "'").list(); 85 return (User)users.get(0); 86 } 87 88 @Override 89 @Transactional(propagation = Propagation.REQUIRED) 90 public void deleteUserById(Integer id) 91 { 92 Session session = sessionFactory.getCurrentSession(); 93 String sql = "delete from User where id=:id"; 94 Query query = session.createQuery(sql); 95 query.setParameter("id", id); 96 query.executeUpdate(); 97 } 98 99 @Override 100 @Transactional(propagation = Propagation.REQUIRED) 101 public void deleteUserByNo(String no) 102 { 103 Session session = sessionFactory.getCurrentSession(); 104 String sql = "delete from User where user_no=:no"; 105 Query query = session.createQuery(sql); 106 query.setParameter("no", no); 107 query.executeUpdate(); 108 } 109 110 @Override 111 @Transactional(propagation = Propagation.REQUIRED) 112 public void deleteUserByEntity(User user) 113 { 114 Session session = sessionFactory.getCurrentSession(); 115 //传入实例对象,比较id删除对应行,,没有id匹配就不删除 116 session.delete(User.class.getName(), user); 117 } 118 }
四、源码分享
欢迎Star个人GitHub:https://github.com/lovelifeming/Resource/tree/master/SSH
备注:
作者:Shengming Zeng
博客:http://www.cnblogs.com/zengming/
本文是原创,欢迎大家转载;但转载时必须注明文章来源,且在文章开头明显处给明链接。
<欢迎有不同想法或见解的同学一起探讨,共同进步>