前记:刚刚学ssh整合的时候就发现一个很不开心的问题,怎么这么多配置文件!!!详情看这里
特别是entity那里,一个entity一个配置文件,晕死。如果项目涉及的entity很多的话,岂不是要忙死程序员,而且修改字段的话,修改了entity的Java类,还得修改相应的配置文件,类和配置文件的耦合性简直强到了极致。这是其一。其二,视图的跳转也是通过配置文件的,也是烦,虽然可以通过通配符来减少Struts.xml中action节点的数量,但是这个也是很强的耦合性啊。这次,这两个问题要通过一个新的东西,一次性解决。
框架详情:SpringMVC4.3.7+Hibernate4.1.7+Spring4.3.7
junit-4.11.jar
hamcrest-core-1.3.jar
spring-core-4.3.7.RELEASE.jar
commons-logging-1.2.jar
spring-beans-4.3.7.RELEASE.jar
spring-context-4.3.7.RELEASE.jar
spring-aop-4.3.7.RELEASE.jar
spring-expression-4.3.7.RELEASE.jar
spring-jdbc-4.3.7.RELEASE.jar
spring-tx-4.3.7.RELEASE.jar
spring-web-4.3.7.RELEASE.jar
spring-webmvc-4.3.7.RELEASE.jar
spring-orm-4.3.7.RELEASE.jar
hibernate-core-4.1.7.Final.jar
antlr-2.7.7.jar
jboss-logging-3.1.0.GA.jar
jboss-transaction-api_1.1_spec-1.0.0.Final.jar
dom4j-1.6.1.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
javassist-3.15.0-GA.jar
hibernate-commons-annotations-4.0.1.Final.jar
mysql-connector-java-5.1.21.jar
c3p0-0.9.1.2.jar
jstl-1.2.jar
jsp-api-2.2.1-b03.jar
fastjson-1.1.24.jar
servlet-api-2.5.jar
commons-fileupload-1.3.2.jar
commons-io-2.2.jar
<!--数据库配置-->
<context:property-placeholder location="/WEB-INF/configs/db.properties" />
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${driverClass}">
</property>
<property name="jdbcUrl" value="${jdbcUrl}">
</property>
<property name="user" value="${user}">
</property>
<property name="password" value="${password}">
</property>
<property name="maxPoolSize" value="${maxPoolSize}">
</property>
<property name="minPoolSize" value="${minPoolSize}">
</property>
<property name="maxStatements" value="${maxStatements}">
</property>
<property name="acquireIncrement" value="${acquireIncrement}">
</property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="/WEB-INF/configs/hibernate.cfg.xml"></property>
<property name="packagesToScan" value="com.ycTime.bean" />
<!--这几个属性的配置是为了避免出现数据库连接8小时后连接失效而导致项目无法访问-->
<property name="hibernateProperties">
<props>
<prop key="hibernate.c3p0.testConnectionOnCheckout">true</prop>
<prop key="hibernate.c3p0.idle_test_period">60</prop>
<prop key="hibernate.c3p0.acquire_increment">2</prop>
<prop key="hibernate.c3p0.validate">true</prop>
</props>
</property>
</bean>
<!--定义拦截器 -->
<bean id="springMethodInterceptor" class="com.ycTime.interceptor.UserCheckInterceptor"></bean>
<aop:config>
<!--切入点 -->
<aop:pointcut id="loginPoint" expression="execution(public * com.ycTime.controller.*.*(..)) " />
<!--在该切入点使用自定义拦截器 -->
<!--切入点 -->
<aop:pointcut id="adminLoginPoint" expression="execution(public * com.ycTime.controller.payAdmin.*.*(..)) " />
<!--在该切入点使用自定义拦截器 -->
<aop:advisor pointcut-ref="adminLoginPoint" advice-ref="springMethodInterceptor" />
<aop:advisor pointcut-ref="loginPoint" advice-ref="springMethodInterceptor" />
</aop:config>
<!--开启包扫描-->
<context:component-scan base-package="com.ycTime.controller"></context:component-scan>
<context:component-scan base-package="com.ycTime.dao"></context:component-scan>
<context:component-scan base-package="com.ycTime.service"></context:component-scan>
<context:component-scan base-package="com.ycTime.util"></context:component-scan>
<context:component-scan base-package="com.ycTime.bean"></context:component-scan>
<!--开启事务管理-->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
<!--文件上传的时候要用到这个-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="UTF-8" />
</beans>
这个db.properties还是挺关键的,解耦嘛,哈哈,数据库的配置文件不用和哪一个框架的配置文件耦合在一起
db.properties:user=root
password=XXXX
driverClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/nslc?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8
maxPoolSize=20
minPoolSize=5
maxStatements=100
acquireIncrement=2
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="dialect">
org.hibernate.dialect.MySQL5InnoDBDialect
</property>
<property name="hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<property name="minPoolSize" >10</property>
<!--连接池中保留的最大连接数。Default: 15 -->
<property name="maxPoolSize" >100</property>
<!--最大空闲时间,1800秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
<property name="maxIdleTime" >1800</property>
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
<property name="acquireIncrement" >3</property>
<property name="maxStatements" >1000</property>
<property name="initialPoolSize">10</property>
<!--每60秒检查所有连接池中的空闲连接。Default: 0 -->
<property name="idleConnectionTestPeriod" >60</property>
<!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->
<property name="acquireRetryAttempts" >30</property>
<property name="breakAfterAcquireFailure" >true</property>
<property name="testConnectionOnCheckout" >false</property>
<!-- 最大连接数 -->
<property name="hibernate.c3p0.max_size">20</property>
<!-- 最小连接数 -->
<property name="hibernate.c3p0.min_size">5</property>
<!-- 获得连接的超时时间,如果超过这个时间,会抛出异常,单位毫秒 -->
<property name="hibernate.c3p0.timeout">120</property>
<!-- 最大的PreparedStatement的数量 -->
<property name="hibernate.c3p0.max_statements">100</property>
<!-- 每隔120秒检查连接池里的空闲连接 ,单位是秒 -->
<property name="hibernate.c3p0.idle_test_period">120</property>
<!-- 当连接池里面的连接用完的时候,C3P0一下获取的新的连接数 -->
<property name="hibernate.c3p0.acquire_increment">2</property>
<!-- 每次都验证连接是否可用 -->
<property name="hibernate.c3p0.validate">true</property>
</session-factory>
</hibernate-configuration>
<?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>
NSLC
</display-name>
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/configs/ApplicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>Dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/configs/ApplicationContext.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Dispatcher</servlet-name>
<url-pattern>.do</url-pattern>
</servlet-mapping>
<filter>
<filter-name>encoding</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>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping>
<context-param>
</web-app>
对的,你没看错,就是写Java代码了,上文中的applicationContext.xml不知道有没有用心看呢,扫描配置那里多了好多需要扫描的包。对的,就是通过注解来完成之前那些那么多的配置文件做的事。
直接上代码:
entity:
- Inform.java
import java.util.Date;
import javax.persistence.*;
import org.springframework.core.annotation.Order;
@Entity(name = "Inform")
@Table(name = "nslc_Inform")
public class Inform {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(nullable=false)
private Date informTime;
@Column(nullable=false,columnDefinition="text")
private String informContent;
@ManyToOne(targetEntity=User.class)
@JoinColumn(name="user_id")
private User beInformer;
@Override
public String toString() {
String s = " Inform [ "+
" id = "+id+" informTime = "+informTime+" informContent = "+informContent+
" beInformer_id = "+beInformer+
" ]";
return s;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getInformTime() {
return informTime;
}
public void setInformTime(Date informTime) {
this.informTime = informTime;
}
public String getInformContent() {
return informContent;
}
public void setInformContent(String informContent) {
this.informContent = informContent;
}
public User getBeInformer() {
return beInformer;
}
public void setBeInformer(User beInformer) {
this.beInformer = beInformer;
}
}
在这个Inform类中,可以看到类名上有两个注解,@Entity的意思就是将这个实体类声明为“Inform”,@Table的意思则是对应的数据库的表的名字,其次,在每一个private属性的字段上也有对应的@column注解,该注解里面还有很多属性,可以翻阅API来查看,这里就不详细描述了。还有beInformer上有个@ManyToOne和@JoinColumn,manyToOne顾名思义,多对一,而JoinColumn就是该表上(nslc_Inform)该字段(user_id)的相关限制。
只要每个实体类都做好这个注解,做好多对一和一对多以及多对多之间的对应,就可以省略一大堆的配置文件,而且要修改数据库字段,直接修改Java类就可以了,简直强到爆炸。
Dao和Service,这两个和上一篇的配置并没有区别,所以就不写在这了。
Controller(即Action)
这里,前言中的另外一个问题就是在这解决的,上代码
@Controller @RequestMapping("/inform") public class InformController { @Autowired private InformService informService; @LoginRequired @RequestMapping("/getInformIndex") public String getInforms(HttpServletRequest request, HttpServletResponse response){ try { User user = (User) request.getSession().getAttribute("user"); JudgementEncapsulatedBean judgementEncapsulatedBean = new JudgementEncapsulatedBean(); judgementEncapsulatedBean.append("beInformer", user); PageVo<Inform> pageVo = informService.findDataByPage(judgementEncapsulatedBean, 7, 5,"id","desc"); request.setAttribute("pageVo", pageVo); return "/success.jsp"; } catch (Exception e) { e.printStackTrace(); request.setAttribute("error", e.getMessage()); return "/fail.jsp"; } } }
然后到这里,ssh就这样整合完成了,相比于之前那一次,这一次的整合真的是轻松多了,省了超多代码,避免了写一大堆配置文件的麻烦,棒极了。