一、准备工作

开始之前,先参考上一篇:

struts2.3.24 + spring4.1.6 + hibernate4.3.11 + mysql5.5.25 开发环境搭建及相关说明

struts2.3.24 + spring4.1.6 + hibernate4.3.11 + mysql5.5.25 开发环境搭建及相关说明

struts2.3.24 + spring4.1.6 + hibernate4.3.11 + mysql5.5.25 开发环境搭建及相关说明

思路都是一样的,只不过把struts2替换成了spring mvc

二、不同的地方

工程目录及jar包:

action包改成controller;

删除struts2 jar包,添加spring mvc包(已有的话,不需添加);

   

web.xml配置:

跟之前不同的地方是把struts2的过滤器替换成了一个servlet,主要目的是路由url,交给spring mvc处理;

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>SSH</display-name> <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> <welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list> <servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping> </web-app>

applicationContext.xml配置:

不同的地方主要是配置自动扫描的时候,要排除@Controller组件,这些bean是由spring mvc 去生成的;

其它配置跟前一篇一样;

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.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-4.1.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd"> <!-- scans the classpath for annotated components (including @Repostory
and @Service that will be auto-registered as Spring beans -->
<context:component-scan base-package="ssh" >
<!--排除@Controller组件,该组件由SpringMVC配置文件扫描 -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan> <!--配数据源 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/demo" />
<property name="user" value="root" />
<property name="password" value="root" /> <property name="acquireIncrement" value="1"></property>
<property name="initialPoolSize" value="80"></property>
<property name="maxIdleTime" value="60"></property>
<property name="maxPoolSize" value="80"></property>
<property name="minPoolSize" value="50"></property>
<property name="acquireRetryDelay" value="1000"></property>
<property name="acquireRetryAttempts" value="60"></property>
<property name="breakAfterAcquireFailure" value="false"></property>
<!-- 如出现Too many connections, 注意修改mysql的配置文件my.ini,增大最多连接数配置项,(查看当前连接命令:show processlist) -->
</bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" /> <property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="connection.pool_size">10</prop>
<prop key="current_session_context_class">thread</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.cache.provider_configuration_file_resource_path">ehcache.xml</prop>
</props>
</property>
<property name="mappingLocations">
<list>
<value>classpath:ssh/model/User.hbm.xml</value>
</list>
</property>
<!--
<property name="annotatedClasses">
<list>
<value>ssh.model.User</value>
</list>
</property>
-->
</bean> <!-- 配置事务管理器 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean> <!-- 事务的传播特性 -->
<tx:advice id="txadvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
<tx:method name="delete*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
<tx:method name="update*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
<tx:method name="save*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
</tx:attributes>
</tx:advice> <aop:config>
<aop:pointcut id="pcMethod" expression="execution(* ssh.service..*.*(..))" />
<aop:advisor pointcut-ref="pcMethod" advice-ref="txadvice" />
</aop:config> <!-- 自定义aop处理 测试 -->
<bean id="aopTest" class="ssh.aop.AopTest"></bean>
<bean id="myAop" class="ssh.aop.MyAop"></bean>
<aop:config proxy-target-class="true">
<aop:aspect ref="myAop">
<aop:pointcut id="pcMethodTest" expression="execution(* ssh.aop.AopTest.test*(..))"/>
<aop:before pointcut-ref="pcMethodTest" method="before"/>
<aop:after pointcut-ref="pcMethodTest" method="after"/>
</aop:aspect>
</aop:config> </beans>

springmvc-servlet.xml配置:

配置自动扫描ssh.controller包下的@Controller,这里要恢复applicationContext.xml中配置的exclude-filter;

配置视图解析器,有很多解析器,这里以InternalResourceViewResolver为例;

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
"> <!-- 启动自动扫描该包下所有的Bean(例如@Controller) -->
<context:component-scan base-package="ssh.controller" >
<!-- 恢复父容器设置的 exclude-filter,注意包扫描路径ssh.controller-->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan> <!-- 定义视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean> </beans>

编写controller:

由于使用spring mvc替换struts2,也就没有了action包了,删除,并新建controller包,在包下新建UserController类;

@RequestMapping:映射url;

@ResponseBody:内容直接作为body返回;

UserController.java

package ssh.controller;

import java.io.PrintWriter;
import java.util.List; import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import ssh.aop.AopTest;
import ssh.model.User;
import ssh.service.UserService; import com.google.gson.Gson; @Controller
@RequestMapping("/user")
public class UserController {
Logger logger = Logger.getLogger(UserController.class);
@Resource
private UserService userService;
@Resource
private AopTest aopTest; @RequestMapping(value="/addUser")
@ResponseBody
public void addUser(HttpServletRequest request, HttpServletResponse response){
PrintWriter out = null;
try{
response.setContentType("text/html;charset=UTF-8");
String account = request.getParameter("account");
String name = request.getParameter("name");
String address = request.getParameter("address");
User user = new User();
user.setAccount(account);
user.setAddress(address);
user.setName(name);
userService.add(user);
out = response.getWriter();
out.write(new Gson().toJson("success"));
}catch(Exception e){
e.printStackTrace();
logger.error(e.getMessage());
if(out != null)
out.write(new Gson().toJson("fail"));
}finally{
out.flush();
out.close();
} } @RequestMapping(value="/queryUser")
@ResponseBody
public void queryAllUser(HttpServletRequest request, HttpServletResponse response){
PrintWriter out = null; aopTest.test1();
aopTest.test2(); try { response.setContentType("text/html;charset=UTF-8"); Gson gson = new Gson();
List<User> userList= userService.queryAllUser();
String gsonStr = gson.toJson(userList); out = response.getWriter();
out.write(gsonStr);
} catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage());
if(out != null)
out.write(new Gson().toJson("fail"));
}finally{
out.flush();
out.close();
}
}
}

