搭建基于SpringMVC+MyBatis+Maven的web项目

一 开发前准备

1.1 开发环境

Jdk1.6

MyEclipse 10

Tomcat7

MySQL5

1.2 创建表

CREATE TABLE `user` (  

  `ID` int(11) NOT NULL AUTO_INCREMENT,  

  `NAME` char(30) NOT NULL,  

  `PASSWORD` char(30) NOT NULL,  

  PRIMARY KEY (`ID`),  

  KEY `IDX_NAME` (`NAME`)  

) ENGINE=InnoDB DEFAULT CHARSET=utf8

1.3 插入测试数据

INSERT INTO user (ID, NAME, PASSWORD) VALUES (1, 'admin', '123456');  

INSERT INTO user (ID, NAME, PASSWORD) VALUES (2, '张三', '88888');  

INSERT INTO user (ID, NAME, PASSWORD) VALUES (3, '李四', '[email protected]');  

二 创建项目

File->New->Other

 搭建基于SpringMVC+MyBatis+Maven的web项目_第1张图片

 搭建基于SpringMVC+MyBatis+Maven的web项目_第2张图片

 搭建基于SpringMVC+MyBatis+Maven的web项目_第3张图片

 

 

 

 

添加文件夹

src/main/java

src/main/resources

src/test/java

src/test/resources

 搭建基于SpringMVC+MyBatis+Maven的web项目_第4张图片

 

 

检查以下3处的jdk版本,保持一致

 搭建基于SpringMVC+MyBatis+Maven的web项目_第5张图片

 搭建基于SpringMVC+MyBatis+Maven的web项目_第6张图片

 搭建基于SpringMVC+MyBatis+Maven的web项目_第7张图片

 

三 配置POM文件

<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/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0modelVersion>

<groupId>com.kittygroupId>

<artifactId>testartifactId>

<version>0.0.1-SNAPSHOTversion>

<packaging>warpackaging>

<properties>

<spring.version>3.2.8.RELEASEspring.version>

<slf4j.version>1.6.6slf4j.version>

<log4j.version>1.2.12log4j.version>

<junit.version>4.10junit.version>

<mybatis.version>3.2.1mybatis.version>

properties>

 

<dependencies>

<dependency>

<groupId>org.springframeworkgroupId>

<artifactId>spring-coreartifactId>

<version>${spring.version}version>

dependency>

<dependency>

<groupId>org.springframeworkgroupId>

<artifactId>spring-webmvcartifactId>

<version>${spring.version}version>

dependency>

<dependency>

<groupId>org.springframeworkgroupId>

<artifactId>spring-contextartifactId>

<version>${spring.version}version>

dependency>

<dependency>

<groupId>org.springframeworkgroupId>

<artifactId>spring-context-supportartifactId>

<version>${spring.version}version>

dependency>

<dependency>

<groupId>org.springframeworkgroupId>

<artifactId>spring-aopartifactId>

<version>${spring.version}version>

dependency>

<dependency>

<groupId>org.springframeworkgroupId>

<artifactId>spring-aspectsartifactId>

<version>${spring.version}version>

dependency>

<dependency>

<groupId>org.springframeworkgroupId>

<artifactId>spring-txartifactId>

<version>${spring.version}version>

dependency>

<dependency>

<groupId>org.springframeworkgroupId>

<artifactId>spring-jdbcartifactId>

<version>${spring.version}version>

dependency>

<dependency>

<groupId>org.springframeworkgroupId>

<artifactId>spring-webartifactId>

<version>${spring.version}version>

dependency>

<dependency>

<groupId>junitgroupId>

<artifactId>junitartifactId>

<version>${junit.version}version>

<scope>testscope>

dependency>

<dependency>

<groupId>log4jgroupId>

<artifactId>log4jartifactId>

<version>${log4j.version}version>

dependency>

<dependency>

<groupId>org.slf4jgroupId>

<artifactId>slf4j-apiartifactId>

<version>${slf4j.version}version>

dependency>

<dependency>

<groupId>org.slf4jgroupId>

<artifactId>slf4j-log4j12artifactId>

<version>${slf4j.version}version>

dependency>

<dependency>

<groupId>org.springframeworkgroupId>

<artifactId>spring-testartifactId>

<version>${spring.version}version>

<scope>testscope>

dependency>

<dependency>

<groupId>org.mybatisgroupId>

<artifactId>mybatisartifactId>

