1. 程式人生 > >springMVC+spring+MyBatis(SSM)的簡單配置

springMVC+spring+MyBatis(SSM)的簡單配置

ram web 調用 定制 troy mls param border 並不會

SSM(Spring+SpringMVC+MyBatis)框架集由Spring、SpringMVC、MyBatis三個開源框架整合而成,常作為數據源較簡單的web項目的框架。

其中:

Spring是一個輕量級的控制反轉(IOC)和面向切面(AOP)的容器框架。

SpringMVC分離了模型對象(Model)、視圖(View)、控制器(Controller),這種分離讓它們更容易進行定制。

MyBatis是一個支持普通SQL查詢,存儲過程和高級映射的優秀持久層框架。

今天,就帶領大家見證基礎,進行SSM的學習。

在此之前呢,首先要引入的是系統分層

如何分層呢

表示層(UI):數據展現 / 操作界面,請求分發(總所周知的MVC 是表示層的架構思想)。

持久層(服務層):封裝業務邏輯處理。

持久層(數據訪問層):封裝數據訪問邏輯。

而各層之間的關系呢,表示層通過接口調用業務層,業務層通過接口調用持久層。之所以引入系統分層的概念,主要的原因是:當下一層的實現發生改變的時候,並不會影響下一層。

敘述的就是這些了,開始我們的項目了

首先創建一個maven項目,格局如下:

技術分享圖片

1.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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.ninemax</groupId>
  <artifactId>springMVC-test2</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
   
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>
   
   <dependencies>
  
       <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>4.1.2.RELEASE</version>
      </dependency>
      
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc14</artifactId>
            <version>10.2.0.3.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.8</version>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>
        
        <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>jstl</artifactId>
          <version>1.2</version>
      </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.2</version>
        </dependency>
   </dependencies>
</project>
View Code

2.User.java

技術分享圖片
package com.nine.entity;

public class User {

    private String name;
    private Integer age;
    private String gender;
    private Double salary;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    
public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Double getSalary() { return salary; } public void setSalary(Double salary) { this.salary = salary; } @Override public String toString() { return "User [name=" + name + ", age=" + age + ", gender=" + gender + ", salary=" + salary + "]"; } }
View Code

3.UserDao.java

技術分享圖片
package com.nine.dao;

import java.util.List;

import com.nine.entity.User;

public interface UserDao {
    List<User> findAll();
}
View Code

4.UserMapper.xml

技術分享圖片
<?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"      
 "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">

<mapper namespace="com.nine.dao.UserDao">
   
   <select id="findAll" resultType="com.nine.entity.User">
        SELECT * FROM T_USER 
   </select>

</mapper>
View Code

5.UserService.java

技術分享圖片
package com.nine.service;

import java.util.List;

import com.nine.entity.User;

public interface UserService {

    List<User> userList();
}
View Code

6.UserServiceImpl

技術分享圖片
package com.nine.service;

import java.util.List;

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

import com.nine.dao.UserDao;
import com.nine.entity.User;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    public List<User> userList() {
        List<User> list = userDao.findAll();
        return list;
    }

}
View Code

7.UserController

技術分享圖片
package com.nine.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.nine.entity.User;
import com.nine.service.UserService;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/hello")
    public String hello(HttpServletRequest request) {
        List<User> list = new ArrayList<User>();
        try {
            list = userService.userList();
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
        request.setAttribute("list", list);
        return "hello";
    }
}
View Code

8.application.properties

spring.datasource.url=jdbc:oracle:thin:@10.21*.4.2*:1521:orcl
spring.datasource.username=*
spring.datasource.password=*
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver

9.spring-mvc.xml (這是springMVC重要的配置文件,前往不能忽略)

