搭建maven+springmvc+mybatis

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了搭建maven+springmvc+mybatis相关的知识,希望对你有一定的参考价值。


首先说明一下,搭建springmvc+mybatis整整花费了两天的功夫,主要问题就是jar包冲突、配置文件有误等问题,也有教程本身可能存在问题,因此本次就重新搭建了一次。

搭建maven+springmvc+mybatis_xml

首先看一下目录结构,这个就是完整的maven+springmvc+mybatis目录。


第一步:使用maven搭建springmvc动态网站

搭建maven+springmvc+mybatis_spring_02

搭建maven+springmvc+mybatis_xml_03

搭建maven+springmvc+mybatis_xml_04

【注意】在完成后,还需要手动进入工程文件夹,从跟目录src开始新建三个文件夹

main/java

test/java

test/resources


刷新项目工程,就成为了动态web项目。


第二步:新建springmvc+mybatis

在完成动态web的搭建后,现在要加入springmvc和mybatis项目的支持。pom.xml文件如下:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>jianghuiwen.youhua</groupId>
<artifactId>springmvc</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>springmvc Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<springversion>3.1.1.RELEASE</springversion>
<junitversion>3.8.1</junitversion>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>

<!-- mybatis核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.3.0</version>
</dependency>
<!-- mybatis/spring包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<!-- 导入mysql数据库链接jar包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>$springversion</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>$springversion</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>$springversion</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>$springversion</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>$springversion</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-dao</artifactId>
<version>2.0.8</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>$springversion</version>
</dependency>
</dependencies>
<build>
<finalName>springmvc</finalName>
</build>
</project>


web.xml中增加对springmvc和mybatis的启动支持

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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_3_0.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<!-- Spring的log4j监听器 -->
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>

<!-- 核心控制器 -->
<servlet>
<servlet-name>book</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<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-mapping>
<servlet-name>book</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

</web-app>


spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

<mvc:annotation-driven />
<context:component-scan base-package="click.youhua.*" />

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>

<mvc:interceptors>
<!-- 使用bean定义一个Interceptor,直接定义在mvc:interceptors根下面的Interceptor将拦截所有的请求 -->
<mvc:interceptor>
<mvc:mapping path="/index.do/**"/>
<!-- 定义在mvc:interceptor下面的表示是对特定的请求才进行拦截的 -->
<bean class="click.youhua.interceptor.LoginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>


</beans>


对日志的支持log4j.properties:

#定义LOG输出级别
log4j.rootLogger=INFO,Console,File
#定义日志输出目的地为控制台
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
#可以灵活地指定日志输出格式,下面一行是指定具体的格式
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n

#文件大小到达指定尺寸的时候产生一个新的文件
log4j.appender.File = org.apache.log4j.RollingFileAppender
#指定输出目录
log4j.appender.File.File = logs/ssm.log
#定义文件最大大小
log4j.appender.File.MaxFileSize = 10MB
# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%dyyyy-MM-dd HH\\:mm\\:ss][%c]%m%n


mybatis的支持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:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:p="http://www.springframework.org/schema/p" 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/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">


<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1:3306/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>

<!-- 配置事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- configLocation:用于指定Mybatis的配置文件位置 -->
</bean>

<context:annotation-config />


<tx:annotation-driven />

<!--
自动扫描和注册Mapper接口
basePackage是用来指定Mapper接口文件所在的基包,
在这个基包或其所有子包下面的Mapper接口都将被搜索到。
多个基包之间可以使用逗号或者分号进行分隔
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="
click.youhua.mapper
" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>

</beans>


上面就是配置文件,下面就是mybatis对于数据库的操作接口

/springmvc/src/main/java/click/youhua/mapper/StudentMapper.java

package click.youhua.mapper;

import click.youhua.model.Student;
/*
* mybatis接口,完成对数据库的映射,即在service层调用该接口的时候,直接可以操作对应的Mapper.xml中的SQL语句
* 因此要求该类名需要和数据库映射文件名字相同.例如:StudentMapper.java -- studentMapper.xml
* */
public interface StudentMapper
public Student findById(Long id);
public void addStudent(Student student);

studentMapper.xml

<?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="click.youhua.mapper.StudentMapper">
<select id="findById" resultType="click.youhua.model.Student">
select id, name , age from student where id = #id limit 1
</select>
<insert id="addStudent" parameterType="click.youhua.model.Student">
insert into student(name, age) values(#name, #age)
</insert>
</mapper>


完成上面的配置后,就可以配置service层和controller层了。

/springmvc/src/main/java/click/youhua/service/impl/StudentServiceImpl.java

package click.youhua.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import click.youhua.mapper.StudentMapper;
import click.youhua.model.Student;
import click.youhua.service.StudentService;


@Service("studentService")
public class StudentServiceImpl implements StudentService
@Resource
private StudentMapper studentMapper;
@Override
public Student findById(Long id)
return studentMapper.findById(id);

@Override
public void addStudent(Student student)
studentMapper.addStudent(student);


/springmvc/src/main/java/click/youhua/controller/IndexController.java

package click.youhua.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import click.youhua.model.Student;
import click.youhua.service.StudentService;


@Controller
@RequestMapping(value = "/index")
public class IndexController

@Autowired
private StudentService studentService;

@RequestMapping(value="/list")
public ModelAndView list()
System.out.println("index...");
Map<String,Object> data = new HashMap<String,Object>();
data.put("name",studentService.findById(3L).getName());
return new ModelAndView("index",data);


@RequestMapping(value = "/add")
public String add()
System.out.println("add...");
Student student = new Student();
student.setId(3L);
student.setName("hongwen");
student.setAge(20L);
studentService.addStudent(student);
return "index";



当然,我还多加了一个拦截器,拦截器没做什么。

/springmvc/src/main/java/click/youhua/interceptor/LoginInterceptor.java

package click.youhua.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class LoginInterceptor implements HandlerInterceptor

@Override
public void afterCompletion(HttpServletRequest arg0,
HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception



@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, ModelAndView arg3) throws Exception



@Override
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2) throws Exception
System.out.println("拦截器拦截啦!");
return false;



【注意】我的数据库表很简单,就是一个数据库名:test,数据库表:student 字段:id name age。

启动tomcat访问,可以看到:

搭建maven+springmvc+mybatis_xml_05

以上是关于搭建maven+springmvc+mybatis的主要内容,如果未能解决你的问题,请参考以下文章

maven+springMVC+mybatis 搭建过程

使用intellij idea搭建MAVEN+springmvc+mybatis框架

Maven搭建SpringMVC+Mybatis项目详解

Maven搭建SpringMVC+Mybatis项目详解

Maven搭建SpringMVC+Mybatis项目详解

使用intellij idea搭建MAVEN+springmvc+mybatis框架