mybatis与SpringMVC集成

来源:互联网 发布:周潜川内经知要讲义 编辑:程序博客网 时间:2024/06/05 23:08

1、创建web项目。

2、配置web.xml文件,项目启动时自动加载Spring的配置文件,并且配置DispatcherServlet,拦截用户请求

<?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>Mybatis_SpringMVC</display-name><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list><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><servlet><servlet-name>mvc</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>mvc</servlet-name><url-pattern>/</url-pattern></servlet-mapping></web-app>
3、在web.xml同目录下配置mvc-servlet.xml文件,要注意:mvc-servlet.xml文件名中,-servlet.xml之前的部分(标红色),名称是自定的,但是必须要和web.xml中配置的DispatcherServlet的servlet-name属性的 值完全一致,否则会FileNotFoundException。

mvc-servlet.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"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"><mvc:annotation-driven /><context:component-scan base-package="com.cpf.controller" /><context:component-scan base-package="com.cpf.service" /><!-- 基于注解映射 --><beanclass="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /></beans>
配置<context:component-scan>,spring可以自动去扫描base-pack下面或者子包下面的java文件,如果扫描到有@Component @Controller@Service等这些注解的类,则把这些类注册为bean。

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"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.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://127.0.0.1:3306/mydb"></property><property name="user" value="root"></property><property name="password" value="root"></property></bean><!-- 实用Spring的会话管理 --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><!-- 要用到的数据源,上面配置的c3p0连接池 --><property name="dataSource" ref="dataSource"></property><!-- mybatis的配置文件 --><property name="configLocation" value="classpath:Configuration.xml"></property><!-- 自动导入所有的配置sql的xml文件 --><property name="mapperLocations" value="classpath*:com/cpf/entity/*.xml"></property></bean><!-- 配置静态资源的处理,不经过DispatcherServlet拦截 --><mvc:default-servlet-handler/><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.cpf"></property></bean>  <bean        class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <property name="prefix">            <value>/pages/</value>        </property>        <property name="suffix">            <value>.jsp</value>        </property>    </bean></beans>
mybatis的配置文件。

<?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>    <typeAliases>         <typeAlias alias="User" type="com.cpf.entity.User"/>         <typeAlias alias="Course" type="com.cpf.entity.Course"/>    </typeAliases> </configuration>
使用Spring 配置文件中<property name="mapperLocations" value="classpath*:com/cpf/entity/*.xml"></property>标签来自动导入所有的mapper.xml配置文件,就不需要在mybatis的配置文件中逐个配置<mappers><mapper resource="com/cpf/entity/User.xml"/>  </mappers>  了

4、Controller类。

在Controller中使用注解进行配置,就不需要在applicationContext.xml中配置每个Controller对应的bean,以及为bean的属性配置property标签,例如下面的配置可以不要。

<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"><property name="sqlSessionFactory" ref="sqlSessionFactory"></property><!--mapperInterface属性指定映射器接口,用于实现此接口并生成映射器对象 --><property name="mapperInterface" value="com.cpf.service.IUserService"></property></bean>
UserController.java

package com.cpf.controller;import java.io.UnsupportedEncodingException;import java.util.List;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.servlet.ModelAndView;import com.cpf.entity.User;import com.cpf.service.IUserService;@Controllerpublic class UserController {@Autowiredprivate IUserService userService;@RequestMapping(value="list", method=RequestMethod.GET)@ResponseBodypublic ModelAndView listAll(HttpServletRequest req, HttpServletResponse res) throws UnsupportedEncodingException{List<User> userList = userService.getUsers("%");//show对应jsp文件的名字ModelAndView mav = new ModelAndView("show");mav.addObject("userList", userList);return mav;}}

IUserService文件

package com.mybatis_spring.mapper;import java.util.List;import com.mybatis_spring.entity.Course;import com.mybatis_spring.entity.User;public interface IUserService {User getUserById(int id);List<User> getUsers(String username);void doAddUser(User user);void doUpdateUser(User user);void doDeleteUser(int id);List<Course> getCourseByUserId(int id);}

User.java,  User.xml等文件,和mtbatis学习1中用到的文件完全相同。

show.jsp文件。

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>用户列表</title></head><body><table border="1"><c:forEach items="${userList }" var="user"><tr><td>${user.id }</td><td>${user.name }</td><td>${user.age }</td><td>${user.address }</td></tr></c:forEach></table></body></html>


0 0
原创粉丝点击