快速整合ssh框架搭建简单demo

eclipse创建项目
File -> new ->Dynamic Web Project
在这里插入图片描述
->next ->next
在这里插入图片描述
Generate web.xml deployment descriptor 打上勾,项目创建时会自动创建web.xml文件。->finish
项目工程目录
复制相关jar文件到lib
struts2_lib
struts2需要的jar包
spring_lib
spring需要的jar包
hibernate_lib
hibernatge需要的jar包
这三个lib目录分别单独属于struts2、spring、hibernate三个框架,整合在一起的会有部分重复,删除旧版本,保留新版本即可
在这里插入图片描述
三个框架整合是struts-spring.jar一定要加,调试的时候忘记导入这个包,spring和struts2整合疯狂报错,当时一脸懵
这里推荐一个jar下载网站Jar File Download,需要的jar、源文件一般都可以在里面找到=-=重要的是,完全免费,不需要积分,都知道说的是谁奥:) 或者使用maven,只需要配置pom.xml就可以自动下载所需的jar包
导入jar到项目中
选中lib包下所有的jar(按住shift,左键点第一个文件,最后一个文件,即可选中所有的jar)右键->Build Path -> add to Build Path

需求:查询数据库中user表中的所有记录,以表格形式显示所有的记录(user表字段【id,username,password】)
前期准备
在src文件下新建下列包和.java,.xml文件
在这里插入图片描述
Demo.java

public class Demo extends ActionSupport{
	DemoService demoService;
	public void setDemoService(DemoService demoService) {
		this.demoService = demoService;
	}
	public String query() throws Exception{
		List<User> list = demoService.queryAll();
		//获取值栈对象,将demoService返回的List<User>放入值栈中
		ActionContext context = ActionContext.getContext();
		ValueStack valueStack = context.getValueStack();
		valueStack.set("users",list);
		return "query";	
	}	
}

User.java

package cn.sshdemo.entity;
public class User {
	private Integer id;
	private String username;
	private String password;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
}

DemoDao.java

public interface DemoDao {
	//返回User集合
	List<User> queryAll();
}

DemoDaoImpl.java 实现DemoDao接口

public class DemoDaoImpl extends HibernateDaoSupport implements DemoDao{
	@Override
	public List<User> queryAll() {
		// TODO Auto-generated method stub
		List<User> users = (List<User>)this.getHibernateTemplate().find("from User");
		return users;
	}
}

DemoService.java
类名上添加事务注解

@Transactional
public class DemoService {
	DemoDao demoDao;
	public void setDemoDao(DemoDao demoDao) {
		this.demoDao = demoDao;
	}
	public List<User> queryAll(){
		return demoDao.queryAll();
	}
}

在这里插入图片描述
WebContent 下新建index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 <!--加载struts2标签库-->
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
	<table>
		<tr>
			<th>id</th>
			<th>username</th>
			<th>password</th>
		</tr>
		<!--使用ognl表达式循环生成表格记录-->
		<s:iterator value="users">
			<tr>
				<td><s:property value="id"/></td>
				<td><s:property value="username"/></td>
				<td><s:property value="password"/></td>
			</tr>
		</s:iterator>
	</table>
</body>
</html>

搭建struts2环境
(1)创建struts.xml,在xml中配置action

<!--服务器解析客户端的请求,映射到Demo中的某个方法,将调用方法的返回值和result中name值比较,确定跳转至哪个页面
	method="{1}" 对应着demo_*的*,比如demo_action,则会调用Demo中的action()方法
-->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">
	<struts>
		<package name="demo" extends="struts-default" >
			<action name="demo_*" class="cn.sshdemo.action.Demo" method="{1}">
				<result name="query">index.jsp</result>
			</action>
		</package>
	</struts>

(2)在web.xml中配置struts2的过滤器

 <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
     <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

