前记:刚刚学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
二. 写applicationContext.xml
<code>
<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" />
<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>
</code>
三. 写数据库相关的配置
这个db.properties还是挺关键的,解耦嘛,哈哈,数据库的配置文件不用和哪一个框架的配置文件耦合在一起
db.properties:
<code>
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
</code>hibernate.cfg.xml
<code>
<?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>
<property name="maxPoolSize" >100</property>
<property name="maxIdleTime" >1800</property>
<property name="acquireIncrement" >3</property>
<property name="maxStatements" >1000</property>
<property name="initialPoolSize">10</property>
<property name="idleConnectionTestPeriod" >60</property>
<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>
<property name="hibernate.c3p0.max_statements">100</property>
<property name="hibernate.c3p0.idle_test_period">120</property>
<property name="hibernate.c3p0.acquire_increment">2</property>
<property name="hibernate.c3p0.validate">true</property>
</session-factory>
</hibernate-configuration>
</code>
四.写web.xml
<code>
<?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>
</code>
五. 直接写类代码!!!
对的,你没看错,就是写Java代码了,上文中的applicationContext.xml不知道有没有用心看呢,扫描配置那里多了好多需要扫描的包。对的,就是通过注解来完成之前那些那么多的配置文件做的事。
直接上代码:
entity:
- Inform.java
<code>
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;
}
}
</code>
在这个Inform类中,可以看到类名上有两个注解,@Entity的意思就是将这个实体类声明为“Inform”,@Table的意思则是对应的数据库的表的名字,其次,在每一个private属性的字段上也有对应的@column注解,该注解里面还有很多属性,可以翻阅API来查看,这里就不详细描述了。还有beInformer上有个@ManyToOne和@JoinColumn,manyToOne顾名思义,多对一,而JoinColumn就是该表上(nslc_Inform)该字段(user_id)的相关限制。
只要每个实体类都做好这个注解,做好多对一和一对多以及多对多之间的对应,就可以省略一大堆的配置文件,而且要修改数据库字段,直接修改Java类就可以了,简直强到爆炸。
Dao和Service,这两个和上一篇的配置并没有区别,所以就不写在这了。
Controller(即Action)
这里,前言中的另外一个问题就是在这解决的,上代码
<code>
@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";
}
}
}
</code>
- 首先是类名上面的注释,我们看@RequestMapping("/inform"),这个其实相当于上一篇中的namespace,也就是我们需要访问这个类的方法的时候,需要在项目的URL上加上"inform"。
- 其次,我们看getInforms方法上的注解,@LoginRequired和@RequestMapping("/getInformIndex"),LoginRequired是我自定义的注解,为的是实现登录拦截,这里暂且不提。而在方法这里的@RequestMapping,相当于上一篇中Struts.xml里写的action节点里的name属性。
- 还有,方法里传入了HttpServletRequest和HttpServletResponse参数,我们就不需要在方法里再获取一次,节约了不少代码。
- 最后,看返回值,同样都是String类型的返回值,但是在这里直接就指定了返回的具体页面(可以重定向,还可以把action作为跳转目的,具体请查阅API)。
所以这个方法是怎么回事呢,在浏览器访问localhost:8080/nslc/inform/getInformIndex.do,然后就会访问到我们InformController中的getInforms方法,最后跳转到success.jsp或者fail.jsp中。
然后到这里,ssh就这样整合完成了,相比于之前那一次,这一次的整合真的是轻松多了,省了超多代码,避免了写一大堆配置文件的麻烦,棒极了。