一、啥是SSH(Spring+Struts+Hibernate)
在这里就不多解释,直接百度了一下SSH的解释,此篇主要结合SSH来完成一个简单的CRUD项目。
百度一下:SSH在J2EE项目中表示了3种框架,即 Spring + Struts +Hibernate。 Struts对Model,View和Controller都提供了对应的组件。Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架,它由Rod Johnson创建。它是为了解决企业应用开发的复杂性而创建的。Spring使用基本的JavaBean来完成以前只可能由EJB完成的事情。 Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,可以应用在任何使用JDBC的场合,可以在Servlet/JSP的Web应用中使用,也可以在应用EJB的J2EE架构中取代CMP,完成数据持久化的重任。
二、开始我们的项目
项目结构
2.1、pom.xml
<?xml version="1.0" encoding="UTF-8"?> <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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.hsl</groupId> <artifactId>springStrutsHibernate02</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <!--spring相关依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.0.2.RELEASE</version> </dependency> <!--struts2相关依赖--> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>2.5.14.1</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-spring-plugin</artifactId> <version>2.5.14.1</version> </dependency> <!--hibernate相关依赖--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.2.12.Final</version> </dependency> <!--mysql依赖--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.8-dmr</version> </dependency> <!--实现DataSource的接口--> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.2</version> </dependency> <!--servlet依赖--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.2</version> <configuration> <warSourceDirectory>web</warSourceDirectory> </configuration> </plugin> </plugins> </build> </project>
2.2、web.xml
如果spring的配置文件名为applicationContext.xml则可以省略web.xml文件中的<context-param>
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml</param-value> </context-param> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
2.3、Teacher.java
package entity; public class Teacher { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
2.4、TeacherDao.java
package dao; import entity.Teacher; import java.util.List; public interface TeacherDao { //添加 void addTeacher(Teacher teacher); //查询全部 List<Teacher> queryAll(); //根据编号删除 void delete(int id); //根据编号查询 Teacher queryById(int id); //修改 void update(Teacher teacher); }
2.5、TeacherDaoImpl.java
package dao; import entity.Teacher; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import java.util.List; public class TeacherDaoImpl implements TeacherDao { private SessionFactory sessionFactory; public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } //增加数据 public void addTeacher(Teacher teacher) { Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); session.save(teacher); transaction.commit(); session.close(); } //查询全部数据 public List<Teacher> queryAll() { Session session = sessionFactory.openSession(); List<Teacher> teachers = session.createQuery("from Teacher ").list(); session.close(); return teachers; } //根据编号删除 public void delete(int id) { Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); session.delete(session.get(Teacher.class,id)); transaction.commit(); session.close(); } //根据编号查询 public Teacher queryById(int id) { Session session = sessionFactory.openSession(); Teacher teacher = session.get(Teacher.class,id); session.close(); return teacher; } //修改 public void update(Teacher teacher) { Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); session.update(teacher); transaction.commit(); session.close(); } }
2.6、TeacherService.java
package service; import dao.TeacherDao; import entity.Teacher; import java.util.List; public class TeacherService { private TeacherDao teacherDao; public TeacherDao getTeacherDao() { return teacherDao; } public void setTeacherDao(TeacherDao teacherDao) { this.teacherDao = teacherDao; } public void addTeacher(Teacher teacher){ teacherDao.addTeacher(teacher); } public List<Teacher> queryAll(){ return teacherDao.queryAll(); } public void delete(int id){ teacherDao.delete(id); } public Teacher queryById(int id){ return teacherDao.queryById(id); } public void update(Teacher teacher){ teacherDao.update(teacher); } }
2.7、TeacherController.java
package controller; import entity.Teacher; import org.apache.struts2.ServletActionContext; import service.TeacherService; import javax.servlet.http.HttpServletRequest; import java.util.List; public class TeacherController { private TeacherService teacherService; public void setTeacherService(TeacherService teacherService) { this.teacherService = teacherService; } private String name; private int id; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } private Teacher teacher; public void setTeacher(Teacher teacher) { this.teacher = teacher; } public String add(){ teacher.setName(name); teacherService.addTeacher(teacher); return "success"; } public String queryAll(){ List<Teacher> teachers = teacherService.queryAll(); HttpServletRequest httpServletRequest = ServletActionContext.getRequest(); httpServletRequest.setAttribute("teachers",teachers); return "success"; } public String delete(){ teacherService.delete(id); return "success"; } public String queryById(){ Teacher teacher = teacherService.queryById(id); HttpServletRequest httpServletRequest = ServletActionContext.getRequest(); httpServletRequest.setAttribute("teacher",teacher); return "success"; } public String update(){ teacher.setId(id); teacher.setName(name); teacherService.update(teacher); return "success"; } }
2.8、spring.xml
其中<props>中的hibernate.dialect得注意放置的位置,理应上是需要放第一个<prop>中,否则可能会出现找不到sessionFactory的问题。
<?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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!--<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"-->也可以是这个 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" p:driverClass="com.mysql.jdbc.Driver" p:jdbcUrl="jdbc:mysql://localhost:3306/student?serverTimezone=UTC" p:user="root" p:password="123456" /> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop> //注意位置!!多次入坑 <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> </props> </property> <property name="mappingLocations"> <list> <value>classpath:Teacher.hbm.xml</value> </list> </property> </bean> <bean id="teacherDao" class="dao.TeacherDaoImpl"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <bean id="teacherService" class="service.TeacherService"> <property name="teacherDao" ref="teacherDao"/> </bean> <bean id="teacher" class="entity.Teacher"/> <bean id="teacherController" class="controller.TeacherController" scope="prototype"> <property name="teacher" ref="teacher"/> <property name="teacherService" ref="teacherService"/> </bean> </beans>
2.9、struts.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd"> <struts> <package name="ssh" extends="struts-default"> <action name="add" class="teacherController" method="add"> <result name="success" type="redirectAction">queryAll</result> </action> <action name="queryAll" class="teacherController" method="queryAll"> <result name="success" type="dispatcher">index.jsp</result> </action> <action name="delete" class="teacherController" method="delete"> <result name="success" type="redirectAction">queryAll</result> </action> <action name="queryById" class="teacherController" method="queryById"> <result name="success" type="dispatcher">update.jsp</result> </action> <action name="update" class="teacherController" method="update"> <result name="success" type="redirectAction">queryAll</result> </action> </package> </struts>
2.10、index.jsp
<%@ page import="entity.Teacher" %> <%@ page import="java.util.List" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>老师信息</title> </head> <body> <table border="1"> <tr> <th>编号</th> <th>姓名</th> <th>操作</th> </tr> <% for(Teacher teacher:(List<Teacher>) request.getAttribute("teachers")){ %> <tr> <td><%= teacher.getId()%></td> <td><%= teacher.getName()%></td> <td> <a href="delete.action?id=<%= teacher.getId()%>">删除</a> | <a href="queryById.action?id=<%= teacher.getId()%>">修改</a> </td> </tr> <% } %> </table> <a href="add.jsp">添加</a> </body> </html>
2.11、add.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>添加</title> </head> <body> <h1>添加</h1> <form action="add.action" method="post"> <p> <label>姓名:</label> <input type="text" name="name" id="name"/> </p> <p> <input type="submit" value="添加"> </p> </form> </body> </html>
2.12、update.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>修改</title> </head> <body> <h1>修改</h1> <form action="update.action" method="post"> <% Teacher teacher = (Teacher) request.getAttribute("teacher"); %> <p> <label>姓名:</label> <input type="text" name="name" value="<%= teacher.getName()%>" id="name"/> </p> <p> <input type="hidden" name="id" value="<%= teacher.getId()%>" id="id"/> <input type="submit" value="修改"> </p> </form> </body> </html>
运行结果:
刚刚入门sprig,如果错误请评论指正!!