在Eclipse中使用Struts和Hibernate框架搭建Maven Web项目
前言
学习使用Java还是2012年的事情,刚开始学习的Java的时候,使用的是MyEclipse工具和SSH框架。初学者适合使用MyEclipse,因为他将struts、Spring和Hibernate等框架集成在IDE中,可以直接通过添加Capacities将这些框架集成到Web Project中,相应的Jar包也会自动添加到lib目录下,开发过程中还是需要手动添加一些jar包。再后来开始接触Maven,在Eclipse下搭建Maven Web项目。在后来就转C#项目开发了,项目做了快两年的时间,到最近才开始重新拾起这些尘封很久的东西。虽然之前做过Java Web项目,但是最近重温的时候才发现,要始终保持一颗Coding的心,不然真是的是寸步难行啊。这篇文章没有什么技术含量,主要是为后来者提供入门的帮助。
一、工具准备
必备工具:JDK(jdk1.6.0_10)、Eclipse、Maven(apache-maven-3.0.5)。
开发过程中,使用Jetty来替代Tomcat来发布项目,在项目完成之后,可以直接部署在Tomcat中。JDK、Eclipse的安装和配置在Baidu上可以找到很多,这里不再赘述。Maven插件的安装教程网上也有,在Maven依赖库的使用上建议使用自定义路径的本地Repository,只需要配置一下settings.xml文件,如<localRepository>D:/Program Files/Java/Maven Local Repository/repository</localRepository>。
二、搭建Maven Web项目
New Maven Project,在选择项目 Archetype(原型)的时候,GroupID选择org.apach.maven.archetype,ArtifactID选择maven-archetype-webapp,接着就是设置项目的GroupID、ArtifactID,其中ArtifactID就是项目名称。
新建好的项目结构如下:
如果项目结构不一样,是因为选择的Perspective的问题,要选择Java Perspective。在src/main目录下添加Source Folder:src/main/java。
1 配置web.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app id="pp_monitor" version="2.4" 3 xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> 5 6 <display-name>MavenSSH2</display-name> 7 8 <filter> 9 <filter-name>struts2</filter-name> 10 <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> 11 </filter> 12 <filter-mapping> 13 <filter-name>struts2</filter-name> 14 <url-pattern>/*</url-pattern> 15 <dispatcher>REQUEST</dispatcher> 16 <dispatcher>FORWARD</dispatcher> 17 </filter-mapping> 18 19 </web-app>
主要是配置过滤器,将struts融入到项目中,表示对应当前应用里面的所有请求都使用org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter进行处理。
2 配置pom.xml
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 3 <modelVersion>4.0.0</modelVersion> 4 <groupId>liu.test.maven</groupId> 5 <artifactId>MavenSSH2</artifactId> 6 <packaging>war</packaging> 7 <version>0.0.1-SNAPSHOT</version> 8 <name>MavenSSH2</name> 9 <url>http://maven.apache.org</url> 10 <dependencies> 11 12 <dependency> 13 <groupId>junit</groupId> 14 <artifactId>junit</artifactId> 15 <version>3.8.1</version> 16 <scope>test</scope> 17 </dependency> 18 <dependency> 19 <groupId>org.apache.struts</groupId> 20 <artifactId>struts-taglib</artifactId> 21 <version>1.3.10</version> 22 </dependency> 23 <dependency> 24 <groupId>org.hibernate</groupId> 25 <artifactId>hibernate</artifactId> 26 <version>3.2.7</version> 27 </dependency> 28 29 <!-- 必备依赖 --> 30 <dependency> 31 <groupId>org.apache.struts</groupId> 32 <artifactId>struts2-core</artifactId> 33 <version>2.2.3</version> 34 </dependency> 35 <dependency> 36 <groupId>org.freemarker</groupId> 37 <artifactId>freemarker</artifactId> 38 <version>2.3.14</version> 39 </dependency> 40 <dependency> 41 <groupId>commons-fileupload</groupId> 42 <artifactId>commons-fileupload</artifactId> 43 <version>1.2.2</version> 44 </dependency> 45 <dependency> 46 <groupId>commons-lang</groupId> 47 <artifactId>commons-lang</artifactId> 48 <version>2.6</version> 49 </dependency> 50 <dependency> 51 <groupId>commons-io</groupId> 52 <artifactId>commons-io</artifactId> 53 <version>2.3</version> 54 </dependency> 55 <dependency> 56 <groupId>commons-logging</groupId> 57 <artifactId>commons-logging</artifactId> 58 <version>1.1.1</version> 59 </dependency> 60 <dependency> 61 <groupId>org.apache.struts.xwork</groupId> 62 <artifactId>xwork-core</artifactId> 63 <version>2.2.3.1</version> 64 </dependency> 65 <dependency> 66 <groupId>ognl</groupId> 67 <artifactId>ognl</artifactId> 68 <version>3.0.5</version> 69 </dependency> 70 <dependency> 71 <groupId>dom4j</groupId> 72 <artifactId>dom4j</artifactId> 73 <version>1.6.1</version> 74 </dependency> 75 <!-- 使用hbm映射文件必备 --> 76 <dependency> 77 <groupId>commons-collections</groupId> 78 <artifactId>commons-collections</artifactId> 79 <version>3.2.1</version> 80 </dependency> 81 <!-- 使用hibernate必备 --> 82 <dependency> 83 <groupId>cglib</groupId> 84 <artifactId>cglib</artifactId> 85 <version>2.2.2</version> 86 </dependency> 87 <dependency> 88 <groupId>antlr</groupId> 89 <artifactId>antlr</artifactId> 90 <version>2.7.7</version> 91 </dependency> 92 <!-- SQL Server驱动 --> 93 <dependency> 94 <groupId>net.sourceforge.jtds</groupId> 95 <artifactId>jtds</artifactId> 96 <version>1.2.4</version> 97 </dependency> 98 <!-- 必备依赖 --> 99 </dependencies> 100 101 <build> 102 <finalName>MavenSSH2</finalName> 103 <sourceDirectory>src/main/java</sourceDirectory> 104 <outputDirectory>target/${project.name}/WEB-INF/classes</outputDirectory> 105 106 <plugins> 107 <plugin> 108 <groupId>org.mortbay.jetty</groupId> 109 <artifactId>maven-jetty-plugin</artifactId> 110 <version>6.1.24</version> 111 <configuration> 112 <scanIntervalSeconds>10</scanIntervalSeconds> 113 <contextPath>/</contextPath> 114 <stopKey>foo</stopKey> 115 <stopPort>9999</stopPort> 116 </configuration> 117 <executions> 118 <execution> 119 <id>start-jetty</id> 120 <phase>pre-integration-test</phase> 121 <goals> 122 <goal>run</goal> 123 </goals> 124 <configuration> 125 <scanIntervalSeconds>0</scanIntervalSeconds> 126 <daemon>true</daemon> 127 </configuration> 128 </execution> 129 <execution> 130 <id>stop-jetty</id> 131 <phase>post-integration-test</phase> 132 <goals> 133 <goal>stop</goal> 134 </goals> 135 </execution> 136 </executions> 137 </plugin> 138 </plugins> 139 <!-- 140 <resources> 141 <resource> 142 143 <targetPath>${basedir}/target/${project.name}/WEB-INF/classes</targetPath> 144 <filtering>false</filtering> 145 <directory>${basedir}/src/main/resources</directory> 146 <includes> 147 <include>**/*.*</include> 148 </includes> 149 <excludes> 150 <exclude></exclude> 151 </excludes> 152 </resource> 153 </resources> 154 --> 155 </build> 156 </project>
pom中配置了使用Struts和Hibernate框架必备的依赖,以及用于开发测试的Jetty服务器plugin。
3、配置Hibernate配置文件hibernate.cfg.xml
在src/main/resources下新建XML文件,命名hibernate.cfg.xml。
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-configuration PUBLIC 3 "-//Hibernate.Hibernate Configuration DTD 3.0//EN" 4 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> 5 6 <hibernate-configuration> 7 8 <session-factory> 9 10 <!-- 所使用数据库的驱动名称,不同的数据库有不同的驱动名称 --> 11 <property name="connection.driver_class">net.sourceforge.jtds.jdbc.Driver</property> 12 <!-- 数据库连接串,数据库服务器IP:127.0.0.1,端口号1433,数据库名称blog --> 13 <property name="connection.url">jdbc:jtds:sqlserver://127.0.0.1:1433/blog</property> 14 <property name="connection.username">root</property> 15 <property name="connection.password">123456</property> 16 17 <!-- Hibernate对应SQL Server的方言。不同数据库有不同的方言 --> 18 <property name="dialect">org.hibernate.dialect.SQLServerDialect</property> 19 20 <!-- 可以看到hibernate每次操作数据库的时候,在console中打印对应的sql语句,开发的时候设置为true,部署的时候设置为false --> 21 <property name="show_sql">true</property> 22 23 <mapping resource="hbm/User.hbm.xml" /> 24 25 </session-factory> 26 27 </hibernate-configuration>
4、创建数据表映射文件
这里根据数据库中的表来创建,测试数据库blog中只有T_User一张表,这里只需要新建映射文件User.hbm.xml,这里需要注意一点就是数据库的表名与我们JavaBean实体类名不要一致,否则在发布的时候会报错。hbm文件写起来比较繁琐,可以使用xdoclet工具直接生成。
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-mapping PUBLIC 3 "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 4 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 5 6 <hibernate-mapping> 7 8 <!-- name对应JavaBean类,tabel对应数据库表明 --> 9 <class name="com.mavenssh.data.User" table="T_User"> 10 <!-- 主键映射 --> 11 <id name="userID" column="userID" type="int"> 12 <generator class="increment"></generator> 13 </id> 14 15 <!-- 其他字段映射 --><!-- 如果实体类中属性名和表字段名一致时,column可指定 --> 16 <property name="username" column="username" type="string"></property> 17 <property name="password" column="password" type="string"></property> 18 </class> 19 20 </hibernate-mapping>
三、代码
在src/main/java下新建相应的package,截图如下:
其中util包中是用于存放一些工具类,比如HibernateUtil等。
1 package com.mavenssh.util; 2 3 import org.hibernate.SessionFactory; 4 import org.hibernate.cfg.Configuration; 5 import org.hibernate.classic.Session; 6 7 public class HibernateUtil { 8 9 private static SessionFactory sessionFactory; 10 11 static 12 { 13 try { 14 15 sessionFactory = new Configuration().configure("/hibernate.cfg.xml") 16 .buildSessionFactory(); 17 } 18 catch (Exception e) 19 { 20 System.out.printf(e.getMessage()); 21 e.printStackTrace(); 22 } 23 } 24 25 public static Session openSession() 26 { 27 Session session = sessionFactory.openSession(); 28 29 return session; 30 } 31 32 public static void closeSession(Session session) 33 { 34 if(session!=null) 35 { 36 session.close(); 37 } 38 } 39 }
1 package com.mavenssh.data; 2 3 public class User { 4 5 private int userID; 6 private String username; 7 private String password; 8 9 public int getUserID() { 10 return userID; 11 } 12 public void setUserID(int userID) { 13 this.userID = userID; 14 } 15 public String getUsername() { 16 return username; 17 } 18 public void setUsername(String username) { 19 this.username = username; 20 } 21 public String getPassword() { 22 return password; 23 } 24 public void setPassword(String password) { 25 this.password = password; 26 } 27 }
1 package com.mavenssh.dao; 2 3 import com.mavenssh.data.User; 4 5 public interface UserDAO { 6 7 public User getUser(User user); 8 9 public void saveUser(User user); 10 }
在实例化SessionFactory的时候,因为hibernate.cfg.xml配置文件在resources源文件夹在,因此需要给configure方法指定路径参数"/hibernate.cfg.xml"。
1 package com.mavenssh.dao.impl; 2 3 import org.hibernate.Query; 4 import org.hibernate.Transaction; 5 import org.hibernate.classic.Session; 6 7 import com.mavenssh.dao.UserDAO; 8 import com.mavenssh.data.User; 9 import com.mavenssh.util.HibernateUtil; 10 11 public class UserDAOImpl implements UserDAO { 12 13 public User getUser(User user) { 14 15 Session session = HibernateUtil.openSession(); 16 Transaction tx = session.beginTransaction(); 17 User user2 = null; 18 19 try 20 { 21 Query query = session.createQuery("from User where username=?"); 22 query.setString(0, user.getUsername()); 23 user2 = (User)query.uniqueResult(); 24 tx.commit(); 25 } 26 catch (Exception e) 27 { 28 if(tx!=null) 29 { 30 tx.rollback(); 31 } 32 } 33 finally 34 { 35 HibernateUtil.closeSession(session); 36 } 37 38 return user2; 39 } 40 41 public void saveUser(User user) 42 { 43 Session session = HibernateUtil.openSession(); 44 Transaction tx = session.beginTransaction(); 45 46 try 47 { 48 session.save(user); 49 tx.commit(); 50 } catch (Exception e) { 51 if(tx!=null) 52 { 53 tx.rollback(); 54 } 55 } 56 finally 57 { 58 HibernateUtil.closeSession(session); 59 } 60 } 61 }
UserService是业务层,主要是处理业务逻辑的代码。
1 package com.mavenssh.service; 2 3 import com.mavenssh.data.User; 4 5 public interface UserService { 6 7 public User getUser(User user); 8 9 public void saveUser(User user); 10 }
1 package com.mavenssh.service.impl; 2 3 import com.mavenssh.dao.UserDAO; 4 import com.mavenssh.dao.impl.UserDAOImpl; 5 import com.mavenssh.data.User; 6 import com.mavenssh.service.UserService; 7 8 public class UserServiceImpl implements UserService { 9 10 private UserDAO userDAO = new UserDAOImpl(); 11 12 public UserDAO getUserDAO() { 13 return userDAO; 14 } 15 16 public void setUserDAO(UserDAO userDAO) { 17 this.userDAO = userDAO; 18 } 19 20 public User getUser(User user) { 21 22 return userDAO.getUser(user); 23 } 24 25 public void saveUser(User user) { 26 27 userDAO.saveUser(user); 28 } 29 }
LoginAction类继承了ActionSupport,并重写了其execute方法,这个方法对应LoginAction请求是会被执行,如果是自定义方法,需要在struts.xml的action Element中指定method Attribute。
1 package com.mavenssh.action; 2 3 import java.io.Console; 4 5 import com.mavenssh.data.User; 6 import com.mavenssh.service.UserService; 7 import com.mavenssh.service.impl.UserServiceImpl; 8 import com.opensymphony.xwork2.ActionSupport; 9 10 public class LoginAction extends ActionSupport { 11 12 private User user; 13 private UserService userService = new UserServiceImpl(); 14 15 public User getUser() { 16 return user; 17 } 18 19 public void setUser(User user) { 20 this.user = user; 21 } 22 23 public UserService getUserService() { 24 return userService; 25 } 26 27 public void setUserService(UserService userService) { 28 this.userService = userService; 29 } 30 31 @Override 32 public String execute() throws Exception { 33 34 User user2 = userService.getUser(user); 35 36 if(user2!=null){ 37 38 return SUCCESS; 39 } 40 else { 41 42 return "login"; 43 } 44 } 45 }
四、页面和struts.xml
index.jsp页面代码如下,使用的struts taglib,要使用struts标签库需要在jsp页面顶部添加<%@ taglib uri="/struts-tags" prefix="s" %>。
1 <%@ page language="java" contentType="text/html" pageEncoding="UTF-8" %> 2 <%@ taglib uri="/struts-tags" prefix="s" %> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 5 6 <html> 7 <body style="padding: 200px;margin-left:500px"> 8 9 <s:form id="loginForm" action="loginAction" class="www_zzjs_net" method="post" namespace="/"> 10 <s:textfield name="user.username" label="UserName" required="required" aria-required="true" placeholder="请输入用户名"></s:textfield> 11 <s:textfield name="user.password" label="Password" required="required" aria-required="true" placeholder="请输入密码"></s:textfield> 12 13 <s:submit value="submit" value="登录"></s:submit> 14 <s:reset value="reset" value="取消"></s:reset> 15 </s:form> 16 17 </body> 18 </html>
在src.main/resources下新建struts.xml文件,主要配置JSP页面请求对应的Action类以及处理方法,以及页面跳转逻辑。
1 <?xml version="1.0" encoding="GBK" ?> 2 <!DOCTYPE struts PUBLIC 3 "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" 4 "http://struts.apache.org/dtds/struts-2.0.dtd"> 5 <struts> 6 7 <package name="main" extends="struts-default" namespace="/"> 8 <action name="loginAction" class="com.mavenssh.action.LoginAction"> 9 <result name="success">profile.jsp</result> 10 <result name="login">index.jsp</result> 11 </action> 12 <action name="registerAction" class="com.mavenssh.action.RegisterAction"> 13 <result name="success">profile.jsp</result> 14 </action> 15 </package> 16 17 </struts>
五、项目结构
开启Jetty服务器,在浏览器中输入http://localhost:8080/index.jsp