2f Spring web整合.txt
UP 返回
1.spring-servlet整合
1.1 项目创建
新建项目→选择Java Enterprise→勾选Web Application→下一步完成
项目展开,web/WEB-INF下新建lib文件夹,将所用的包复制进去,右键lib,选择Add as Library,点击OK
1.2 项目参见 D:\ProjectCodes\IDEA2017\spring-servlet
注意点:
为了避免在servlet中重复创建上下文,需要配置web.xml配置文件,在里面设置监听器自动在项目启动时读入配置文件。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<!--●配置spring配置文件的加载路径-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--●监听器-->
<listener>
<!--▶配置默认读取[/WEB-INF/applicationContext.xml]路径下的文件,如果位置不一样需要做上面的修改配置-->
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
servlet代码:
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取参数
String username=request.getParameter("username");
//获取application对象
IUserService userService=null;
ApplicationContext context=WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
userService=(IUserService) context.getBean("userService");
userService.add(username);
//响应
response.getWriter().write("register success");
}
}
浏览器访问方式:http://localhost:8080/register?username=用户名
2.spring-struts-hibernate整合
2.1 导入jar
首先创建项目,过程同上。
相比之前的jar,因为现在使用hibernate,所以spring-jdbc可以不导入
Struts包:
F:\BaiduNetdiskDownload\2019年4月黑马程序员教程\01-黑马IDEA版本Java基础+就业课程\4.框架\Java开发工具\jar包\struts\struts-2.3.33-all\struts-2.3.33\apps\
下的struts2-blank.war,压缩软件打开,将WEB-INF\lib下的所有jar复制进入lib文件夹
Spring包:
基础:4+1 , beans、core、context、expression , commons-logging (struts已经导入) 前4个在dist中,最后一个在依赖(org.apache.commons\logging)
AOP:aop联盟(aopalliance)、aspect规范(aspect.weaver)、spring aop 、spring aspect 前2个在依赖(org.aopalliance,org.aspectj\weaver),后两个在dist中
db:jdbc,tx 两个包均要导入,都在dist中
测试:test dist中
web开发:spring-web dist中
驱动:mysql F:\BaiduNetdiskDownload\2019年4月黑马程序员教程\01-黑马IDEA版本Java基础+就业课程\4.框架\Java开发工具\jar包\dbcp连接池\mysql-connector-java-5.0.8-bin.jar
连接池:c3p0 依赖中(com.mchange.c3p0)
整合hibernate:spring-orm dist中
log4j包:
log4j-1.2.16.jar F:\BaiduNetdiskDownload\2019年4月黑马程序员教程\01-黑马IDEA版本Java基础+就业课程\4.框架\Java开发工具\jar包\log4j\apache-log4j-1.2.16.zip\文件夹\.jar
slf4j-log4j12-1.7.2.jar (起到桥接两个jar的作用) F:\BaiduNetdiskDownload\2019年4月黑马程序员教程\01-黑马IDEA版本Java基础+就业课程\4.框架\Java开发工具\jar包\log4j
二级缓存:
backport-util-concurrent.jar 两个包都在F:\BaiduNetdiskDownload\2019年4月黑马程序员教程\01-黑马IDEA版本Java基础+就业课程\4.框架\Java开发工具\jar包\hibernate\ehcache.zip中
ehcache-1.5.0.jar
整合包:
spring整合hibernate: spring orm (前面已导入)
struts 整合spring:struts2-spring-plugin-2.3.15.3.jar F:\BaiduNetdiskDownload\2019年4月黑马程序员教程\01-黑马IDEA版本Java基础+就业课程\4.框架\Java开发工具\jar包\struts\struts-2.3.33-all\struts-2.3.33\lib\struts2-spring-plugin-2.3.33.jar
hibernate包:
hibernate3.jar F:\BaiduNetdiskDownload\2019年4月黑马程序员教程\01-黑马IDEA版本Java基础+就业课程\4.框架\Java开发工具\jar包\hibernate\hibernate-distribution-3.6.10.Final-dist.zip\文件夹\hibernate3.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar F:\BaiduNetdiskDownload\2019年4月黑马程序员教程\01-黑马IDEA版本Java基础+就业课程\4.框架\Java开发工具\jar包\hibernate\hibernate-distribution-3.6.10.Final-dist.zip\文件夹\lib\jpa\hibernate-jpa-2.0-api-1.0.1.Final.jar
require下所有包(和Struts有重复的javassist.jar,可以删除一个) F:\BaiduNetdiskDownload\2019年4月黑马程序员教程\01-黑马IDEA版本Java基础+就业课程\4.框架\Java开发工具\jar包\hibernate\hibernate-distribution-3.6.10.Final-dist.zip\文件夹\lib\required\*.jar
2.2 整合spring和hibernate
█参见项目:D:\ProjectCodes\IDEA2017\spring-struts-hibernate
★hibernate配置文件 hibernate.cfg.xml
<!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>
<!-- 1、配置数据库连接的4个参数 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123654</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>
<!-- hiberante.dialect:数据库方言
mysql:分页limit
oracle:分页rownum
-->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- 配置映射文件 -->
<mapping resource="com/ittest/model/User.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>
★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: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
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://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>
<bean id="hibernate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="userDao" class="com.ittest.dao.impl.UserDaoImpl">
<property name="hibernateTemplate" ref="hibernate"></property>
</bean>
<bean id="userService" class="com.ittest.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
<!--配置事务(不配置SQL语句不会提交)-->
<!--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.ittest.service..*.*(..))"></aop:advisor>
</aop:config>
</beans>
■model
public class User {
private Integer id;
private String username;
private String password;
private Integer age;
}
▶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 package="com.ittest.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
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
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);
}
}
■test类
//使用spring配置文件测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class Test01 {
@Autowired
private IUserService userService;
@Test
public void save(){
User user=new User("haha","122",11);
userService.register(user);
}
}
2.3 去除hibernate的配置文件(整合进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: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
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///test"></property>
<property name="user" value="root"></property>
<property name="password" value="123654"></property>
</bean>
<!--创建sessionFactory-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<!--▶hibernate的配置文件路径不使用了-->
<!--1.DataSource-->
<property name="dataSource" ref="dataSource"></property>
<!--2.hibernate其他配置-->
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop> ▶注意:在hibernate的配置文件中可以不写hibernate.,但是这里如果不写的话该属性会失效,下面的hibernate.format_sql同理
<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的映射文件路径 *.hbm.xml:取下面所有的映射文件-->
<property name="mappingLocations" value="classpath:com/ittest/model/*.hbm.xml"></property>
</bean>
<bean id="hibernate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="userDao" class="com.ittest.dao.impl.UserDaoImpl">
<property name="hibernateTemplate" ref="hibernate"></property>
</bean>
<bean id="userService" class="com.ittest.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
<!--配置事务(不配置SQL语句不会提交)-->
<!--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.ittest.service..*.*(..))"></aop:advisor>
</aop:config>
</beans>
2.4 整合Struts
★struts.xml
<?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.ittest.web.action.RegisterAction" method="{1}">
<result name="success">/success.jsp</result>
</action>
</package>
</struts>
★web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<context-param>
<param-name>contextConfigLocation</param-name> ▶修改spring配置文件路径
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--▶1.web项启动的时候加载spring配置文件-->
<listener>
<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>
▶success.jsp页面放在web文件夹下
■action
public class RegisterAction extends ActionSupport implements ModelDriven<User>{
private User user=new User();
/**
* ▶▶在action中使用Service注意:
* 1.不需要在spring的配置文件中注入service
* 2.会根据spring中的id的名字注入到当前属性中
* 3.在action中service要提供set方法
原因:在struts-core-2.3.33.jar/org.apache.struts2下有一个default.properties,其中有一句struts.objectFactory.spring.autoWire = name
表示将根据applicationContext中的id名来自动给action注入,但是要有set方法
另外 # struts.objectFactory = spring 这句话表示action对象也将被spring创建。如果不用的话则该对象由struts创建
*/
private IUserService userService;
public void setUserService(IUserService userService) {
this.userService = userService;
}
public String register(){
//调用service
userService.register(user);
//返回结果
return SUCCESS;
}
@Override
public User getModel() {
return user;
}
}
▶浏览器使用 http://localhost:8080/user_register?username=aa&password=123 访问
DOWN 返回