目录
- 1. pom依赖
- 2. web.xml
- 3. spring核心配置文件
- 3.1 jdbc配置信息
- 3.2 sping 配置文件
- 4. 实体映射
- 5. 项目结构
- 5.1 curd
- 5.2 页面
- 6. 测试
1. spring版本 5.1.5 RELEASE
2. hibernate版本 5.3.9.Final
3. 数据源使用c3p0
项目使用eclipse2017 + maven构建, 完成学生的新增,查询功能。学生表是根据hibernate对实体类进行映射生成的。
1. pom依赖
<?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>cn.bitqian</groupId><artifactId>springmvc02</artifactId><version>0.0.1-SNAPSHOT</version><packaging>war</packaging><name>springmvc02 Maven Webapp</name><!-- FIXME change it to the project's website --><url>http://www.example.com</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.compiler.source>1.8</maven.compiler.source><maven.compiler.target>1.8</maven.compiler.target></properties><dependencies><!-- servlet --><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>4.0.1</version></dependency> <!-- mvc --><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.1.5.RELEASE</version></dependency><!-- 整合包 --><!-- https://mvnrepository.com/artifact/org.springframework/spring-orm --><dependency><groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId><version>5.1.6.RELEASE</version></dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-orm --><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.1.5.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>5.1.5.RELEASE</version></dependency> <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver --><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.9.2</version><scope>runtime</scope></dependency><!-- https://mvnrepository.com/artifact/com.mchange/c3p0 --><dependency><groupId>com.mchange</groupId><artifactId>c3p0</artifactId><version>0.9.5.2</version></dependency><!-- hibernate --><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-core</artifactId><version>5.3.9.Final</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency><!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.20</version></dependency><!-- junit --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.11</version><scope>test</scope></dependency> </dependencies><build><finalName>springmvc02</finalName><pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --><plugins><plugin><artifactId>maven-clean-plugin</artifactId><version>3.1.0</version></plugin><!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --><plugin><artifactId>maven-resources-plugin</artifactId><version>3.0.2</version></plugin><plugin><artifactId>maven-compiler-plugin</artifactId><version>3.8.0</version></plugin><plugin><artifactId>maven-surefire-plugin</artifactId><version>2.22.1</version></plugin><plugin><artifactId>maven-war-plugin</artifactId><version>3.2.2</version></plugin><plugin><artifactId>maven-install-plugin</artifactId><version>2.5.2</version></plugin><plugin><artifactId>maven-deploy-plugin</artifactId><version>2.8.2</version></plugin></plugins></pluginManagement></build>
</project>
2. web.xml
注意xml的头文件,版本,2.3的头文件有坑low,这里用的是3.0版本。
ioc容器加载。mvc核心控制器的创建。
<?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>Archetype Created Web Application</display-name><!-- 启动项目时加载容器 --><servlet><servlet-name>dispatcherServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-mvc.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>dispatcherServlet</servlet-name><url-pattern>/</url-pattern></servlet-mapping></web-app>
3. spring核心配置文件
3.1 jdbc配置信息
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/ssh_study?serverTimezone=GMT
jdbc.username=root
password=123456
3.2 sping 配置文件
hibernate 使用了注解的方式,没有配置映射文件。
<?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:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"><!-- 开启mvc注解驱动 --><mvc:annotation-driven /><context:component-scan base-package="cn.bitqian.**" /><!-- 加载jdbc配置文件 --><context:property-placeholder location="classpath:jdbc.properties"/><!-- c3p0数据源 --><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="${driver}"></property><property name="jdbcUrl" value="${url}"></property><property name="user" value="${jdbc.username}"></property><property name="password" value="${password}"></property></bean><!-- session 工厂 --><bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"><property name="dataSource" ref="dataSource"></property><!-- hibernate 相关配置 --><property name="hibernateProperties"><props><prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop><!-- 根据实体类反转表 --><prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.show_sql">true</prop><prop key="hibernate.format_sql">true</prop></props></property><!-- hibernate映射文件 注解扫描 --><property name="packagesToScan" value="cn/bitqian/entity"></property></bean><!-- hibernate模板来操作数据库 --><bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate"><property name="sessionFactory" ref="sessionFactory"></property></bean><!-- 事务 --><bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory"></property></bean><!-- xml事务配置 --><tx:advice id="advice" transaction-manager="transactionManager"><tx:attributes><!-- 对下面的符合规则方法进行事务控制 --><tx:method name="save*" propagation="REQUIRED"/><tx:method name="add*" propagation="REQUIRED"/><tx:method name="insert*" propagation="REQUIRED"/><tx:method name="update*" propagation="REQUIRED"/><tx:method name="delete*" propagation="REQUIRED"/><!-- 只读 --><tx:method name="*" read-only="true" propagation="SUPPORTS"/></tx:attributes></tx:advice><aop:config><!-- 切点 --><aop:pointcut expression="execution(* cn.bitqian.service.impl.*.*(..))" id="pointcut"/><!-- 事务顾问 --><aop:advisor advice-ref="advice" pointcut-ref="pointcut"/></aop:config><!-- 开启事务注解驱动 --><tx:annotation-driven transaction-manager="transactionManager"/></beans>
4. 实体映射
package cn.bitqian.entity;import java.io.Serializable;
import java.util.Date;import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;import org.springframework.format.annotation.DateTimeFormat;/*** * @author echo lovely* @time 2020/11/4**/
@Entity(name="StudentInfo")
@Table(name="student_info")
public class StudentInfo implements Serializable {private static final long serialVersionUID = -5075710692395281523L;@Id@GeneratedValue(strategy=GenerationType.AUTO) // 主键自增// @Column(name="stu_id")private Integer stuId;@Column(name="stu_name")// 列名private String stuName;@Column(name="stu_gender")private Integer stuGender;@Column(name="stu_birth")@DateTimeFormat(pattern="yyyy-MM-dd") // mvc将字符串转换日期private Date stuBirth;// 此字段会被忽悠,不会被反转@Transientprivate String abc;public StudentInfo() {}public Integer getStuId() {return stuId;}public void setStuId(Integer stuId) {this.stuId = stuId;}public String getStuName() {return stuName;}public void setStuName(String stuName) {this.stuName = stuName;}public Integer getStuGender() {return stuGender;}public void setStuGender(Integer stuGender) {this.stuGender = stuGender;}public Date getStuBirth() {return stuBirth;}public void setStuBirth(Date stuBirth) {this.stuBirth = stuBirth;}}
5. 项目结构
5.1 curd
dao
package cn.bitqian.dao.impl;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;import cn.bitqian.dao.StudentInfoDao;
import cn.bitqian.entity.StudentInfo;@Repository
public class StudentInfoDaoImpl implements StudentInfoDao {@Autowiredprivate HibernateTemplate ht;@Overridepublic List<StudentInfo> queryAll() {// 查询所有// return (List<StudentInfo>) ht.find("from StudentInfo");return ht.loadAll(StudentInfo.class);}@Overridepublic void add(StudentInfo stu) {// 新增ht.save(stu);}}
service(省略),没有业务
package cn.bitqian.service.impl;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;import cn.bitqian.dao.StudentInfoDao;
import cn.bitqian.entity.StudentInfo;
import cn.bitqian.service.StudentInfoService;@Service
public class StudentInfoServiceImpl implements StudentInfoService {@Autowiredprivate StudentInfoDao stuDao;@Overridepublic List<StudentInfo> queryAll() throws Exception {List<StudentInfo> list = null;try {list = stuDao.queryAll();} catch (Exception e) {// 捕捉到异常并抛出e.printStackTrace();throw new Exception(e);}return list;}@Overridepublic void add(StudentInfo stu) throws Exception {try {stuDao.add(stu);} catch (Exception e) {e.printStackTrace();throw new Exception(e);}}/*** 测试为事务注解*/@Transactional@Overridepublic void testAdd1(StudentInfo stu) {stuDao.add(stu);}}
controller
package cn.bitqian.controller;import javax.annotation.Resource;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;import cn.bitqian.entity.StudentInfo;
import cn.bitqian.service.StudentInfoService;@Controller
@RequestMapping("/stu")
public class StudentInfoController {@Resource()private StudentInfoService stuInfoService;@GetMapping("/list")public ModelAndView queryAllStu() {ModelAndView mv = new ModelAndView();try {// 带上查询的数据mv.addObject("stuList", stuInfoService.queryAll());} catch (Exception e) {e.printStackTrace();mv.addObject("msg", "出错拉");}mv.setViewName("/list.jsp");return mv;}@PostMapping("/add")public ModelAndView saveStu(StudentInfo stuInfo) {stuInfoService.testAdd1(stuInfo);// 查询一遍return this.queryAllStu();}}
5.2 页面
- 新增
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>新增学生</title>
</head>
<body><form action="stu/add" method="post"><input type="text" name="stuName"/> <br/><input type="radio" name="stuGender" value="0"/>男<input type="radio" name="stuGender" value="1"/>女 <br/><input type="date" name="stuBirth"/> <br/><input type="submit" value="add"/> <br/></form></body>
</html>
- 查询
坑:jstl,识别不了。。可能我导入的servlet(4.0)版本太高,而头文件的版本当时是2.3… 把头文件改为3.0就行了
无法在web.xml或使用此应用程序部署的jar文件中解析绝对uri:[http://java.sun.com
<%@ page language="java" isELIgnored="false" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>学生查询</title>
</head>
<body><table><tr><td>id</td><td>name</td><td>gender</td><td>birth</td></tr><c:forEach items="${stuList}" var="stu"><tr><td>${stu.stuId}</td><td>${stu.stuName}</td><td>${stu.stuGender == 0 ? "男" : "女"}</td><td>${stu.stuBirth} </td></tr></c:forEach></table></body>
</html>
6. 测试