林炳文Evankaka原创作品。转载请注明出处http://blog.csdn.net/evankaka
本文要实现spring+SpringMVC+Mybatis+MySQL的一个整合,实现了SpringMVC控制访问的页面,将得到的页面参数传递给Spring中的Mybatis的bean类,然后查找mysql数据的功能,并通过JSP显示出来。建议可以先看笔者另一文章Mybatis与Spring整合创建Web项目 。笔者觉得整合过程中问题比较多的还是Spring+Mybatis的整合,SpringMVC的整合还是比较简单。
Spring
Spring 是一个开源框架, Spring 是于 2003 年兴起的一个轻量级的 Java 开发框架,由 Rod Johnson 在其著作 Expert One-On-One J2EE Development and Design 中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。 Spring 使用基本的 JavaBean 来完成以前只可能由 EJB 完成的事情。然而, Spring 的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何 Java 应用都可以从 Spring 中受益。 简单来说, Spring 是一个轻量级的控制反转( IoC )和面向切面( AOP )的容器框架。
SpringMVC
Spring MVC 属于 SpringFrameWork 的后续产品,已经融合在 Spring Web Flow 里面。 Spring MVC 分离了 控制器 、模型 对象 、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制。
MyBatis
MyBatis 本是 apache 的一个开源项目 iBatis , 2010 年这个项目由 apache software foundation 迁移到了 google code ,并且改名为 MyBatis 。 MyBatis 是一个基于 Java 的 持久层 框架。 iBATIS 提供的 持久层 框架包括 SQL Maps 和 Data Access Objects ( DAO ) MyBatis 消除了几乎所有的 JDBC 代码和参数的手工设置以及结果集的检索。 MyBatis 使用简单的 XML 或注解用于配置和原始映射,将接口和 Java 的 POJOs ( Plain Old JavaObjects ,普通的 Java 对象)映射成数据库中的记录。
使用的版本:Mybatis-3.2.8
Spring3.2.9
SpringMVC 3.2.9
Mysql5.6
开发环境: Eclipse java EE Kepler+Win7
一、创建Web项目
最终整个工程目录如下:
![](https://img-blog.csdn.net/20150517173353200)
需要导入的包
![](https://img-blog.csdn.net/20150517173543629)
二、创建库表映射类并配置MyBatis
1、首先在数据库中创建一张表 t_user
- use test;
- DROP TABLE IF EXISTS t_user;
- create table t_user
- (
- userId int primary key auto_increment,
- userName VARCHAR(50) not null,
- userAge int not null
- );
然后插入4条数据:
- insert into t_user values(1,'小王',10);
- insert into t_user values(2,'红红',11);
- insert into t_user values(3,'明明',12);
- insert into t_user values(4,'天天',13);
查看下结果:
![](https://img-blog.csdn.net/20150517180237109)
2、表创建好之后便创建其映射类User,位于包com.mucfc.model中
- package com.mucfc.model;
-
-
-
-
-
- public class User {
- private Integer userId;
- private String userName;
- private int userAge;
- public Integer getUserId() {
- return userId;
- }
- public void setUserId(Integer userId) {
- this.userId = userId;
- }
- public String getUserName() {
- return userName;
- }
- public void setUserName(String userName) {
- this.userName = userName;
- }
- public int getUserAge() {
- return userAge;
- }
- public void setUserAge(int userAge) {
- this.userAge = userAge;
- }
- @Override
- public String toString() {
- return "User [userId=" + userId + ", userName=" + userName
- + ", userAge=" + userAge + "]";
- }
-
- }
2、映射类创建好之后便创建MyBatis映射文件(即Mapper文件),位于和src同级的conf的mapper包中,文件内容如下:
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mapper namespace="com.mucfc.mapper.UserMapper">
-
- <select id="selectUserById" parameterType="int" resultType="User">
- select * from t_user where userId = #{userId}
- </select>
- </mapper>
3、创建映射UserMapper类如下,位于包com.mucfc.mapper中
- package com.mucfc.mapper;
-
- import com.mucfc.model.User;
-
-
-
-
-
- public interface UserMapper {
- public User selectUserById(int userId);
-
- }
4、创建操作数据的DAO层
- package com.mucfc.dao;
-
- import com.mucfc.model.User;
-
-
-
-
-
- public interface UserDao {
-
-
-
-
-
- public User findUserById(int id);
- }
然后是对应的实现层
- package com.mucfc.dao;
-
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Component;
- import com.mucfc.mapper.UserMapper;
- import com.mucfc.model.User;
-
-
-
-
-
- @Component
- public class UserDaoImpl implements UserDao{
- @Autowired
- private UserMapper userMapper;
- @Override
- public User findUserById(int id) {
- User user = userMapper.selectUserById(id);
- return user;
- }
-
- }
5、在conf里配置Mybatis的配置文件:
MyBatisConf.xmll放在conf里,注意路径
- <?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.mucfc.model.User"/>
- </typeAliases>
- <!-- 配置Mapper文件的路径 -->
- <mappers>
- <mapper resource="mapper/UserMapper.xml"/>
- </mappers>
- </configuration>
如果不与Spring进行整合的话,此配置文件还需要配置数据源信息,与Spring整合之后数据源就配置在Spring配置文件中,只需要配置映射文件的路径就可以了。
三、配置Spring
1、在conf里创建Spring的配置文件:(conf是和src同级的文件夹)
SpringConf.xml放在conf里,注意路径
- <?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"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.2.xsd">
-
- <bean id="dataSource"
- class="org.springframework.jdbc.datasource.DriverManagerDataSource">
- <property name="driverClassName" value="com.mysql.jdbc.Driver" />
- <property name="url" value="jdbc:mysql://localhost:3306/test" />
- <property name="username" value="root" />
- <property name="password" value="christmas258@" />
- </bean>
-
-
- <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
- <property name="dataSource" ref="dataSource" />
- <property name="configLocation" value="classpath:MyBatisConf.xml" />
- <!-- <property name="typeAliasesPackage" value="com.tiantian.ckeditor.model"
- /> -->
- </bean>
-
- <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
- <property name="mapperInterface"
- value="com.mucfc.mapper.UserMapper" />
- <property name="sqlSessionFactory" ref="sqlSessionFactory" />
- </bean>
-
- <context:component-scan base-package="com.mucfc.dao" />
-
- </beans>
2、web.xml中启动Spring
web.xml放在WEB-INF里
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
-
- <!-- <welcome-file-list>
- <welcome-file>index.html</welcome-file>
- <welcome-file>index.htm</welcome-file>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list> -->
-
-
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:SpringConf.xml</param-value>
- </context-param>
-
- </web-app>
其实到这里就完成了Spring+Mybatis的配置中,可以在JSP中通过Spring中创建的bean来操作数据 库了
四、配置SpringMVC
1、首先应该先更改web.xml,在里面设置拦截的内容
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
-
- <!-- <welcome-file-list>
- <welcome-file>index.html</welcome-file>
- <welcome-file>index.htm</welcome-file>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list> -->
-
-
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:SpringConf.xml</param-value>
- </context-param>
-
-
- <servlet>
- <servlet-name>MyDispatcher</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>MyDispatcher</servlet-name>
-
- <url-pattern>/</url-pattern>
- </servlet-mapping>
-
-
-
- <filter>
- <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
-
- </web-app>
2、在conf里创建SpringMVC的配置文件:(conf是和src同级的文件夹)
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:util="http://www.springframework.org/schema/util" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
- xsi:schemaLocation="
- http://www.springframework.org/schema/util
- http://www.springframework.org/schema/util/spring-util-3.2.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.2.xsd">
- <mvc:annotation-driven/>
-
- <context:component-scan base-package="com.mucfc.controller" />
-
- <bean
- class="org.springframework.web.servlet.view.InternalResourceViewResolver"
- p:prefix="/WEB-INF/views/" p:suffix=".jsp" />
-
-
- </beans>
3、注解@conroller类的实现
com.mucfc.controller包下新建UserController.java
- package com.mucfc.controller;
-
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
-
- @Controller
- public class UserController {
- @RequestMapping(value="/findUser",method = RequestMethod.POST)
- public String getUser(){
- return "findUser";
- }
- @RequestMapping("/")
- public String getIndex(){
- return "index";
- }
-
- }
根据浏览器输入的网址,定位到不同的页面中去
五、JSP页面创建
由于SpringMVC配置了p:prefix="/WEB-INF/views/" p:suffix=".jsp" /。。。
所以要在WEB-INF中创建文件夹views,然后在这里放置JSP文件
首先是index.jsp
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme() + "://"
- + request.getServerName() + ":" + request.getServerPort()
- + path + "/";
- %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <title>查找用户信息</title>
- <base href="<%=basePath%>">
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- </head>
- <body>
- <center>
- <form action="findUser" method="post">
- 请输入用户ID:<input type="text" name="id">
- <input type="submit" value="确定">
- </form>
- </center>
- </body>
- </html>
将数据传递给findUser.jsp
findUser.jsp内容如下
- <%@ page import="com.mucfc.dao.UserDao"%>
- <%@page import="org.springframework.web.context.WebApplicationContext"%>
- <%@page import="org.springframework.web.context.support.WebApplicationContextUtils"%>
- <%@ page language="java" contentType="text/html" pageEncoding="UTF-8"%>
-
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <title>Insert title here</title>
- </head>
- <body>
- <center>
- 通过controller访问<br/>
- 欢迎<br/>
- <%
- WebApplicationContext wac = WebApplicationContextUtils
- .getWebApplicationContext(this.getServletContext());
- UserDao userDao = (UserDao) wac.getBean("userDaoImpl");
- String in=(String)request.getParameter("id");
- System.out.println(in);
- int num=Integer.parseInt(in);
- %>
- <%=userDao.findUserById(num)%><br />
- <%-- <%=userDao.findUserById(2)%><br />
- <%=userDao.findUserById(3)%><br />
- <%=userDao.findUserById(4)%><br /> --%>
- </center>
- </body>
- </html>
根据 输入的id,来查找数据库中是否有这个人
六、运行
输入1
![](https://img-blog.csdn.net/20150517180106585)
结果表明这个人存在
![](https://img-blog.csdn.net/20150517180121172)
输入5,不存在这个人
![](https://img-blog.csdn.net/20150517180238641)
林炳文Evankaka原创作品。转载请注明出处http://blog.csdn.net/evankaka