利用Intellij+MAVEN搭建Spring+Mybatis+MySql+SpringMVC项目详解

利用Intellij+MAVEN搭建Spring+Mybatis+MySql+SpringMVC项目详解

这两天在公司实习,师父让我先熟悉Intellij软件的使用和SpringMVC框架。话不多说,先利用这些搭建一个小环境吧。

1 创建MAVEN项目:File-NEW-MAVEN-create from..前打勾--选下面的org.apache..archetypes:maven-archetype-webapp,点击next

                 后面的项目名称:

GroupId:项目的名称,
ArtiFactId:项目的模块名称(建议用项目名称-模块名称来表示),
Version:项目版本的名称
如:groupID:SpringMVC;ArtiFactId:SpringMVC-Demo,version:默认完成后,IDEA就自动给我们构建了一个空的maven项目.

利用Intellij+MAVEN搭建Spring+Mybatis+MySql+SpringMVC项目详解_第1张图片


2  配置pom.xml文件,这里利用标签导入需要的库。这里需要导入的有junit , spring , springmvc , mysql , mybatis , jstl等等,详见下面的配置文件:


  4.0.0
  MybatisTest
  MybatisTest-Demo1
  war
  1.0-SNAPSHOT
  MybatisTest-Demo1 Maven Webapp
  http://maven.apache.org
  
    
      junit
      junit
      3.8.1
      test
    

    
    
      mysql
      mysql-connector-java
      5.1.6
    

    
    
    
      org.springframework
      spring-aop
      4.3.5.RELEASE
    

    
    
      org.springframework
      spring-tx
      4.3.5.RELEASE
    


    
      org.springframework
      spring-beans
      4.3.1.RELEASE
    

    
      org.springframework
      spring-core
      4.3.1.RELEASE
    

    
      org.springframework
      spring-context
      4.3.1.RELEASE
    

    
    
      org.springframework
      spring-web
      4.3.1.RELEASE
    
    
      org.springframework
      spring-webmvc
      4.3.1.RELEASE
    

    
    
    
      javax.servlet
      jstl
      1.2
    

    
      taglibs
      standard
      1.1.2
    

    
    
      javax.servlet
      servlet-api
      2.5
    

    
    
      javax.servlet.jsp
      jsp-api
      2.2
    

    
    
      com.mchange
      c3p0
      0.9.5.1
    

    
    
      org.aspectj
      aspectjweaver
      1.8.6
    

    
      org.aspectj
      aspectjrt
      1.8.6
    

    
    
      org.springframework
      spring-jdbc
      3.0.5.RELEASE
    

    
    
      org.mybatis
      mybatis
      3.4.1
    
    
    
      org.mybatis
      mybatis-spring
      1.3.0
    
    
      junit
      junit
      RELEASE
    

  
    
      org.springframework
      spring-test
      3.2.3.RELEASE
      test
    
    
      org.springframework
      spring-test
      RELEASE
    

  
  
    MybatisTest-Demo1

    
      
      
        org.eclipse.jetty
        jetty-maven-plugin
        9.3.10.v20160621
      

      
      
        org.mybatis.generator
        mybatis-generator-maven-plugin
        1.3.2
        
          true
          true
        
      
      
        org.apache.maven.plugins
        maven-compiler-plugin
        
          1.7
          1.7
        
      
    

  


3 src下面新建java包,将其设置为source root(在java包上点击右键,选择Mark Directory As Source Root),依次建如图类结构:

利用Intellij+MAVEN搭建Spring+Mybatis+MySql+SpringMVC项目详解_第2张图片


1)创建接口EmployeeMapper.java,这里是采用Mybatis的注解的方式,要在后面的spring-mybatis文件中去注册接口

package com.mybatis.dao;

import com.mybatis.model.Employee;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * Created by wanggenshen_sx on 2016/12/26.
 */

public interface EmployeeMapper {
	@Select("select id,lastName,email from employee where id=#{id}")
	Employee getEmployeeById(int id);

	@Select("select * from employee")
	List getAllEmployees();
}

2)实体类:Employee.java

package com.mybatis.model;

/**
 * Created by wanggenshen_sx on 2016/12/23.
 */
public class Employee {

	private int id;
	private String lastName;
	private String email;

	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	@Override
	public String toString() {
		return "Employee [id=" + id + ", lastName=" + lastName + ", email="
				+ email+" ]" ;
	}
	public Employee(){}
}
3 ) Service层:

创建EmployeeService接口

package com.mybatis.service;

import com.mybatis.model.Employee;

import java.util.List;

/**
 * Created by wanggenshen_sx on 2016/12/26.
 */
public interface EmployeeService {
	Employee getEmployee(int id);

	List getEmployees();
}

创建EmployeeServiceImpl实现类:注意添加@Service注解

