前几天做项目的时候,项目的服务端用到了SpringMVC+hibernate的框架和工具,由于是带队老师给我搭建的,我还感觉挺好玩的,所以决定用假期时间自己搭建一下试试玩。顺便当成是实习期间的笔记记录一下吧(小公司小项目的实习生,实在小白属性,有大佬在的话还请不要见笑)。目录标题中带* 的内容为可省略内容,为了方便才加上的。
p.s>有关的软件及其版本问题
MySQL “5.6.22”(提前安装好了的,不知道怎么安装的小伙伴请自行百度,我就不赘述了)
Eclipse “2019-06 (4.12.0)””
tomcat “apache-tomcat-9.0.24”
java “1.8.0_161”
其它请参考最后的pom.xml
SpringMVC项目的创建
主要是创建Maven项目,然后配置pom.xml导入相关包,以及在web.xml、springmvc.xml中配置属性。
参考自创建第一个SpringMVC项目(基于Maven管理)博客
创建Maven项目
基本是点点点操作,我就直接放图了,有细节的地方我再补充说明~
注意! :
这里点击“next”之后可能会出现以下的泛红报错,可以先忽略,出现报错是因为缺少”javax.servlet.jar”包
* 解决报错信息
解决方法一:有强迫症的同学可以在pom.xml中添加如下包依赖,可以消除该死的报红波浪线
pom.xml中< dependencies >标签内添加1 2 3 4 5 6 7 8
| ... <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> ...
|
解决方法二:也可以手动添加server、添加相关包消除红色波浪报错信息
选择运行环境后再选择对应的tomcat安装版本,也可以消除报错的红色波浪线问题
添加依赖包
在pom.xml中添加各种依赖包关系之后,使用坤坤键(ctrl)+s保存,项目即可自动下载并添加相关的jar等包文件到项目中,这也是使用Maven管理项目的一大优势,不用自己去找各种包复制添加进去,需要导包的时候把依赖在pom.xml中一添加就完美了
在pom.xml中添加的依赖1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| ... <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>11.0.1</maven.compiler.source> <maven.compiler.target>11.0.1</maven.compiler.target> <spring.version>5.0.2.RELEASE</spring.version> </properties> <dependencies>
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency>
</dependencies> ...
|
* 创建前端index.jsp
新建一个jsp文件,在其中添加一个按钮来跳转辅助测试(也可以不做次步骤,只是为了测试tomcat正常运行与否,若正常则在浏览器中输入进入http://localhost:8080/项目名/ 则可以有具体的显示内容)
index.jsp1 2 3 4 5 6 7 8 9
| <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <html> <title>主页</title> <body> <h2>Hello World!</h2> <a href="/SpringTest/hello">测试</a> </body> </html>
|
在web.xml中配置前端控制器
创建一个新的controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| package com.zy.controller;
import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping;
import com.zy.entity.User;
@Controller public class HelloController {
@RequestMapping("/hello" ) public String sayHello() { System.out.println("后台:测试成功"); return "success"; } }
|
这里返回的是字符串success,接下来通过配置视图解析器让返回的字符串跳转jsp页面。
配置web.xml文件
web.xml1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| ... <web-app> <display-name>My First SpringMVC 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:Springmvc.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> ...
|
接下来新建Springmvc.xml
新建并配置Springmvc.xml
Springmvc.xml1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.zy.*"></context:component-scan>
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"></property> <property name="suffix" value=".jsp"></property> </bean> <mvc:annotation-driven /> </beans>
|
创建返回的view——success.jsp文件
新建views文件夹,在文件夹下新建success.jsp文件,具体位置如下:
success.jsp1 2 3 4 5 6 7 8 9 10 11 12
| <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>跳转成功</title> </head> <body> <h1>跳转成功页面</h1> </body> </html>
|
阶段结果
到这里项目基本的SpringMVC属性就配置完成了,输入http://localhost:8080/SpringTest/ 点击测试超链接即可测试跳转结果,应该是跳转到success.jsp 的内容当中,前端显示“跳转成功”,后端控制台打印出“后台:测试成功”
配置hibernate
配置依赖项
在pom.xml中添加hibernate要用到的依赖项(这里没有配置具体的连接池之类的属性,这个知识点我还有点小问题,准备回头请教一下老师和同事,但是跑demo的话还是不影响的)
在< dependencies >标签内添加如下内容:
hibernate&&jdbc依赖1 2 3 4 5 6 7 8 9 10 11 12 13 14
| ...
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.1.0.Final</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.41</version> </dependency> ...
|
配置hibernate.cfg.xml、
在下图对应的位置新建一个xml文件用以配置hibernate
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "src/resource/schema/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url"> jdbc:mysql://127.0.0.1:3306/mydb?characterEncoding=utf-8 </property> <property name="connection.username">你的MySQL用户</property> <property name="connection.password">你的MySQL用户密码</property>
<property name="hibernate.dialect"> org.hibernate.dialect.MySQL5InnoDBDialect </property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class"> org.hibernate.cache.internal.NoCacheProvider </property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping class="com.zy.entity.User"></mapping> </session-factory>
</hibernate-configuration>
|
创建持久化实体类
创建entity文件夹,并在文件夹下添加新创建的User持久化实体类
User.java1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| package com.zy.entity;
import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity @Table(name="my_users") public class User { private Integer userId; private String userPhoneNum; private String userName; private String passWord;
@Id @GeneratedValue(generator="increment") @GenericGenerator(name="increment", strategy = "increment") @Column(name = "user_id") public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } @Column(name = "user_phoneNum") public String getUserPhoneNum() { return userPhoneNum; } public void setUserPhoneNum(String userPhoneNum) { this.userPhoneNum = userPhoneNum; }
@Column(name = "username") public String getUserName() { return userName; }
public void setUserName(String userName) { this.userName = userName; }
@Column(name = "password") public String getPassWord() { return passWord; }
public void setPassWord(String passWord) { this.passWord = passWord; } }
|
hibernate常用注解
hibernate常用配置文件说明
测试:添加数据
在之前的controller中sayHello()方法中添加如下代码:
HelloController.java-->sayHello()1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| ... User user = new User(); user.setUserName("xxx"); user.setPassWord("123456"); user.setUserPhoneNum("185*****207"); Configuration config = new Configuration().configure(); SessionFactory sessionFactory = config.buildSessionFactory(); Session session = sessionFactory.openSession(); Transaction tran = session.beginTransaction(); try { session.saveOrUpdate(user); tran.commit(); System.out.println("实例化成功"); } catch (Exception e) { tran.rollback(); e.printStackTrace(); } finally { session.close(); sessionFactory.close(); } ... System.out.println("后台:测试成功"); return "success";
|
测试结果
代码展示
由于之前的代码是粘的部分,所以在这 重新贴一遍pom.xml、web.xml和HelloController.java 的完整代码
pom.xml
pom.xml1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| <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.zy</groupId> <artifactId>SpringTest</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>SpringTest Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>11.0.1</maven.compiler.source> <maven.compiler.target>11.0.1</maven.compiler.target> <spring.version>5.0.2.RELEASE</spring.version> </properties>
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.1.0.Final</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.41</version> </dependency> </dependencies> <build> <finalName>SpringTest</finalName> </build> </project>
|
web.xml
web.xml1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app> <display-name>My First SpringMVC 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:Springmvc.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>
|
HelloController.java
HelloController.java1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| package com.zy.controller;
import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping;
import com.zy.entity.User;
@Controller public class HelloController {
@RequestMapping("/hello" ) public String sayHello() { User user = new User(); user.setUserName("xxx"); user.setPassWord("123456"); user.setUserPhoneNum("185*****207"); Configuration config = new Configuration().configure(); SessionFactory sessionFactory = config.buildSessionFactory(); Session session = sessionFactory.openSession(); Transaction tran = session.beginTransaction(); try { session.saveOrUpdate(user); tran.commit(); System.out.println("实例化成功"); } catch (Exception e) { tran.rollback(); e.printStackTrace(); } finally { session.close(); sessionFactory.close(); } System.out.println("后台:测试成功"); return "success"; } }
|
测试结果
同阶段测试结果,只是点击跳转成功后,后端控制台会多打印出一些东西(跳过带* 内容的大兄弟,最后测试的时候直接在地址栏填写并进入 http://localhost:8080/SpringTest/hello 测试即可,红叉那儿跳过的话会在pom.xml添加依赖后报错消失)
最后特别感谢参考的博客内容
weixin_44140423的 创建第一个SpringMVC项目(基于Maven管理);
skytering的eclipse+maven搭建hibernate5测试环境;