1、web整合servlet+spring(在sts中创建javaweb可以参考:https://www.cnblogs.com/ZXF6/p/11066691.html ,此案例中Dynamic web module version用的是3.1)
(1) 前提sts中已经配置tomcat 服务器、maven和jdk。
(2)导包 目录
架包下载链接:https://pan.baidu.com/s/1Er_HeDA9b5S0fYfKjPhDsw 提取码:m71g
(3)①service层:接口
package com.gyf.service;
public interface IUserService {
public void add(String username);
}
实现类:
package com.gyf.service.impl;
import com.gyf.service.IUserService;
public class UserServiceImpl implements IUserService {
@Override
public void add(String username) {
System.out.println("添加用户成功!。。。。"+username);
}
}
②web层
package com.gyf.web.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.gyf.service.IUserService;
/**
* Servlet implementation class RegisterServlt
*/
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public RegisterServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取参数
String username=request.getParameter("username");
//调用service
//service的创建交由spring,并从spring的容器获取user
IUserService userService=null;
//,开发中,项目只需要加载一次spring的配置文件就行了
/* ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
;//这样写会导致浏览器每次刷新都会加载一次spring的配置文件:解决---》配置一个监听器 */
//获取applicationContext对象
ApplicationContext context=WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
System.out.println(context.hashCode());
userService=(IUserService) context.getBean("userService");
userService.add(username);
//响应
response.getWriter().write("register success");
}
}
③applicationContext.xml(在/src目录下)
<?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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd">
<bean id="userService" class="com.gyf.service.impl.UserServiceImpl"></bean>
</beans>
④web.xml(在/WebContent/WEB-INF目录下)
<?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>web-servlet-spring</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 配置spring配置文件的加载路径 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 监听器 --><!-- 默认是找[/WEB-INF/applicationContext.xml ] 路径下的文件-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- <listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener> -->
</web-app>
⑤index.jsp(在/WebContent目录下)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>wellcom!</title>
</head>
<body>
你好!
</body>
</html>
结果:
总结:大致过程包括:导包、创建servlet和service、写spring的配置文件applicationContext.xml、在web.xml中配置spring的监听等步骤。
2、web整合struts+hibernate+spring(struts-2.3.24-all.zip、spring-framework-3.0.2.RELEASE.zip、hibernate-distribution-3.6.10.Final-dist.zip)
导包:①struts的jar包:解压struts-2.3.24-all.zip后的sturts-2.3.24all\struts-2.3.34\apps\struts2-blank.war\WEB-INF\lib目录下内的所有jar;②spring的jar包:基础4+1:[beans、core、context、expression,commons-logging(struts 已经导入的话,就这个包就不用导入了)]、aop联盟(aopalliance)、aspect规范(aspect.weaver)、spring aop、spring aspect 、db:spring-jdbc、spring-tx、测试:spring-test、web开发:spring-web(web.xml加载spring配置文件)、驱动:mysql、连接池:c3p0、整合hibernate:spring-orm(事务管理器);③hibernate包:hibernate3.jar、jpa文件和required文件下的所有包。log4j-api-2.3.jar/log4j-core-2.3.jar。
架包下载链接:https://pan.baidu.com/s/1hgT_HhbVcAtuAMOVOC665g 提取码: bfd9
目录
(一)整合hibernate+spring
(1)po类(persistant object 持久对象,可以看成是与数据库中的表相映射的java对象)和映射文件
①model层:User类
package com.gyf.itedu.model;
public class User {
private Integer id;
private String username;
private String password;
private Integer age;
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;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password="
+ password + ", age=" + age + "]";
}
public User() {
super();
}
public User(String username, String password, Integer age) {
super();
this.username = username;
this.password = password;
this.age = age;
}
}
User.hbm.xml文件(在model包下)
<?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 package="com.gyf.itedu.model">
<class name="User">
<id name="id">
<generator class="native"></generator>
</id>
<property name="username" length="20"></property>
<property name="password" length="10"></property>
<property name="age"></property>
</class>
</hibernate-mapping>
②dao层:接口IUserDao
package com.gyf.itedu.dao;
import com.gyf.itedu.model.User;
public interface IUserDao {
public void add(User user);
}
实体类:UserDaoImpl
package com.gyf.itedu.dao.impl;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.gyf.itedu.dao.IUserDao;
import com.gyf.itedu.model.User;
public class UserDaoImpl implements IUserDao {
private HibernateTemplate hibernateTemplate;
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
@Override
public void add(User user) {
hibernateTemplate.save(user);
}
}
③service层:接口
package com.gyf.itedu.service;
import com.gyf.itedu.model.User;
public interface IUserService {
public void register(User user);
}
实体类:
package com.gyf.itedu.service.impl;
import com.gyf.itedu.dao.IUserDao;
import com.gyf.itedu.model.User;
import com.gyf.itedu.service.IUserService;
public class UserServiceImpl implements IUserService {
private IUserDao userDao;
public void setUserdao(IUserDao userDao) {
this.userDao = userDao;
}
@Override
public void register(User user) {
userDao.add(user);
}
}
④创建itedu数据库就行,里面是空的,没有一张表。
编写hibernate.cfg.xml(位于/src下)
<!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>
<!-- 配置数据库连接的4个参数 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///itedu</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123456</property>
<!-- 是否显示sql语句 -->
<property name="show_sql">true</property>
<!-- 是否格式化sql语句 -->
<property name="format_sql">true</property>
<!--hibernate.hbm2ddl.auto
配置 映射文件与数据库表的关系,update:如果数据库没有表,自动帮你创表[常用]-->
<property name="hibernate.hbm2ddl.auto">update</property>
<!--hibernate.dialect 数据库方言
mysql:分页limit
oracle:分页rownum-->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- 配置映射文件 -->
<mapping resource="com/gyf/itedu/model/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
编写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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 创建sessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<!-- 配置 hibernate的配置文件路径-->
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
</bean>
<!-- 创建Hibernate的模板 -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean >
<!-- 创建dao -->
<bean id="userDao" class="com.gyf.itedu.dao.impl.UserDaoImpl">
<property name="hibernateTemplate" ref="hibernateTemplate"></property>
</bean>
<!-- 创建service -->
<bean id="userService" class="com.gyf.itedu.service.impl.UserServiceImpl">
<property name="userdao" ref="userDao"></property>
</bean>
<!-- 配置事务 -->
<!-- 1、事务管理器 -->
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 2、配置通知 -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="register"/>
</tx:attributes>
</tx:advice>
<!-- 3、把通知应用到切入点 -->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.gyf.itedu.service..*.*(..))"/>
</aop:config>
</beans>
⑤配置Hibernate的事务
<!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>
<!-- 配置数据库连接的4个参数 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///itedu</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123456</property>
<!-- 是否显示sql语句 -->
<property name="show_sql">true</property>
<!-- 是否格式化sql语句 -->
<property name="format_sql">true</property>
<!--hibernate.hbm2ddl.auto
配置 映射文件与数据库表的关系,update:如果数据库没有表,自动帮你创表[常用]-->
<property name="hibernate.hbm2ddl.auto">update</property>
<!--hibernate.dialect 数据库方言
mysql:分页limit
oracle:分页rownum-->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- 配置映射文件 -->
<mapping resource="com/gyf/itedu/model/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
⑥test层 Demo01类:
package com.gyf.itedu.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.gyf.itedu.model.User;
import com.gyf.itedu.service.IUserService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class Demo01 {
@Autowired
private IUserService userService;
@Test
public void test1() {
//保存一个用户
User user=new User("gyf","123",10);
userService.register(user);
}
}
(二)简化。去除hibernate.cfg.xml,将它的内容写applicationContext.xml中(先将applicationContext.xml复制一份到/src中再修改)
<?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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd">
<!--数据源 datasource (以前这些是放在java文件中会编译才.class文件,要修改比较难,现在放在xml了,.xml文件不会编译成.class文件)-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///itedu"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!-- 创建sessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<!-- 1、datasource-->
<property name="dataSource" ref="dataSource"></property>
<!-- 2、hibernate其他配置-->
<!--<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<mapping resource="com/gyf/itedu/model/User.hbm.xml"/>
-->
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
</props>
</property>
<!-- 3、hibernate的映射文件路径-->
<property name="mappingLocations" value="classpath:com/gyf/itedu/model/*.hbm.xml"></property>
</bean>
<!-- 创建Hibernate的模板 -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean >
<!-- 创建dao -->
<bean id="userDao" class="com.gyf.itedu.dao.impl.UserDaoImpl">
<property name="hibernateTemplate" ref="hibernateTemplate"></property>
</bean>
<!-- 创建service -->
<bean id="userService" class="com.gyf.itedu.service.impl.UserServiceImpl">
<property name="userdao" ref="userDao"></property>
</bean>
<!-- 配置事务 -->
<!-- 1、事务管理器 -->
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 2、配置通知 -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="register"/>
</tx:attributes>
</tx:advice>
<!-- 3、把通知应用到切入点 -->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.gyf.itedu.service..*.*(..))"/>
</aop:config>
</beans>
(三)整合struts+spring
编写action类,并将其配置给spring,spring可以注入service,编写struts.xml,编写表但jsp页面。
web.xml配置:确定配置文件contextConfigLocation、配置监听器、contextLocationListener、配置前端控制器StrutsPrepareAndExecuteFitler
①web层UserAction
package com.gyf.itedu.web.action;
import org.springframework.beans.factory.annotation.Autowired;
import com.gyf.itedu.model.User;
import com.gyf.itedu.service.IUserService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class UserAction extends ActionSupport implements ModelDriven<User>{
private User user= new User();
//action中使用Service注意:①不需要在spring的配置文件中注入service。②会根据spring中的id名字注入到当前属性中
private IUserService userService;
public void setUserService(IUserService userService) {
this.userService = userService;
}
public String register() {
//获取请求参数
System.out.println(user);
//调用service
userService.register(user);
//返回结果
return SUCCESS;
}
@Override
public User getModel() {
return user;
}
}
②编写struts.xml(在/src目录下)
<?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>
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
<action name="user_*" class="com.gyf.itedu.web.action.UserAction" method="{1}">
<result name="success">/success.jsp</result>
</action>
</package>
</struts>
③编写success.jsp页面(在/WebContent目录下)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
注册成功!
</body>
</html>
编写index.jsp页面(在/WebContent目录下)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>wellcom!</title>
</head>
<body>
你好!
</body>
</html>
⑤编写web.xml(在/WebContent/WEB-INF目录下)
<?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">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 1、web项目启动时加载spring配置[监听器] -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener><!-- org.springframework.web.context.ContextLoaderListener -->
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 2、配置Struts的拦截器 -->
<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>
</web-app>
启动服务器后,在浏览器输入http://localhost:8080/web-ssh/user_register?username=af&password=128&age=21结果:
注意:数据库表中出现的是22而不是7,是因为我已经把7到21的记录删除了,定义的是自增型,id是主键,所以是22。