前言:最近需要用Struts2+Hibernate5做一个实验,在实验过程中遇到了很多问题,尤其是版本问题的搭配,这里我使用Struts2.5.20,Hibernate5.0.7,MySQL5.7的环境搭配。
目录
八、配置Hibernate核心配置文件(路径:src目录下)
先看下我们项目的一个结构:
注意各个文件的存放路径。
一、首先导入依赖JAR包
如图:
我们在导入包的时候会出现同名包的情况,版本不同。如下图
我们看到,有两个都是javassist-xxx-GA.jar的JAR包,那么我们只需要去掉低版本(javassist-3.18.1-GA.jar)的即可,
项目最小核心包如图1。如果不删除有可能出现如这篇博客中的问题:https://blog.csdn.net/qq_34137397/article/details/68546428。
二、在数据库建立表
#创建Hibernate数据库
CREATE DATABASE hibernate CHARACTER SET utf8;
#使用Hibernate数据库
USE hibernate;
#创建Student数据表
CREATE TABLE Student(
s_id INT PRIMARY KEY AUTO_INCREMENT COMMENT '编号',
s_name VARCHAR(20) NOT NULL COMMENT '姓名',
s_sex CHAR(2) NOT NULL COMMENT '性别',
s_phone VARCHAR(20) NOT NULL COMMENT '手机',
s_email VARCHAR(30) NOT NULL COMMENT '邮箱'
)ENGINE=INNODB DEFAULT CHARSET=utf8;
#查看表结构
DESC Student;
#查看表中数据
SELECT * FROM Student;
表结构如下:
三、编写JSP页面(视图层)
1.register.jsp:(说明:这里加入了XML校验文件功能,请读者根据需要取舍)
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>注册页面</title>
<style type="text/css">
.error {
color: red;
text-align: center;
}
ul li{
display: inline;
}
</style>
</head>
<body>
<h3 style="text-align: center; margin-top: 15px;">学生注册页面</h3>
<!-- 更换主题为"simple",form中的label属性失效 -->
<s:form theme="simple" action="register" method="post" >
<table align="center">
<tr>
<td>姓名:</td>
<td><s:textfield name="name" /></td>
</tr>
<tr>
<td colspan="2" class="error"><s:fielderror fieldName="name"/></td>
</tr>
<tr>
<td>性别:</td>
<td><s:radio name="sex" list="#{'0':'男','1':'女'}" value="0" /></td>
</tr>
<tr>
<td>手机:</td>
<td><s:textfield name="phone" /></td>
</tr>
<tr>
<td colspan="2" class="error"><s:fielderror fieldName="phone"/></td>
</tr>
<tr>
<td>邮箱:</td>
<td><s:textfield name="email" /></td>
</tr>
<tr>
<td colspan="2" class="error"><s:fielderror fieldName="email"/></td>
</tr>
<tr style="text-align: center">
<td colspan="2">
<s:submit value="提交"/>
<s:reset value="重置"/>
</td>
</tr>
</table>
</s:form>
</body>
</html>
2.success.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>成功页面</title>
<style type="text/css">
table {
background-color: #F0F8FF;
}
table td{
padding:15px;
}
caption {
margin: 5px auto;
font-weight: bold;
font-size: 18px;
}
</style>
</head>
<body style="padding-top: 15px;">
<center>
欢迎<font color="red" size="5px"><s:property value="name"/></font>,注册成功!
<table border="1">
<caption>个人信息</caption>
<tr>
<th>姓名:</th>
<td><s:property value="name"/></td>
</tr>
<tr>
<th>性别:</th>
<td><s:property value="sex"/></td>
</tr>
<tr>
<th>手机:</th>
<td><s:property value="phone"/></td>
</tr>
<tr>
<th>邮箱:</th>
<td><s:property value="email"/></td>
</tr>
</table>
<s:debug/>
</center>
</body>
</html>
四、配置Struts2核心过滤文件
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>hibernate5_test6</display-name>
<!-- 启动struts2的程序 -->
<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>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
五、创建连接数据库文件(连接层)
1.HibernateSessionFactory.java:
package com.test6.addHibernateFile;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* 读取hibernate.cfg.xml文件
* 创建SessionFactory工厂
* @author lxm
*
*/
public class HibernateSessionFactory {
private SessionFactory sessionFactory;
public HibernateSessionFactory(){
}
public SessionFactory config(){
try{
//1.读取hibernate.cfg.xml文件
Configuration configuration= new Configuration().configure();
//2.创建SessionFactory工厂
return configuration.buildSessionFactory();
}catch(Exception e){
e.getMessage();
return null;
}
}
public Session getSession(){
sessionFactory=config();
//3.创建Session对象
return sessionFactory.openSession();
}
}
2.RegisterInfo.java:
package com.test6.dao;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.test6.addHibernateFile.HibernateSessionFactory;
import com.test6.po.Student;
/**
* 用户注册功能,存储用户数据
* @author lxm
*/
public class RegisterInfo {
private Session session;
private Transaction transaction;
HibernateSessionFactory getSession;
public RegisterInfo(){
}
public String saveInfo(Student info){
getSession=new HibernateSessionFactory();
session=getSession.getSession();
try{
//4.开启事务
transaction=session.beginTransaction();
//5.执行添加操作,向数据表插入数据
session.save(info);
//6.提交事务
transaction.commit();
return "success";
}catch(Exception e){
e.printStackTrace();
return "error";
}finally {
//7.关闭资源
session.close();
}
}
}
六、创建用户实体类(持久层)
1.Student.java:
package com.test6.po;
import java.io.Serializable;
/**
* PO对象(持久化对象)的类,与数据库相对应
* @author lxm
*/
public class Student implements Serializable{
private static final long serialVersionUID = 1L;
private Integer id; //编号
private String name; //姓名
private String sex; //性别
private String phone; //手机
private String email; //邮箱
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Student [id="+ id +" name="+ name +" sex="+ sex
+" phone="+ phone +" email="+ email +"]";
}
}
2.编写Hibernate的核心映射文件Student.hbm.xml(路径:与实体类一致,命名格式:实体类名.hbm.xml):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 映射文件的根元素 -->
<hibernate-mapping>
<!-- name:实体类名,table:表名 -->
<class name="com.test6.po.Student" table="student">
<!-- name:Student类中的属性,column:数据表中字段,type指定类型-->
<id name="id" column="s_id" type="java.lang.Integer">
<!-- 主键生成策略 -->
<generator class="native"/>
</id>
<!-- 其它属性 -->
<!-- type没有指定时,Hibernate会自动识别对应的Java类型 -->
<property name="name" column="s_name" type="java.lang.String"/>
<property name="sex" column="s_sex" type="java.lang.String"/>
<property name="phone" column="s_phone" type="java.lang.String"/>
<property name="email" column="s_email" type="java.lang.String"/>
</class>
</hibernate-mapping>
七、创建实现注册功能Action类(业务层
1.RegisterAction.java:
package com.test6.action;
import java.util.List;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.util.ValueStack;
import com.test6.dao.RegisterInfo;
import com.test6.po.Student;
/**
* 实现用户注册
* @author lxm
*
*/
public class RegisterAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private String name; //姓名
private String sex; //性别
private String phone; //手机
private String email; //邮箱
private String mess=ERROR; //ERROR等同于"error"
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Student userInfo(){
//获取上下文对象
ValueStack valueStack = ActionContext.getContext().getValueStack();
//创建对象并为对象中的属性赋值
Student info=new Student();
info.setName(this.getName());
if(this.getSex().equals("1")) {
info.setSex("女");
}else {
info.setSex("男");
}
info.setPhone(this.getPhone());
info.setEmail(this.getEmail());
valueStack.push(info);
System.out.println(info);
return info;
}
public String execute() throws Exception{
RegisterInfo register=new RegisterInfo();
//将表单参数传入
String ri=register.saveInfo(userInfo());
if(ri.equals("success")){
System.out.println("数据插入成功");
mess=SUCCESS;
}
return mess;
}
}
2.实现注册用户校验功能(路径:与RegisterAction.java一致,命名格式:Action类名-validation.xml),根据需求取舍。
RegisterAction-validation.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
"-//Apache Struts//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<!-- 采用非字段验证 -->
<validators>
<!-- 校验器,开启短路校验 -->
<validator type="requiredstring" short-circuit="true">
<!-- 指定Action属性的名称 -->
<param name="fieldName">name</param>
<param name="trim">true</param>
<!-- 指定返回提示信息 -->
<message>姓名不能为空</message>
</validator>
<validator type="requiredstring" short-circuit="true">
<param name="fieldName">phone</param>
<param name="trim">true</param>
<message>手机不能为空</message>
</validator>
<validator type="requiredstring" short-circuit="true">
<param name="fieldName">email</param>
<param name="trim">true</param>
<message>邮箱不能为空</message>
</validator>
<validator type="stringlength">
<param name="fieldName">name</param>
<param name="minLength">2</param>
<param name="maxLength">10</param>
<message>姓名的长度为2-10位</message>
</validator>
<validator type="stringlength">
<param name="fieldName">phone</param>
<param name="minLength">11</param>
<param name="maxLength">11</param>
<message>手机为11位</message>
</validator>
<validator type="email">
<param name="fieldName">email</param>
<message>邮箱的格式为xxx@xx.com</message>
</validator>
</validators>
八、配置Hibernate核心配置文件(路径:src目录下)
hibernate.cfg.xml:
因为在连接数据库时,会出现:Establishing SSL connection without server's identity verification is not recommend,
所以我们需要在连接数据库的url后面加入&useSSL=true。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- 连接数据库参数 -->
<hibernate-configuration>
<session-factory>
<!-- 1.连接数据库参数 -->
<!-- 数据库驱动 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 连接数据库的URL 格式:jdbc://端口号/数据库名称 -->
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate?useUnicode=true&characterEncoding=utf-8&useSSL=true</property>
<!-- 数据库的用户名 -->
<property name="connection.username">root</property>
<!-- 数据库的密码 -->
<property name="connection.password">root</property>
<!-- 指定数据库的方言 -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 2.hibernate扩展参数 -->
<!-- 控制台显示SQL语句 -->
<property name="hibernate.show_sql">true</property>
<!-- 格式化SQL语句 -->
<property name="hibernate.format_sql">true</property>
<!-- 根据需要自动生成、更新数据表 -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 加入映射文件 -->
<mapping resource="com/test6/po/Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
九、配置Struts2的核心配置文件
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>
<!-- 开启debug标签使用 -->
<constant name="struts.devMode" value="true" />
<package name="default" extends="struts-default">
<action name="register" class="com.test6.action.RegisterAction">
<result name="success">/success.jsp</result>
<result name="input">/register.jsp</result>
<result name="error">/register.jsp</result>
</action>
</package>
</struts>
十、总结
按照上面的步骤就能完成最基本的数据库连接了,数据库的版本不同,可能会出现一些小问题,根据提示解决即可。
在浏览器地址栏输入:http://localhost:8080/hibernate5_test6_4/register.jsp,进行页面访问。如下图:
注册页面效果图:
控制台效果图:
可以看到id=null,因为id对应数据库的s_id,这个字段s_id为自动增长类型,数据库自动填充。
成功页面效果图:
查看数据库数据表数据:
由于本人水平有限,难免有出错之处,欢迎指正!
整理不易,转载请注明出处:https://blog.csdn.net/qq_39123517/article/details/89251252