Maven搭建struts2+spring+hibernate环境(一)
本文简单的使用STS的自带的maven插件工具搭建ssh(struts2+spring+hibernate)开发环境,图文并茂,简单上手,适合新手。
关于STS的介绍,请参考另一篇文章《Java IDE介绍:Spring开发利器-spring-tool-suite》地址:http://blog.csdn.net/sgl731524380/article/details/8831540
首先,STS自带的maven的插件已经默认有了maven,但是不建议使用默认的 maven。更改STS默认的maven可在windows-preferences-Maven 选项下,同时我将在另一篇文章里也有介绍,《STS,MyEclipse中Maven配置》 地址:http://blog.csdn.net/sgl731524380/article/details/8871470
一、新建Maven项目。
New--Project--Maven Project,
next.
next,输入webapp,检索,选中maven-aechetype-webapp
next,
Finish即可。
项目结构如图(修改了pom.xml文件,使用JUnit4):
二、搭建struts2+spring+hibernate
双击打开pom.xml,配置pom.xml文件。配置如下,
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.sgl</groupId><artifactId>MSSH</artifactId><packaging>war</packaging><version>0.0.1-SNAPSHOT</version><name>MSSH Maven Webapp</name><url>http://maven.apache.org</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><!-- log4j 日志--><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency><!-- servlet API --><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1-b09</version><scope>provided</scope></dependency><!-- MySQL驱动 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.24</version></dependency><!-- mchange C3P0 数据源--><dependency><groupId>com.mchange</groupId><artifactId>c3p0</artifactId><version>0.9.5-pre2</version></dependency><!-- junit --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.11</version><scope>test</scope></dependency><!-- fastjson --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.1.29</version></dependency><!-- struts2 --><dependency><groupId>org.apache.struts</groupId><artifactId>struts2-core</artifactId><version>2.3.14</version><exclusions><exclusion><groupId>javassist</groupId><artifactId>javassist</artifactId></exclusion></exclusions></dependency><dependency><groupId>org.apache.struts</groupId><artifactId>struts2-spring-plugin</artifactId><version>2.3.14</version></dependency><dependency><groupId>org.apache.struts</groupId><artifactId>struts2-convention-plugin</artifactId><version>2.3.14</version></dependency><!-- spring --><dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>3.2.2.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>3.2.2.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>3.2.2.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-beans</artifactId><version>3.2.2.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>3.2.2.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-expression</artifactId><version>3.2.2.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-orm</artifactId><version>3.2.2.RELEASE</version></dependency><!-- aspectjweaver --><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.7.2</version></dependency><!-- hibernate --><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-core</artifactId><version>4.2.0.Final</version></dependency></dependencies><build><!-- Maven插件 --><plugins><plugin><artifactId>maven-war-plugin</artifactId></plugin><plugin><artifactId>maven-compiler-plugin</artifactId><configuration><source>1.6</source><target>1.6</target><encoding>utf-8</encoding></configuration></plugin><plugin><artifactId>maven-resources-plugin</artifactId><configuration><encoding>utf-8</encoding></configuration></plugin><plugin><artifactId>maven-javadoc-plugin</artifactId><configuration><encoding>utf-8</encoding></configuration></plugin><plugin><artifactId>maven-surefire-plugin</artifactId><version>2.7.2</version><configuration><forkMode>once</forkMode><argLine>-Dfile.encoding=UTF-8</argLine></configuration></plugin></plugins></build> </project>
保存,Maven会自动联网去下载所有需要的jar包,至于只写jar的名字,不用记住,只要去Maven中央仓库去搜索,Maven中央仓库地址:http://search.maven.org/
完成之后,多了很多jar,并且都放到了配置的本地仓库中,以后要再使用相同版本的jar时候,就不需要联网下载了。
这时候,所有需要的jar都到齐了。
后面一篇我将演示如何写一个小小的程序来验证ssh框架搭建是否成功。
Maven搭建struts2+spring+hibernate环境(二)
一、修改项目结构
上一篇中我们已经完成了jar的引入,现在开始构建测试程序。刚刚完成的 project图标上可能有一个红色的叉,只需要把项目复制--粘贴--重命名。即可解决,并不是项目搭建错误所致,这可能是IDE的一个bug吧,在 MyEclipse中搭建也出现这种情况,解决方法一样。
但是,构建的MSSH项目的结构并不是一个标准的Maven结构,我们需要手动新建几个Source Folder(注意:是source folder,不是package!!)。
完成后的结构如下:
src/main.java:存放java源文件
src/main/resources:存放项目配置文件,如spring.xml,hibernate.cfg.xml。。。
src/test/java:存放test的java文件
src/test/resources:存放test时候所需的配置文件
二、编写程序
建立如下的结构
编写配置文件,各种配置的含义我在此就不累赘了,有ssh使用基础的同学都能看懂的。
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"> <struts><!-- 将Action交给spring容器管理 --><constant name="struts.objectFactory" value="spring" /><!-- 模式为开发模式,修改xml配置文件会自动加载,项目交付的时候设置为false,以免影响性能 --><constant name="struts.devMode" value="true" /><constant name="struts.configuration.xml.reload" value="true" /><!-- 字符集编码 --><constant name="struts.i18n.encoding" value="utf-8" /><package name="defaultPackage" namespace="/" extends="struts-default"><action name="userAction" class="userAction" method="reg"><result name="success">/success.jsp</result><result name="error">/error.jsp</result></action></package> </struts>
spring.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:context="http://www.springframework.org/schema/context"xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"><!-- 引入属性文件 --><context:property-placeholder location="classpath:database.properties" /><!-- 自动扫描dao和service包(自动注入) --><context:component-scan base-package="com.sgl.action,com.sgl.dao.impl,com.sgl.service" /></beans>
spring-hibernate.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:tx="http://www.springframework.org/schema/tx"xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"><!-- 使用C3P0数据源,MySQL数据库 --><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"destroy-method="close"><!-- MySQL5 --><property name="driverClass" value="${driverClassName}"></property><property name="jdbcUrl" value="${url}"></property><property name="user" value="${username}"></property><property name="password" value="${password}"></property> <property name="maxPoolSize" value="40"></property><property name="minPoolSize" value="1"></property><property name="initialPoolSize" value="1"></property><property name="maxIdleTime" value="20"></property></bean><!-- session工厂 --><bean id="sessionFactory"class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"><property name="dataSource" ref="dataSource" /><property name="hibernateProperties"><props><prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop><prop key="hibernate.dialect">${hibernate.dialect}</prop><prop key="hibernate.show_sql">${hibernate.show_sql}</prop><prop key="hibernate.format_sql">${hibernate.format_sql}</prop></props></property><!-- 注解方式配置 --><property name="packagesToScan"><list><value>com.sgl.model</value></list></property></bean><!-- 配置事务 --><bean name="txManager"class="org.springframework.orm.hibernate4.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory"></property></bean><tx:annotation-driven transaction-manager="txManager" /></beans>
database.properties
hibernate.dialect=org.hibernate.dialect.MySQLDialect driverClassName=com.mysql.jdbc.Driver validationQuery=SELECT 1 url=jdbc:mysql://localhost:3306/mssh?useUnicode=true&characterEncoding=UTF-8 username=root password=sglhibernate.hbm2ddl.auto=update hibernate.show_sql=true hibernate.format_sql=true
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"><display-name></display-name><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring.xml,classpath:spring-hibernate.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><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></filter><filter-mapping><filter-name>encodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><!--Hibernate的session丢失解决方法 --><filter><filter-name>openSessionInView</filter-name><filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class></filter><filter-mapping><filter-name>openSessionInView</filter-name><url-pattern>/*</url-pattern></filter-mapping><!-- struts2配置 --><filter><filter-name>struts2</filter-name><filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class></filter><filter-mapping><filter-name>struts2</filter-name><url-pattern>/*</url-pattern></filter-mapping><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list> </web-app>
编写java文件,采用MVC架构,使用hibernate,spring注解
User.java
package com.sgl.model;import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient;@SuppressWarnings("serial") @Entity @Table(name = "tuser") public class User implements java.io.Serializable {private String id;private Date regtime;private String username;private String password;@Column(name="password",nullable=false,length=20)public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}private String code;@Transientpublic String getCode() {return code;}public void setCode(String code) {this.code = code;}public User(){}public User(String id, Date regtime, String username,String password) {super();this.id = id;this.regtime = regtime;this.username = username;this.password = password;}@Id@Column(name = "id", nullable = false, length = 36)public String getId() {return id;}public void setId(String id) {this.id = id;}@Temporal(TemporalType.TIMESTAMP)@Column(name = "regtime", length = 7)public Date getRegtime() {return regtime;}public void setRegtime(Date regtime) {this.regtime = regtime;}@Column(name = "username", unique = false, nullable = false, length = 100)public String getUsername() {return username;}public void setUsername(String username) {this.username = username;} }
UserDaoI.java
package com.sgl.dao;import java.io.Serializable;public interface UserDaoI<T> {public Serializable save(T o); }
UserDaoImpl.java
package com.sgl.dao.impl;import java.io.Serializable; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.sgl.dao.UserDaoI;@Repository("userDao") public class UserDaoImpl<T> implements UserDaoI<T> {//注入sessionfactory @Autowiredprivate SessionFactory sessionFactory;public Serializable save(T o) {return sessionFactory.getCurrentSession().save(o);}}
UserService.java
package com.sgl.service;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.sgl.dao.UserDaoI; import com.sgl.model.User; @Service("userService") @Transactional public class UserService //之前这里写错成了UserServiceImpl,谢谢wangdianyong的提醒,此处已做修改 { //自动注入dao @Autowiredprivate UserDaoI<User> userDao;public void addUser(User user){userDao.save(user);}}
UserAction.java
package com.sgl.action;import java.util.Date; import java.util.UUID; 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 com.sgl.model.User; import com.sgl.service.UserService; //修改为UserService @controller("userAction") public class UserAction {@Autowiredprivate UserService userService;private User user;public User getUser(){return user;}public void setUser(User user){this.user = user;}public String reg(){user.setId(UUID.randomUUID().toString());user.setRegtime(new Date());try{ userService.addUser(user);ServletActionContext.getContext().getSession().put("user", user);ServletActionContext.getContext().getSession().put("msg", "注册成功了,可以去登陆了");return "success";} catch (Exception e){e.printStackTrace();ServletActionContext.getContext().getSession().put("msg", "注册失败了");return "error";}} }
Maven搭建struts2+spring+hibernate环境(三)
后台功能都已完成,现在是前台的页面编写
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>注册</title>
</head>
<body>
<form action="userAction" method="post"><table width="207" border="0" align="center"><tr><td colspan="2" align="center" nowrap="nowrap">用户注册</td></tr><tr><td width="68" nowrap="nowrap">用户名</td><td width="127" nowrap="nowrap"><label><input name="user.username" type="text" id="username" size="20" /></label></td></tr><tr><td nowrap="nowrap">密 码</td><td nowrap="nowrap"><input name="user.password" type="password" id="password" size="20" maxlength="10" /></td></tr><tr><td colspan="2" align="center" nowrap="nowrap"><label><input type="submit" value="注册" /><input type="reset" value="重填" /></label></td></tr></table>
</form>
</body>
</html>
success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> ${user.username } <br> ${msg } </body> </html>
error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> 出错了。。。。。。。。。。 </body> </html>
至此,项目编写基本完成。
右键项目---run as---maven install
编译成功,没有错误
现在可以部署到服务器上运行了,部署,启动,浏览器输入http://localhost:8080/MSSH/或者http://localhost:8080/MSSH/index.jsp回车
注册,查看数据库,成功!
至此,Maven搭建struts2+spring+hibernate开发环境就完成了,其中还有很多不足之处,希望大家指出。