<version>${mybatis.version}version>

dependency>

<dependency>

<groupId>org.mybatisgroupId>

<artifactId>mybatis-springartifactId>

<version>1.2.0version>

dependency>

<dependency>

<groupId>mysqlgroupId>

<artifactId>mysql-connector-javaartifactId>

<version>5.1.29version>

dependency>

<dependency>

<groupId>commons-dbcpgroupId>

<artifactId>commons-dbcpartifactId>

<version>1.2.2version>

dependency>

<dependency>

<groupId>javaxgroupId>

<artifactId>javaee-apiartifactId>

<version>6.0version>

<scope>providedscope>

dependency>

<dependency>

<groupId>javaxgroupId>

<artifactId>javaee-web-apiartifactId>

<version>6.0version>

<scope>providedscope>

dependency>

<dependency>

<groupId>com.fasterxml.jackson.coregroupId>

<artifactId>jackson-databindartifactId>

<version>2.7.4version>

dependency>

<dependency>

<groupId>com.fasterxml.jackson.coregroupId>

<artifactId>jackson-coreartifactId>

<version>2.7.4version>

dependency>

<dependency>

<groupId>com.fasterxml.jackson.coregroupId>

<artifactId>jackson-annotationsartifactId>

<version>2.7.4version>

dependency>

dependencies>

project>

 

 

四 SpringMyBatis集成

 

Spring配置文件application.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:jee="http://www.springframework.org/schema/jee" xmlns:p="http://www.springframework.org/schema/p"

xsi:schemaLocation="    

           http://www.springframework.org/schema/beans    

           http://www.springframework.org/schema/beans/spring-beans-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/context    

           http://www.springframework.org/schema/context/spring-context-3.0.xsd

           http://www.springframework.org/schema/util

   http://www.springframework.org/schema/util/spring-util-3.1.xsd">

 

<context:component-scan base-package="com.kitty.service" />    

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"

        destroy-method="close">

        <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="root" />

        

        <property name="maxActive" value="60" />

        

        <property name="maxIdle" value="60" />

         

        <property name="minIdle" value="5" />          

               

        <property name="initialSize" value="1" /> 

          

        <property name="maxWait" value="30000" />  

    bean>

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

<property name="dataSource" ref="dataSource" />

<property name="mapperLocations" value="classpath*:com/kitty/mapper/**/*.xml" />

bean>

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

<property name="basePackage" value="com.kitty.dao" />

<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />

Modeluser.java

package com.kitty.model;

 

public class User {

private Integer id;  

    private String name;  

    private String password;    

  

    public Integer getId() {  

        return id;  

    }  

  

    public void setId(Integer Id) {  

        this.id = Id;  

    }  

  

    public String getName() {  

        return name;  

    }  

  

    public void setName(String Name) {  

        this.name = Name;  

    }  

  

    public String getPassword() {  

        return password;  

    }  

  

    public void setPassword(String Password) {  

        this.password = Password;  

    }  

}

 

DaoUserDao.java

package com.kitty.dao;

 

import com.kitty.model.User;

 

public interface UserDao {

public User selectUserById(Integer userId); 

}

MyBatis配置映射文件mapper.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="com.kitty.dao.UserDao">  

  

    <resultMap id="BaseResultMap" type="com.kitty.model.User">  

        <id column="ID" property="id" jdbcType="INTEGER" />  

        <result column="NAME" property="name" jdbcType="CHAR" />  

        <result column="PASSWORD" property="password" jdbcType="CHAR" /> 

    resultMap>  

      

    <select id="selectUserById" parameterType="int" resultMap="BaseResultMap">  

        SELECT * FROM user WHERE ID = #{userId}  

    select>  

mapper>  

Service层接口UserService.java

package com.kitty.service;

import com.kitty.model.User;   

 

public interface UserService { 

    User selectUserById(Integer userId);    

Service层实现类UserServiceImpl.java

package com.kitty.service;

 

import org.springframework.beans.factory.annotation.Autowired;  

import org.springframework.stereotype.Service;  

  

import com.kitty.dao.UserDao;

import com.kitty.model.User;  

 

@Service  

public class UserServiceImpl implements UserService{  

    @Autowired  

    private UserDao userDao;  

  