搭建hibernate环境
创建hibernate.cfg.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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">【数据库url地址】</property>
		<property name="hibernate.connection.username">【用户名】</property>
		<property name="hibernate.connection.password">【密码】</property> 
		<property name="hibernate.show_sql">true</property>
		<property name="hibernate.format_sql">true</property>
		<!-- update  没有表,创建表,已有表,更新表 -->
		<property name="hibernate.hbm2ddl.auto" >update</property>
		<!-- 配置数据库方言
			在mysql里面实现分页关键字limit,只能使用在mysql里面
			在oracle数据库,实现分页rownum
			让hibernate框架识别不同数据库中特有的语句
		 -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		
		<mapping resource="cn/sshdemo/entity/user.hbm.xml"/>
	</session-factory>
	
</hibernate-configuration>

创建映射配置文件user.hbm.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="cn.sshdemo.entity.User" table="m_user">
			<id name="id" column="id">
				<generator class="native"></generator>
			</id>
			<property name="username" column="username"></property>
			<property name="password" column="password"></property>
		</class>
	
	</hibernate-mapping>

搭建spring环境
创建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:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.2.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
		
</beans>

web.xml中相关配置

<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>

struts2和spring整合
配置applicationContext.xml
spring核心功能之一IOC:控制反转,将实例化对象交由spring处理。这里生成demoService、demoDaoImpl分别通过set方法注入到DemoAction、DemoService中去

<bean id="demoAction" class="cn.sshdemo.action.Demo" scope="prototype">
		<property name="demoService" ref="demoService"></property>
	</bean>
	<bean id="demoService" class="cn.sshdemo.service.DemoService">
		<property name="demoDao" ref="demoDaoImpl"></property>
	</bean>
	<bean id="demoDaoImpl" class="cn.sshdemo.daoImpl.DemoDaoImpl">
		<property name="hibernateTemplate" ref="hibernateTemplate"></property>
	</bean>

修改struts.xml文件,action的class修改为demoAction,因为该对象已由spring创建

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">
	<struts>
		<package name="demo" extends="struts-default" >
			<action name="demo_*" class="demoAction" method="{1}">
				<result name="query">index.jsp</result>
			</action>
		</package>
	</struts>

hibernate和spring整合
在applicationContext.xml中配置dataSource、sessionFactory等相关信息

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
       <property name="url" value="jdbc:mysql://127.0.0.1:3306/spring" />
       <property name="username" value="root" />
       <property name="password" value="895772" />
	</bean>
	<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource"></property>
		<property name="configLocations" value="classPath:hibernate.cfg.xml"></property>
	</bean>
	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>

注释掉hibernate.cfg.xml中配置的数据库连接信息,因为已由spring配置完毕

<?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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">...............</property>
		<property name="hibernate.connection.username">.........</property>
		<property name="hibernate.connection.password">..........</property>  -->
		<property name="hibernate.show_sql">true</property>
		<property name="hibernate.format_sql">true</property>
		<!-- update  没有表,创建表,已有表,更新表 -->
		<property name="hibernate.hbm2ddl.auto" >update</property>
		<!-- 配置数据库方言
			在mysql里面实现分页关键字limit,只能使用在mysql里面
			在oracle数据库,实现分页rownum
			让hibernate框架识别不同数据库中特有的语句
		 -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		
		<mapping resource="cn/sshdemo/entity/user.hbm.xml"/>
	</session-factory>
	
</hibernate-configuration>

配置事务
在applicationContext.xml中添加一下代码

<!-- 配置事务 -->
	<!-- 配置事务管理器 --> 
	<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
	<!-- 注入sessionFactory -->
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<!-- 开启事务注解 -->
	<tx:annotation-driven transaction-manager="transactionManager"/>

运行
右键add and remove,将要运行的项目添加进 Configured
在这里插入图片描述
右键start,服务器启动。查看console,如果程序没有问题,控制台不会有异常抛出且数据库会自动生成m_user表,如果出现异常,则根据异常一步步排查错误
打开chrome浏览器,地址栏中输入localhost:8080/sshdemo/demo_query.action 调用Demo中的query方法
在这里插入图片描述
因为数据库中只插了一行记录,当然只有一行显示啦==
如果出现404错误,检查路径;出现500错误,检查代码就行了:)

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值