本文将为大家介绍如何在一个Web应用中使用Hibernate、Spring和Struts三个框架,并扩展Struts框架,以实现一个完整的MVC架构。下面我们将一步步讲解如何搭建这个Web应用。
环境准备
在开始之前,请确保已经安装了以下环境:
- JDK 1.8
- Tomcat 8.5
- MySQL 5.x
创建工程
- 在Eclipse中创建一个动态Web工程,命名为"spring-struts-hibernate"。
- 将hibernate-validator、mysql-connector-java、spring和struts2的jar包放到工程的WEB-INF/lib目录下。
- 在WEB-INF目录下创建一个classes目录,以便于存放Java类。
- 在WEB-INF目录下创建一个lib目录,以便于存放项目依赖的jar包。
- 创建以下文件:
-src
--main
---java
----com.example.dao
-----UserDao.java
----com.example.entity
-----User.java
---resources
----spring
-----applicationContext.xml
---webapp
----WEB-INF
-----web.xml
创建数据表
在MySQL中创建以下表:
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(20) NOT NULL,
`password` varchar(20) NOT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
编写Java类
- 创建用户实体类User.java
package com.example.entity;
public class User {
private int id;
private String username;
private String password;
private int age;
//getter和setter方法...
}
- 创建用户DAO类UserDao.java,用于操作用户实体类
package com.example.dao;
import java.util.List;
import com.example.entity.User;
public interface UserDao {
public void save(User user);
public void update(User user);
public void delete(int id);
public User findById(int id);
public List<User> findAll();
}
- 在DAO类中创建Hibernate实现
package com.example.dao.impl;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.example.dao.UserDao;
import com.example.entity.User;
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private SessionFactory sessionFactory;
private Session getSession(){
return sessionFactory.getCurrentSession();
}
public void save(User user) {
this.getSession().save(user);
}
public void update(User user) {
this.getSession().update(user);
}
public void delete(int id) {
User user = findById(id);
if(user != null){
this.getSession().delete(user);
}
}
public User findById(int id) {
return (User) this.getSession().get(User.class, id);
}
@SuppressWarnings("unchecked")
public List<User> findAll() {
String hql = "from User";
return this.getSession().createQuery(hql).list();
}
}
配置Spring
- 在classpath中创建Spring配置文件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:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/demo"></property>
<property name="username" value="root"></property>
<property name="password" value=""></property>
</bean>
<!-- 配置SessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mappingResources">
<list>
<value>com/example/entity/User.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- 配置事务管理器 -->
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 配置事务注解支持 -->
<context:annotation-config></context:annotation-config>
<tx:annotation-driven transaction-manager="txManager"></tx:annotation-driven>
<!-- 配置DAO层 -->
<bean id="userDao" class="com.example.dao.impl.UserDaoImpl"></bean>
</beans>
- 在Web.xml配置文件中添加以下内容,以便于加载Spring:
<!-- spring配置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/spring/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
配置Struts
- 在classpath中创建Struts配置文件struts.xml,并添加以下内容:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="true" />
<constant name="struts.devMode" value="true" />
<constant name="struts.action.excludePattern" value="/favicon.ico" />
<package name="default" extends="struts-default">
<action name="user" class="com.example.action.UserAction">
<result name="list">/WEB-INF/jsp/user/list.jsp</result>
<result name="input">/WEB-INF/jsp/user/input.jsp</result>
<result name="add">/WEB-INF/jsp/user/list.jsp</result>
<result name="edit">/WEB-INF/jsp/user/input.jsp</result>
<result name="delete">/WEB-INF/jsp/user/list.jsp</result>
</action>
</package>
</struts>
- 创建用户Action类UserAction.java,用于处理用户操作
package com.example.action;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.example.dao.UserDao;
import com.example.entity.User;
import com.opensymphony.xwork2.ActionSupport;
public class UserAction extends ActionSupport {
private static final long serialVersionUID = 1L;
@Autowired
private UserDao userDao;
private List<User> list;
private User user;
private int id;
//getter和setter方法...
public String list(){
list = userDao.findAll();
return "list";
}
public String add(){
userDao.save(user);
return "add";
}
public String edit(){
user = userDao.findById(id);
return "edit";
}
public String update(){
userDao.update(user);
return "add";
}
public String delete(){
userDao.delete(id);
return "delete";
}
}
编写JSP页面
- 在Webapp目录下创建以下文件:
-webapp
--WEB-INF
---jsp
----user
-----list.jsp
-----input.jsp
- 编写用户列表页list.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>用户管理</title>
</head>
<body>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>用户名</th>
<th>密码</th>
<th>年龄</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<s:forEach var="user" items="list">
<tr>
<td><s:property value="id"/></td>
<td><s:property value="username"/></td>
<td><s:property value="password"/></td>
<td><s:property value="age"/></td>
<td>
<s:a href="user_edit.action?id=${user.id}">编辑</s:a>
<s:a href="user_delete.action?id=${user.id}">删除</s:a>
</td>
</tr>
</s:forEach>
</tbody>
</table>
<p><a href="user_input.action">添加用户</a></p>
</body>
</html>
- 编写用户操作页面input.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>用户信息</title>
</head>
<body>
<s:form action="user_${action}.action">
<s:hidden name="user.id" value="%{id}" />
<s:textfield name="user.username" label="用户名" value="%{user.username}" />
<s:textfield name="user.password" label="密码" value="%{user.password}" />
<s:textfield name="user.age" label="年龄" value="%{user.age}" />
<s:submit value="提交" />
</s:form>
</body>
</html>
运行
- 启动Tomcat服务。
- 在浏览器中输入"http://localhost:8080/spring-struts-hibernate/user_list.action",即可查看用户列表页。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Hibernate+Spring+Struts扩展Struts - Python技术站