三、运行程序

运行程序,添加用户、查询用户功能正常;

另外二级缓存也正常工作,第二次查询已经没有操作数据库了;

spring mvc4.1.6 + spring4.1.6 + hibernate4.3.11 + mysql5.5.25 开发环境搭建及相关说明的更多相关文章

  1. struts2.3.24 + spring4.1.6 + hibernate4.3.11+ mysql5.5.25开发环境搭建及相关说明

    一.目标 1.搭建传统的ssh开发环境,并成功运行(插入.查询) 2.了解c3p0连接池相关配置 3.了解验证hibernate的二级缓存,并验证 4.了解spring事物配置,并验证 5.了解spr ...

  2. spring boot 开发环境搭建(Eclipse)

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

  3. Spring开发环境搭建(Eclipse)

    开发环境搭建,主要包含2部分: Java安装 Eclipse安装 为易于学习,我们只安装这2个部分,对于一般开发学习也足够了.如果你有其他要安装的,酌情添加. Java安装 我们使用Java8: 下载 ...

  4. (转)Spring4.2.5+Hibernate4.3.11+Struts2.3.24整合开发

    http://blog.csdn.net/yerenyuan_pku/article/details/52902851 前面我们已经学会了Spring4.2.5+Hibernate4.3.11+Str ...

  5. (转)Spring4.2.5+Hibernate4.3.11+Struts1.3.8集成方案二

    http://blog.csdn.net/yerenyuan_pku/article/details/52894958 前面我们已经集成了Spring4.2.5+Hibernate4.3.11+Str ...

  6. (转)Spring4.2.5+Hibernate4.3.11+Struts1.3.8集成方案一

    http://blog.csdn.net/yerenyuan_pku/article/details/52888808 前面我们已经集成了Spring4.2.5+Hibernate4.3.11这两个框 ...

  7. (转)Spring4.2.5+Hibernate4.3.11组合开发

    http://blog.csdn.net/yerenyuan_pku/article/details/52887573 搭建和配置Spring与Hibernate整合的环境 今天我们来学习Spring ...

  8. 【转载】Maven+druid+MyBatis+Spring+Oracle+Dubbo开发环境搭建

    原地址:http://blog.csdn.net/wp1603710463/article/details/48247817#t16 Maven+druid+MyBatis+spring+Oracle ...

  9. Spring框架入门之开发环境搭建(MyEclipse2017平台)

    基于MyEclipse2017平台搭建Spring开发环境,这里MyEclipse已将Spring集成好了,我们只需要做一简单配置即可 一.环境配置 OS:Windows7 64位 IDE工具:MyE ...

随机推荐

  1. Hadoop入门进阶课程3--Hadoop2.X64位环境搭建

    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,博主为石山园,博客地址为 http://www.cnblogs.com/shishanyuan  ...

  2. 自己动手模拟百分百<select>下拉列表

    浏览器默认的下拉确实不好用啊,主要是样式不好修改和统一. (一)下手之前先理清一下<select>的流程: 1.结构:<select> <option value=&qu ...

  3. .NET指定程序集的位置

    有两种方法用来指定程序集的位置: 使用 <codeBase> 元素. 使用 <probing> 元素. 还可以使用 .NET Framework 配置工具 (Mscorcfg. ...

  4. jQuery的 delegate问题

    习惯了bind,用惯了live,就不习惯delegate了呀有木有... 支持为动态生成的标签元素绑定事件也许就live和delegate了吧,不过新版本已经不支持live了,只有delegate d ...

  5. C#设计模式——原型模式(Prototype Pattern)

    一.概述 在软件开发中,经常会碰上某些对象,其创建的过程比较复杂,而且随着需求的变化,其创建过程也会发生剧烈的变化,但他们的接口却能比较稳定.对这类对象的创建,我们应该遵循依赖倒置原则,即抽象不应该依 ...

  6. C#中CookieContainer获取里面cookie值异常:InvokeMember("m_domainTable") FieldAccessException

    1.可能是主机提供商的 安全问题. Their hosts works in medium trustsecurity, and ASProxy needs a full trust security ...

  7. 【Bootstrap基础学习】05 Bootstrap学习总结

    好吧,Copy了几天,这个总结算是把我对Bootstrap的一些理解写一下吧. Bootstrap只是一套别人写好的前端框架,直接拿来用就好. 不过对于专业的前端而言,如果不去把所有的代码都看一遍来理 ...

  8. gene框架文档 - 路由类 gene_router

    路由类 Gene\Router 介绍 Gene\Router 是gene框架的核心类之一,本框架区别于其他常见框架的最大地方就是独特.强大.简单的路由定义等.路由强大灵活,支持回调.类方法:支持res ...

  9. Java中处理异常throw和throws

    1.首先我们来了解什么是异常呢? 异常阻止当前方法或作用域继续执行的问题. 2.处理异常 说到处理异常,我们当然会想到 try catch finally 在java中我们会对异常的处理有更高的认识 ...

  10. ArrayList实现源码分析

    本文将以以下几个问题来探讨ArrayList的源码实现 1.ArrayList的大小是如何自动增加的 2.什么情况下你会使用ArrayList?什么时候你会选择LinkedList? 3.如何复制某个 ...