    public User selectUserById(Integer userId) {  

        return userDao.selectUserById(userId);  

          

    }   

}  

 

 

 

五 集成SpringMVC

Web项目配置文件web.xml

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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

id="WebApp_ID" version="2.5">

 

<welcome-file-list>

<welcome-file>index.jspwelcome-file>

welcome-file-list>

<context-param>

<param-name>webAppRootKeyparam-name>

<param-value>webapp.rootparam-value>

context-param>

<context-param>

<param-name>contextConfigLocationparam-name>

<param-value>classpath:application.xmlparam-value>

context-param>

<listener>

<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>

listener>

<filter>

<filter-name>SpringEncodingFilterfilter-name>

<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>

<init-param>

<param-name>encodingparam-name>

<param-value>UTF-8param-value>

init-param>

<init-param>

<param-name>forceEncodingparam-name>

<param-value>trueparam-value>

init-param>

filter>

<filter-mapping>

<filter-name>SpringEncodingFilterfilter-name>

<url-pattern>/*url-pattern>

filter-mapping>

<context-param>

<param-name>log4jConfigLocationparam-name>

<param-value>classpath:log4j.propertiesparam-value>

context-param>

<context-param>

<param-name>log4jRefreshIntervalparam-name>

<param-value>60000param-value>

context-param>

<listener>

<listener-class>org.springframework.web.util.Log4jConfigListenerlistener-class>

listener>

<servlet>

<servlet-name>dispatcherServletservlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>

<init-param>

<param-name>contextConfigLocationparam-name>

<param-value>classpath:spring-mvc.xmlparam-value>

init-param>

<load-on-startup>1load-on-startup>

servlet>

<servlet-mapping>

<servlet-name>dispatcherServletservlet-name>

<url-pattern>/url-pattern>

servlet-mapping>

web-app>

SpringMVC配置文件spring-mvc.xml

xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:context="http://www.springframework.org/schema/context"

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.2.xsd  

    http://www.springframework.org/schema/context  

    http://www.springframework.org/schema/context/spring-context-3.2.xsd  

    http://www.springframework.org/schema/mvc  

    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

 

<context:component-scan base-package="com.kitty.controller" />

 

<bean id="viewResolver"

class="org.springframework.web.servlet.view.InternalResourceViewResolver"

p:prefix="/WEB-INF/view/" p:suffix=".jsp" />

beans> 

日志配置文件log4j.properties

log4j.rootLogger=DEBUG,Console,Stdout  

  

log4j.appender.Console=org.apache.log4j.ConsoleAppender  

log4j.appender.Console.layout=org.apache.log4j.PatternLayout  

log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n  

  

log4j.logger.java.sql.ResultSet=INFO  

log4j.logger.org.apache=INFO  

log4j.logger.java.sql.Connection=DEBUG  

log4j.logger.java.sql.Statement=DEBUG  

log4j.logger.java.sql.PreparedStatement=DEBUG 

 

log4j.appender.Stdout = org.apache.log4j.DailyRollingFileAppender    

log4j.appender.Stdout.File = ${webapp.root}/WEB-INF/logs/sample.log    

log4j.appender.Stdout.Append = true    

log4j.appender.Stdout.Threshold = DEBUG     

log4j.appender.Stdout.layout = org.apache.log4j.PatternLayout    

log4j.appender.Stdout.layout.ConversionPattern =%-d{yyyy-MM-dd HH\:mm\:ss}  [ %t\:%r ] - [ %p ]  %m%n  

ControllerUserController.java

package com.kitty.controller;  

  

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;  

import org.springframework.web.bind.annotation.RequestMapping;  

import org.springframework.web.servlet.ModelAndView;  

  

import com.kitty.model.User;  

import com.kitty.service.UserService;  

  

@Controller  

public class UserController {  

@Autowired  

    private UserService userService;  

      

    @RequestMapping("/")    

    public ModelAndView getIndex(){      

        ModelAndView mav = new ModelAndView("index");   

        User user = userService.selectUserById(1);  

        mav.addObject("user", user);   

        return mav;    

    }    

Viewindex.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>  

<html>  

<body>    

 ${user.id}<br>  

 ${user.name}<br>  

 ${user.password}<br>    

body>  

html> 

 

 

六 测试

整个项目文件结构如下

 搭建基于SpringMVC+MyBatis+Maven的web项目_第8张图片

 

打开浏览器访问http://localhost:8080/test/

访问结果

 搭建基于SpringMVC+MyBatis+Maven的web项目_第9张图片

 

 

你可能感兴趣的:(java)