技術分享圖片
<?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:jdbc="http://www.springframework.org/schema/jdbc"  
    xmlns:jee="http://www.springframework.org/schema/jee" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    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/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
        
    <!-- 配置組件掃描 -->
    <context:component-scan base-package="com.nine"/>
    <!-- 配置MVC註解掃描 -->
    <mvc:annotation-driven/>
    
    <!-- 配置視圖解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <util:properties id="application" location="classpath:application.properties"/>
     <bean id="ds" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="#{application[‘spring.datasource.driver-class-name‘]}"/>
        <property name="url" value="#{application[‘spring.datasource.url‘]}"/>
        <property name="username" value="#{application[‘spring.datasource.username‘]}"/>
        <property name="password" value="#{application[‘spring.datasource.password‘]}"/>
     </bean>
    
     
     <!-- 配置SqlSessionFactoryBean -->
     <!--
        該bean的作用是用來代替MyBatis配置文件 
      -->
      <bean  class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 指定連接池 -->
        <property name="dataSource" ref="ds"/>
        <!-- 指定映射文件位置 -->
        <property name="mapperLocations" value="classpath:com/nine/dao/*.xml"/>
      </bean>
      <!-- 配置MapperScannerConfigurer -->
      <!--
          該bean會掃描指定包及其子包下面的所有的Mapper映射器(接口),然後生成符合該接口要求的對象
          (通過調用SqlSession的getMapper方法),接下來,會將這些對象(即Mapper映射器的實現對象)添加
          到Spring容器裏面(默認的id是首字母小寫之後的接口名) 
       -->
       <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
          <!-- 指定要掃描的包 -->
          <property name="basePackage" value="com.nine.dao"/>
       </bean>
</beans>
View Code

10.記住了!還有一個地方 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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <display-name>springMVC-test2</display-name>
 <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    
</web-app>
View Code

接下來就是簡單的一些靜態頁面了,這裏我沒有做太好的描述,只有一些簡單的頁面供大家參考

hello.jsp

技術分享圖片
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page import="java.util.*" language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
    <head>
        <title>list</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel="stylesheet" type="text/css" href="css/style.css" />
    </head>
    <body>
        
                    <h1>
                        列表
                    </h1>
                    <table border="1px" cellspacing="0px" style="border-collapse:collapse">
                        <tr>
                            <td>
                                姓名
                            </td>
                            <td>
                                年齡
                            </td>
                            <td>
                                性別
                            </td>
                            <td>
                                薪資
                            </td>
                        </tr>
                        
                            <c:forEach items="${list}" var="e" varStatus="s">
                                 <tr> 
                                    <td>${e.name}</td>
                                    <td>${e.age }</td>
                                    <td>${e.gender }</td>
                                    <td>${e.salary}</td>
                                 </tr>
                            </c:forEach>                    
         </table>
    </body>
</html>
View Code

error.jsp

技術分享圖片
<%@page pageEncoding="utf-8" contentType="text/html; charset=utf-8"%>
<html>
   <head></head>
   <body style="font-size:30px;">
                           系統繁忙,稍後重試
   </body>
</html>
View Code

做到這裏,基本上就算做完了,不過首先呢,在完成了之後,最好是先做一個測試類,看是否能夠找出結果

技術分享圖片

UserTest.java

技術分享圖片
package test;

import java.util.List;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.nine.dao.UserDao;
import com.nine.entity.User;

public class UserTest {

    @Test
    public void test1() {

        @SuppressWarnings("resource")
        ApplicationContext ac = new ClassPathXmlApplicationContext("spring-mvc.xml");
        UserDao dao = ac.getBean("userDao", UserDao.class);
        List<User> list = dao.findAll();
        System.out.println(list);

    }
}
View Code

然後運行這個測試類,看是否正確,如果在控制臺出現結果,恭喜你你已經完成了!

然後運行Tomcat,輸入http://localhost:8081/springMVC-test2/hello

技術分享圖片

不知道大家完成的怎麽樣了,如果出現問題,可以在下面進行留言,我會為大家進行解答.

springMVC+spring+MyBatis(SSM)的簡單配置