spring mvc4.1.6 spring4.1.6 hibernate4.3.11 mysql5.5.25开发环境搭建图文教程
作者:风一样的码农 发布时间:2024-01-23 12:27:19
一、准备工作
开始之前,先参考上一篇:
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();
}
}
}
三、运行程序
运行程序,添加用户、查询用户功能正常;
另外二级缓存也正常工作,第二次查询已经没有操作数据库了;
@author 风一样的码农
来源:http://www.cnblogs.com/chenpi/p/5155252.html
猜你喜欢
- 本文的OCR当然不是自己从头开发的,是基于百度智能云提供的API(我感觉是百度在中国的人工智能领域值得称赞的一大贡献),其提供的API完全可
- 下午有同学Python学习群里说,使用pyinstaller打包源码时,因为代码中使用了图像、音频、视频等资源文件,无法将程序打包成单一的可
- 在SQL Server 2005中,它的另外一个强大的新特点是数据库快照。数据库快照是一个数据库的只读副本,它是数据库所有数据的映射,由快照
- 问题一:安装模块时出现报错 Microsoft Visual C++ 14.0 is required,也下载安装了运行库依然还是
- 好了,废话少说,我们先看看几个示例吧一、打开一个网页获取所有的内容from urllib import urlopendoc = urlop
- 1 以下代码的输出结果为:print(round(-3.6))A.-4B.-4.0C.-3D. -3.02 以下代码的输出结果为(Pytho
- Tkinter 实现上述功能并不复杂,只要使用 Tkinter 的相关组件和一些简单的逻辑处理即可,在编写这个案例的过程中大家要做到温故而知
- 只要不是HTTP_REFERER来源于(google.com google.cn *.google.com *.google.cn baid
- 下面看下python调用函数加括号和不加括号的区别,具体代码如下所示; def bracket(data):return dat
- 遵循Web标准的思想,网页要表现出一种亲和力。那么,针对残障用户来说,其“阅读”器可不能读取图像上传递的信息的。所以我们会采用一种Using
- 从最基础的说起。本教程中,所有IE 均指 WindowXP + IE 6.0, 所有 FF 均指 FF 1.5。1. 不用编程的部分1.1
- (1)如下代码,默认递归获取指定目录root_dir下的所有文件,当指定recursive参数为False时,则只获取root_dir目录下
- 前言很多时候在windows下压缩文件没问题,但是到了Linux下,出现乱码,很常见。以前在Ubuntu下,用`unzip -O GBK f
- 功能:为连连看游戏提供连接算法 说明:模块中包含一个Point类,该类是游戏的基本单元“点”,该类包含属性:x,y,value。 其中x,y
- 用系统\administrators可以登录,在安全性用户列表中,修改sa属性时系统提示: 属性IsLocked不可用于登录"[s
- 目录用Python写一个简单的通讯录一、构思1、定义空列表和一个空字典来存储2、定义功能选项3、添加通讯录功能4、 循环,调用所有的函数功能
- 我们首先以一个例子来介绍模块化编程的应用场景,有这样一个名为requirements.py的python3文件,其中两个函数的作用是分别以不
- PIL基本功能介绍from PIL import Imagefrom PIL import ImageEnhanceimg = Image.
- 我们要开始学习如何做等级划分啦。要实现这一功能,还得学习 5 个新的知识点,分别是os.path.exists()、os.mkdir()、算
- 需要的软件phpStudy 用来导入一个数据库api-server 数据库功能可以开启一个服务器,让开发环境可以使用生产环境的网址请求安装