您的位置:首页 > 编程语言 > Java开发

SpringMVC+MyBatis环境整合开发案例

2015-06-28 16:08 731 查看
SpringMVC框架和经典的Struts+Spring相比而言,开发更简单,速度更快。因为使用SpringMVC不再需要像Struts那样写很多配置文件,只要轻松的几个注解就可以实现相应的功能,访问性能也比struts好得多。于初学者或者想了解mvc的人来说我觉得 spring是最好的,它的实现就是教科书!第二它和 tapestry一样是一个纯正的servlet系统,这也是它和tapestry相比 struts所没有的优势。而且框架本身有代码,而且看起来容易理解。不过事物都是相对的,开发容易的代价就是只能适用于中小型项目,毕竟struts是一个独立的视图框架,其管理视图的能力是不容忽视的,那就得看我们开发人员的取舍了。

1.下载和导入jar包

当然在之前得建立一个web项目或maven生成,导入的jar包可到官方下载,也可以到下载。

Jar包下载地址:http://download.csdn.net/detail/u012131769/8847435

Demo项目下载地址:http://download.csdn.net/detail/u012131769/8847497

2.web.xml配置 利用监听器整合spring,让应用启动时首先加载beans.xml

在web.xml添加一下代码:

<!-- 相关配置使用拦截器配置 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<!-- Spring的配置 -->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/spring-*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/springContext.xml</param-value>
</context-param>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
3.Spring配置文件beans.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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> 
<!-- 1、注解的自动扫描,表示组件(如:@controler,@Service,@Repository,@Resource等)的扫描 -->
<context:component-scan base-package="com.huaxun.smtest"></context:component-scan>

<!-- 2、配置C3P0数据源 -->
<bean id="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/spmvcm?useUnicode=true&characterEncoding=UTF8"/>
<property name="user" value="root" />
<property name="password" value="123" />
<!--连接池中保留的最小连接数。-->
<property name="minPoolSize" value="5" />
<!--连接池中保留的最大连接数。Default: 15 -->
<property name="maxPoolSize" value="30" />
<!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
<property name="initialPoolSize" value="10"/>
<!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
<property name="maxIdleTime" value="60"/>
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
<property name="acquireIncrement" value="5" />
<!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements
属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。
如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0-->
<property name="maxStatements" value="0" />
<!--每60秒检查所有连接池中的空闲连接。Default: 0 -->
<property name="idleConnectionTestPeriod" value="60" />
<!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->
<property name="acquireRetryAttempts" value="30" />
<!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效
保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试
获取连接失败后该数据源将申明已断开并永久关闭。Default: false-->
<property name="breakAfterAcquireFailure" value="true" />
</bean>

<!-- 3、MyBatis -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:Mybatis_Configuration.xml"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.huaxun.smtest.*" />
</bean>

<!--4、创建事务管理器,由spring负责创建  -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>

<!-- 5、使用注解的形式管理事务 -->
<tx:annotation-driven transaction-manager="txManager"/>

</beans>

4.MyBatis配置文件(和Hibernate的有点类似,当然这步可以注解方式实现,不过我觉得xml还是比较直观和简洁一些)Mybatis_Configuration.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<mappers>
<mapper resource="com/huaxun/smtest/domain/mapper/NoteMapper.xml"/>
</mappers>
</configuration>
5.Spring_mvc配置文件(类似于struts2的struts.xml,但这里并不配置action,而是springmvc的一些访问配置属性,如视图的存放位置前缀和后缀等)。

<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- 扫描controller的位置 -->
<context:component-scan base-package="com.huaxun.smtest.view.*" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<!-- 视图所处WebROOT文件目录 -->
<property name="prefix" value="/WEB-INF/pages/" />
<!-- jsp后缀 -->
<property name="suffix" value=".jsp" />
</bean>
<!-- Spring mvc 拦截器 -->
<!--权限控制 -->
<!-- <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<list>
<bean class="com.hb.lw.interceptor" />
</list>
</property>
</bean> -->

<!--文件上传 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1000000000" />
</bean>

<!-- 异常处理类 -->
<bean id="exceptionResolver"
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="defaultErrorView">
<value>/common/failure</value>
</property>
<property name="exceptionMappings">
<props>
<prop key="java.sql.SQLException">/common/failure</prop>
<prop key="java.lang.RuntimeException">/common/failure</prop>
</props>
</property>
</bean>
</beans>
6.Controller的编写demo。(如查询Note的所有列表,并用jsp+JSTL显示)

package com.huaxun.smtest.view.controller;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.huaxun.smtest.domain.Note;
import com.huaxun.smtest.service.NoteService;

/**
*  Class Name: NoteController.java
*  Function:
*
*  @author Yang Ji.
*  @DateTime 2015年6月28日 下午12:50:15
*  @version 1.0
*/
@Controller
public class NoteController {

@Resource(name=NoteService.SERVICE_NAME)
private NoteService noteService;

@RequestMapping("/nlist")
//	@RequestMapping( value = "nlist")
public ModelAndView list(){
//		System.out.println("test-----------");

List<Note> notes = noteService.queryForParam("note.selNotes");
ModelAndView mv = new ModelAndView("notes");
mv.addObject("notes", notes);
return mv;
}
}

7.Notes.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>信息列表</title>
</head>
<body>
<center>
<h1>信息列表</h1>
<c:if test="${not empty notes}">
<table border="1">
<tr><td width="10">id</td>
<td width="20">名称</td>
<td width="30">电话</td>
<td width="30">邮箱</td>
<td width="300">内容</td>
<td width="30">创建时间</td>
</tr>
<c:forEach items="${notes}" var="note">
<tr><td>${note.note_id}</td>
<td>${note.name}</td>
<td>${note.telephone}</td>
<td>${note.email}</td>
<td>${note.content}</td>
<td>${note.create_time}</td>
</tr>
</c:forEach>
</table>
</c:if>
</center>
</body>
</html>


8.调试成功后,访问http://localhost:8080/SpringmvcMyBatis/nlist

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: