写在前面
本文采用ecplipse搭建了一个简单的SSH项目,并提供了示例项目,适合初学者入门。文章可能还有很多不足,请大家谅解,欢迎大佬提意见。
本文使用到的东西
- struts 2.5.22
- spring 5.2.3
- hibernate 5.4.10
- java 12.0.2
- eclipse 2019-11
- win10
文章目录
1.前期准备
1.1 导入jar包方式
(1)struts下载
struts需要的包:
(2)spring下载
spring需要的包:
(3)hibernate下载
hibernate官网
hibernate需要的包:
如果因为某些原因无法下载的话,可以从我百度网盘下载:
链接:https://pan.baidu.com/s/18ABeLSRXFT8wzo0rLR792A
提取码:1tn2
除了基础的SSH框架,还需要连接数据库的驱动,大家自备,我这里以MySQL数据库为例。
1.2 Maven方式
在pom.xml文件中添加如下内容,本文采用直接导包的方式搭建ssh架构
<!-- Struts -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.5.13</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-spring-plugin</artifactId>
<version>2.5.13</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.9.RELEASE</version>
</dependency>
<!-- hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.5.Final</version>
</dependency>
<!-- 数据库连接池jar -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1.1</version>
</dependency>
2.搭建
2.1 创建项目
使用eclipse创建一个Dynamic webproject动态web项目,将以上需要的包导入项目的“lib
”目录。
2.2 创建web.xml文件
在/WebContent/WEB-INF/
目录下新建一个web.xml
文件,并配置struts的过滤器和spring的监听器。
<?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">
<!-- 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>
<!-- spring的监听器配置开始 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
2.3 创建项目包结构
创建最基础的包结构
2.4 创建实体类
- 创建数据库
user
表结构如下
- 添加一条数据,等一下用来查询
- 在
com.nineya.entity
包下创建user表对应的实体类(User
)和映射文件(UserMapper.xml
)。
实体类代码如下:
package com.nineya.entity;
public class User {
private long uid;
private String name;
private String sex;
private String phone;
private String mail;
public User() {
super();
}
public User(long uid, String name, String sex, String phone, String mail) {
super();
this.uid = uid;
this.name = name;
this.sex = sex;
this.phone = phone;
this.mail = mail;
}
public long getUid() {
return uid;
}
public void setUid(long uid) {
this.uid = uid;
}
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 getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
@Override
public String toString() {
return "User [uid=" + uid + ", name=" + name + ", sex=" + sex + ", phone=" + phone + ", mail=" + mail + "]";
}
}
UserMapper.xml映射文件代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.nineya.entity.User" table="user">
<!-- 用户id -->
<id name="uid" column="uid">
<generator class="native"></generator>
</id>
<!-- 姓名 -->
<property name="name" column="name"></property>
<!-- 性别 -->
<property name="sex" column="sex"></property>
<!-- 手机号 -->
<property name="phone" column="phone"></property>
<!-- 邮箱 -->
<property name="mail" column="mail"></property>
</class>
</hibernate-mapping>
2.5 创建Dao接口和实现类
在com.nineya.dao
包里创建接口(UserDao
),在com.nineya.dao.impl
包里创建UserDao
接口的实现类(UserDaoImpl
)。
UserDao接口内容:
package com.nineya.dao;
import java.util.List;
import com.nineya.entity.User;
//Dao层接口
public interface UserDao {
//取得用户列表
public List<User> getUsers();
}
UserDaoImpl类内容:
package com.nineya.dao.impl;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import com.nineya.dao.UserDao;
import com.nineya.entity.User;
public class UserDaoImpl implements UserDao {
//只需要声明一个对象,不需要关注这个实例的创建,通过Spring注入
private SessionFactory sessionFactory;
//set方法用于spring注入,这是第一种注入方法
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public List<User> getUsers() {
/**
* 按常规的方法创建sessionFactory
Configuration cfg = new Configuration().configure("hibernate-config.xml");
sessionFactory = cfg.buildSessionFactory();
*/
//获取session
Session session = sessionFactory.openSession();
//对应的实体类名称,非数据库表名
Query<User> query = session.createQuery("from User");
//取得数据
List<User> list = query.getResultList();
//输出内容
System.out.println(list.toString());
//关闭session
session.close();
//关闭sessionFactory,关闭之后就无法再获取连接了
//sessionFactory.close();
//返回list集合
return list;
}
}
2.6 创建Service接口和实现类
在com.nineya.service
包下创建UserService
(接口),com.nineya.service.impl
包下创建UserService
接口的实现类(UserServiceImpl
)。
UserService.java:
package com.nineya.service;
import java.util.List;
import com.nineya.entity.User;
//服务层接口
public interface UserService {
public List<User> getUsers();
}
UserServiceImpl.java
package com.nineya.service.impl;
import java.util.List;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import com.nineya.dao.UserDao;
import com.nineya.dao.impl.UserDaoImpl;
import com.nineya.entity.User;
import com.nineya.service.UserService;
//创建bean,指定id为UserServiceImpl
@Component
public class UserServiceImpl implements UserService {
//bean工厂
private static BeanFactory fac;
private static UserDao dao;
static {
fac = new ClassPathXmlApplicationContext("applicationContext.xml");
//注入UserDaoImpl,第二种注入方式
dao = fac.getBean(UserDaoImpl.class);
}
@Override
public List<User> getUsers() {
/**
* 在这里编写业务逻辑的代码
* 交给dao来操作数据库
*
*/
List<User> users = dao.getUsers();
return users;
}
}
2.6 创建IndexAction类
在com.nineya.action
包下创建IndexAction类。
package com.nineya.action;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.nineya.entity.User;
import com.nineya.service.UserService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
//创建action类继承ActionSupport类
//通过注解创建一个id为IndexAction的bean
@Component("IndexAction")
public class IndexAction extends ActionSupport {
private static final long serialVersionUID = 1L;
//通过注解注入Bean,第三种注入方式
@Autowired
private UserService service;
//编写execute()方法
public String execute() {
//取得用户列表
List<User> users = service.getUsers();
//将查询出来的用户数量打印出来
System.out.println("用户人数:"+users.size());
//获取Context上下文对象
ActionContext ac = ActionContext.getContext();
//将users集合添加到上下文对象里
ac.put("users", users);
//返回一个字符串
return "index";
}
public String size(List<User> users) {
return "用户人数:"+ users.size() +"人!";
}
}
2.7 创建配置文件
在/src/目录下新建编写struts配置文件(struts.xml)、spring配置文件(applicationContext.xml)、hibernate配置文件(hibernate-config.xml)。
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">
<!-- 注意上面的头版本,复制showcase.war\WEB-INF\src\java\struts.xml -->
<struts>
<!-- 运行时使用Spring来创建对象 -->
<constant name="struts.objectFactory" value="spring" />
<!-- namespace表示的是请求所属的路径范围,指定所属目录需要在最后面加“/*” -->
<package name="default" namespace="/" extends="struts-default">
<!-- name就是url最后的文件名,class是action的bean的id -->
<action name="index" class="IndexAction">
<!-- name就是action返回的字符串 -->
<result name="index">/WEB-INF/index.jsp</result>
</action>
</package>
</struts>
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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 配置spring注解的扫描路径 -->
<context:component-scan base-package="com.nineya" />
<!-- 所有需要的类都由spring去实例化和管理 -->
<bean id="UserDaoImpl" class="com.nineya.dao.impl.UserDaoImpl" scope="prototype">
<!-- 把sessionFactory 注入给IndexDao -->
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 添加sessionFactory bane ,该类是Spring提供的 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" scope="prototype">
<!-- 注入Hibernate 配置文件路径,前面要加上 classpath:-->
<property name="configLocation" value="classpath:hibernate-config.xml"/>
</bean>
</beans>
hibernate-config.xml:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 数据库连接配置 -->
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://192.168.138.39:3306/ssh?useSSL=false&serverTimezone=CST&allowMultiQueries=true</property>
<property name="connection.username">root</property>
<property name="connection.password">361654768</property>
<!-- dialect翻译为具体sql语言,Hibernate根据选择的数据库作调整,生成不同的SQL语句等 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 设置数据库连接池 -->
<property name="connection.pool_size">5</property>
<!-- 显示SQL -->
<property name="show_sql">true</property>
<!-- 格式化SQL -->
<property name="format_sql">true</property>
<!-- 根据schema更新数据表的工具 -->
<property name="hbm2ddl.auto">update</property>
<!-- User表的映射配置文件 -->
<mapping resource="com/nineya/entity/UserMapper.xml"/>
</session-factory>
</hibernate-configuration>
2.8 创建JSP文件
在/WebContent/WEB-INF/
目录下创建index.jsp
文件,内容如下:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ssh首页</title>
</head>
<body>
<table border="1">
<tr>
<td>ID</td>
<td>姓名</td>
<td>性别</td>
<td>手机</td>
<td>邮箱</td>
</tr>
<!-- 使用struts2标签库中的iterator将所有数据遍历循环显示出来 -->
<s:iterator value="#users" status="bcs">
<tr>
<td><s:property value="uid"></s:property></td>
<td><s:property value="name"></s:property></td>
<td><s:property value="sex"></s:property></td>
<td><s:property value="phone"></s:property></td>
<td><s:property value="mail"></s:property></td>
<!-- <td><s:property value="%{formatDouble(deposit)}"></s:property></td> -->
</tr>
</s:iterator>
<tr>
<!-- 调用UserAction的size -->
<td colspan="7"><s:property value="%{size(#users)}"></s:property></td>
</tr>
<!-- 判断用户人数是不是为0 -->
<s:if test="#users.size()==0">
<tr>
<td colspan="7">没有查找到数据</td>
</tr>
</s:if>
</table>
</body>
</html>
2.9 示例项目
链接:https://pan.baidu.com/s/1_aR6vn5q3FdOl0UqkinpDA
提取码:aasw
3.运行
3.1运行效果
访问“http://localhost:8080/ssh/index”路径
3.2 Unable to process Jar entry [module-info.class]错误
在Tomcat8.0服务器及更低版本的服务器下运行会出现Unable to process Jar entry [module-info.class]
错误,该错误不影响使用。但是如果要根除该问题需要升级到Tomcat9.0版本。
1月 22, 2020 9:55:11 下午 org.apache.catalina.startup.ContextConfig processAnnotationsJar
严重: Unable to process Jar entry [module-info.class] from Jar [file:/G:/JavaProject/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/ssh/WEB-INF/lib/txw2-2.3.1.jar] for annotations
org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 19
at org.apache.tomcat.util.bcel.classfile.Constant.readConstant(Constant.java:97)
at org.apache.tomcat.util.bcel.classfile.ConstantPool.<init>(ConstantPool.java:55)
at org.apache.tomcat.util.bcel.classfile.ClassParser.readConstantPool(ClassParser.java:176)
at org.apache.tomcat.util.bcel.classfile.ClassParser.parse(ClassParser.java:85)
at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:2042)
at org.apache.catalina.startup.ContextConfig.processAnnotationsJar(ContextConfig.java:1988)
at org.apache.catalina.startup.ContextConfig.processAnnotationsUrl(ContextConfig.java:1958)
at org.apache.catalina.startup.ContextConfig.processAnnotations(ContextConfig.java:1912)
at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1157)
at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:779)
at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:306)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:95)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5202)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1407)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1397)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:835)
4.总结
虽然完成了SSH框架的整合和搭建,并能够成功运行,但是对一些更详细的内容还不够了,比如Struts的标签,创建action的三种方式有什么不同等问题。有不清楚的地方欢迎评论留言,看到的我都会回复的。本文到此结束,有什么不足的地方请大家不吝指正。