package com.mybatis.service;

import com.mybatis.dao.EmployeeMapper;
import com.mybatis.model.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by wanggenshen_sx on 2016/12/26.
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {

   public EmployeeServiceImpl() {
      System.out.printf("init EmployeeServiceImpl");
   }

   @Autowired
   private EmployeeMapper employeeMapper;

   @Override
   public Employee getEmployee(int id){
      return employeeMapper.getEmployeeById(id);
   }

   public List getEmployees(){
      return employeeMapper.getAllEmployees();
   }

}


4)在spring配置文件中整合mybatis:spring-mybatis.xml

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

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

    
    id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        name="driverClassName" value="com.mysql.jdbc.Driver"/>
        name="url" value="jdbc:mysql://localhost:3306/mytest"/>
        name="username" value="root"/>
        name="password" value="920614"/>
    

    
    id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        name="dataSource" ref="datasource"/>
        name="typeAliasesPackage" value="com.mybatis.model"/>
    

    
    id="config" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
       name="basePackage" value="com.mybatis.dao"/>
        name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    


    
    id="manager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        name="dataSource" ref="datasource"/>
    

    
    <tx:annotation-driven transaction-manager="manager" />

建测试类:EmployeeTest.java

package com.mybatis.test;

import com.mybatis.model.Employee;
import com.mybatis.service.EmployeeService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

/**
 * Created by wanggenshen_sx on 2016/12/27.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring-mybatis.xml" })
public class EmployeeTest {

   @Autowired
   private EmployeeService employeeService;

   @Test
   public void testGetEmployeeById(){
      Employee employee = employeeService.getEmployee(1);
      System.out.print(employee);
   }

   @Test
   public void testGetAll(){
      List employees=employeeService.getEmployees();
      System.out.print(employees);
   }
}

能输出并显示数据库表的内容,即表示Spring整合Mybatis成功,接下来加入SpringMVC内容,将读取的内容显示在页面上。


4 创建springmvc-servlet.xml,配置视图信息。

xml version="1.0" encoding="UTF-8"?>
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:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
      http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    
    <mvc:annotation-driven/>
    
    <mvc:default-servlet-handler/>

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

    
    id="viewResolverCommon" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        name="prefix" value="/WEB-INF/views/"/>
        name="suffix" value=".jsp"/>
        name="viewClass"  value="org.springframework.web.servlet.view.JstlView" />
    


5 建控制类:
EmployeeController.java

package com.mybatis.controller;

import com.mybatis.model.Employee;
import com.mybatis.service.EmployeeService;
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 java.util.List;
import java.util.Map;

/**
 * Created by wanggenshen_sx on 2016/12/26.
 */
@Controller
public class EmployeeController {

   @Autowired
   private EmployeeService employeeService;

   @RequestMapping(value="/listAll",method= RequestMethod.GET)
   public String list(Map,Object> map){
      List employees = employeeService.getEmployees();
       /*测试用
      if(employees==null)
         System.out.println("null");
      else
         System.out.println(employees);*/

      map.put("employees",employees);
      return "list";
   }


}

6 建立显示页面: Web-app的WEB-INF下建views包下建list.jsp:

注意此处一定要加上

	<%@ page isELIgnored="false" %>

否则无法使用jstl标签。


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: wanggenshen_sx
  Date: 2016/12/26
  Time: 17:25
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>


    </span>Show Page22<span style="color:rgb(232,191,106);">


                border="1" cellspacing="0" cellpadding="10">
                                                                                                                
                    <c:forEach items="${requestScope.employees}" var="emp">                                                                                                                                c:forEach>
                
ID LastName Email
${emp.id} ${emp.lastName} ${emp.email}


7 配置web.xml ,分别指定spring,springmvc配置文件的位置。注意这里一定要有四个部分,即,,,.

  我在这里没有添加标签,spring无法初始化,出现了【Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'employeeController': Unsatisfied dependency expressed through field 'employeeService': No qualifying bean of type [com.mybatis.service.EmployeeService] found for dependency [com.mybatis.service.EmployeeService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: 】错误。

web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >


  <context-param>
    contextConfigLocation
    classpath:spring-mybatis.xml
  context-param>
  
    org.springframework.web.context.ContextLoaderListener
  

  
  
    org.springframework.web.util.IntrospectorCleanupListener
  


  
  
    springmvc-servlet
    org.springframework.web.servlet.DispatcherServlet
    
      contextConfigLocation
      classpath:springmvc-servlet.xml
    
    1
  

  
    springmvc-servlet
    /
  


8 项目整体结构:

利用Intellij+MAVEN搭建Spring+Mybatis+MySql+SpringMVC项目详解_第3张图片


你可能感兴趣的:(SSM)