Spring MVC學習筆記和SSH的整合

帥氣你勇哥發表於2020-10-24

1. Spring MVC

Spring MVC 是目前主流的實現MVC設計模式的企業級開發框架,Spring框架的一個子模組,無需整合,開發起來更加便捷。

 

2. 什麼是MVC

  • Controller
  • Model
  • View

 

3. SpringMVC的核心元件

  • DispatcherServler 前置控制器,相當於總排程。
  • Handler 處理器,相當於Servler或Action。
  • HandlerMapping 相當於路由交換。
  • handlerIntercepetor 處理器攔截器。
  • HandlerExecutionChain 處理器執行鏈。
  • HandlerAdapter 處理介面卡
  • ModelAndView裝載了模型資料和檢視資訊。
  • ViewResouler 檢視解析器。

 

4. Spring MVC 的工作流程。

客戶端請求被DispatcherServlet 接收

根據HandlerMapping 對映到 Handler。

生成Handler 和HandlerInterceptor。

Handler 和HandletInterceptor 。。

 

image.png

 

5. 建立專案及入門程式

image.png

1. 配置web.xml 的servlet接收請求

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

<web-app>
    <display-name>Archetype Created Web Application</display-name>

    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

 

2.新建springmvc.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: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.xsd
 http://www.springframework.org/schema/mvc
 http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">


<!--開啟註解掃描-->
    <context:component-scan base-package="com.liyong"></context:component-scan>

    <!--配置檢視解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--字首/index的/-->
        <property name="prefix" value="/"></property>
        <!--字尾 /index.jsp 的jsp-->
        <property name="suffix" value=".jsp"></property>
    </bean>

</beans>
  1. 新建handler
package com.liyong.controller;

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

// 註冊為handler
@Controller
@RequestMapping("/hello")
public class HelloController {

    // url 對映
    @RequestMapping(path = "/index")
    public String sayHello() {
        System.out.println("執行了index");
        return "index";
    }
}

 

6. Spring 註解

 

  • @Controller 在類定義處新增,結合spring 的loc自動掃描使用。
  • @RequestMapping 該註解將url請求和業務方法進行對映,在類和方法前都可以新增。
    • value 指定url 的實際地址,也是requestMapping的預設值
    • method 指定請求的method 型別。
    • params 指定請求中必須包含某些引數,否則無法訪問
@RequestMapping(path = "/params", params = {"name", "id"})
@ResponseBody
public String params(@RequestParam("name") String name, @RequestParam("id") Integer id) {
    System.out.println(name);
    System.out.println(id);
    return "name" + name + " id" + id;
}

// 接收物件。
// 預設接收中文 會亂碼,需要增加filter
@RequestMapping(value = "/submit", method = RequestMethod.POST)
@ResponseBody
public String submit(User user) {
    return "name:" + user.getName() + " id:" + user.getId();
}

 

    • @CookieValue 獲取cookie 值
@RequestMapping("/getCookie")
@ResponseBody
public String index2(@CookieValue(value = "JSESSIONID") String test1) {
    return test1;
}
  • @RequestParam("name") 註解在形參上,代表當前形參和params 對應。
    • requried 是否必傳
    • value 引數名 代表引數key
    • defaultValue 預設值
  • @RequestBody 代表這個請求是返回響應物件而非檢視解析器
  • @PathVariable 表示獲取路徑引數
  • @RestController 表示處理器會把返回資料直接返回給客戶端,不經過檢視響應,註解在類上。
  • @RequestBody 打在引數上,獲取json資料
  • @GetMpapping 表示get請求
  • @PostMapping 表示post請求
  • @PutMapping 表示put 請求
  • @DeleteMapping 表示delete 請求

 

7. Spring MVC資料繫結

 

資料繫結:在後端業務方法中直接獲取客戶端HTTP請求中的引數,將請求引數對映到業務方法的形參中,springMVC 的資料繫結是由HandlerAdaptter 來完成的。

 

基本資料型別

@RequestMapping("/baseType")
@ResponseBody
public String baseType(int id){
    return id + "";
}

包裝類

包裝類可以接受null。

@RequestMapping("packageType")
@ResponseBody
public String packageType(Integer id){
    return id + "";
}

List (content-type 為 x-www-urlencoded)

  1. 增加entity 類,必須具備構造方法和set 方法。
package com.liyong.entity;

public class User {
  private Integer id;
  private String name;

  public User() {
  }

  public User(Integer id, String name) {
    this.id = id;
    this.name = name;
  }

  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;
  }

  @Override
  public String toString() {
    return "User{" +
      "id=" + id +
      ", name='" + name + '\'' +
      '}';
  }
}
  1. 增加方法入參
@RequestMapping(value = "/list", method = RequestMethod.POST)
@ResponseBody
public String postList(UserList userList) {
    return userList.toString();
}

Map(content-type 為 x-www-urlencoded)

  1. 封裝mapentity類
package com.liyong.entity;

import java.util.Map;

public class UserMap {
    private Map<String, User> userMap;

    public UserMap(Map<String, User> userMap) {
        this.userMap = userMap;
    }

    public UserMap() {
    }

    public Map<String, User> getUserMap() {
        return userMap;
    }

    public void setUserMap(Map<String, User> userMap) {
        this.userMap = userMap;
    }

    @Override
    public String toString() {
        return "UserMap{" +
                "userMap=" + userMap +
                '}';
    }
}
  1. 編寫handler處理邏輯
@RequestMapping(value = "/map", method = RequestMethod.POST)
@ResponseBody
public String postMap(UserMap userMap) {
    return userMap.getUserMap().toString();
}

 

JSON:java預設無法直接把json 轉換為 java物件

  1. 安裝fastjson
  2. 配置再springmvc.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: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.xsd
 http://www.springframework.org/schema/mvc
 http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">


    <!--開啟註解掃描-->
    <context:component-scan base-package="com.liyong"></context:component-scan>

    <!--配置檢視解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--字首/index的/-->
        <property name="prefix" value="/"></property>
        <!--字尾 /index.jsp 的jsp-->
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!--處理響應亂碼-->
    <mvc:annotation-driven>
        <!-- 訊息轉換器 轉換響應格式 為UTF-8 -->
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes" value="text/html;charset=UTF8"></property>
            </bean>

            <!--配置fastjson-->
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json</value>
                        <value>application/json;charset=UTF-8</value>
                        <value>application/atom+xml</value>
                        <value>application/x-www-form-urlencoded</value>
                        <value>application/octet-stream</value>
                        <value>application/pdf</value>
                        <value>application/rss+xml</value>
                        <value>application/xhtml+xml</value>
                        <value>application/xml</value>
                        <value>image/gif</value>
                        <value>image/jpeg</value>
                        <value>image/png</value>
                        <value>text/event-stream</value>
                        <value>text/html</value>
                        <value>text/markdown</value>
                        <value>text/plain</value>
                        <value>text/xml</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

</beans>
  1. 接收json
@RequestMapping(value = "/json", method = RequestMethod.POST)
@ResponseBody
public User postJson(@RequestBody User user) {
    System.out.println(user);
    user.setId(223);
    user.setName("哈哈哈");
    return user;
}

8. Response 響應和Request

  1. 安裝servlet
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>4.0.1</version>
  <scope>provided</scope>
</dependency>
  1. 設定content-type 和 增加cookie
 @RequestMapping("/cookiePage")
  @ResponseBody
  public String cookiePage(HttpServletResponse res) {
    res.addCookie(new Cookie("hello", "123"));
    res.setContentType("text/json;charset=UTF-8");
    return "你好啊";
  }

image.png

 

9. REST 架構

  • get 獲取資源
  • post 新增資源
  • put 修改資源
  • delete 刪除資源

 

其他

增加filter 解決請求中文亂碼問題,在web.xml中新增 spring 自帶的 filter 做encoding

  <!--配置編碼過濾器-->
  <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 生效路由-->
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

 

Rest 增刪查改

  1. 編寫DAO和實現類
package com.liyong.dao;

import com.liyong.entity.User;

import java.util.Collection;
import java.util.List;

public interface UserDAO {
    String create(User user);

    Collection<User> findAllUser();

    User findUserById(Integer id);

    String deleteUserById(Integer id);

    String updateUserById(Integer id, User user);
}

package com.liyong.dao;

import com.liyong.entity.User;
import com.liyong.entity.UserMap;
import org.springframework.stereotype.Repository;

import java.util.*;


@Repository
public class UserDAOImpl implements UserDAO {

    private static Map<Integer, User> userMap;

    static {
        System.out.println("UserDAOImpl static");
        userMap = new HashMap<Integer, User>();
        userMap.put(1, new User(1, "李先生"));
        userMap.put(2, new User(2, "憨憨劉"));
    }

    @Override
    public String create(User user) {
        userMap.put(userMap.size() + 1, user);
        return "success";
    }

    @Override
    public Collection<User> findAllUser() {
        return userMap.values();
    }

    @Override
    public User findUserById(Integer id) {
        return userMap.get(id);
    }

    @Override
    public String deleteUserById(Integer id) {
        userMap.remove(id);
        return "success";
    }

    @Override
    public String updateUserById(Integer id, User user) {
        userMap.put(id, user);
        return "success";
    }
}

  1. 編寫services 和實現類
package com.liyong.services;

import com.liyong.entity.User;

import java.util.Collection;

public interface UserServices {
    String create(User user);

    Collection<User> findAllUser();

    User findUserById(Integer id);

    String deleteUserById(Integer id);

    String updateUserById(Integer id, User user);
}


package com.liyong.services;


import com.liyong.dao.UserDAOImpl;
import com.liyong.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;

@Service
public class UserServicesImpl implements UserServices {

    @Autowired
    private UserDAOImpl userDAOImpl;

    @Override
    public String create(User user) {
        return userDAOImpl.create(user);
    }

    @Override
    public Collection<User> findAllUser() {
        return userDAOImpl.findAllUser();
    }

    @Override
    public User findUserById(Integer id) {
        return userDAOImpl.findUserById(id);
    }

    @Override
    public String deleteUserById(Integer id) {
        return userDAOImpl.deleteUserById(id);
    }

    @Override
    public String updateUserById(Integer id, User user) {
        return userDAOImpl.updateUserById(id, user);
    }
}
  1. 編寫處理器
package com.liyong.controller;

import com.liyong.entity.User;
import com.liyong.services.UserServicesImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

@RestController
@RequestMapping("/api/user")
public class UserRESTController {

    @Autowired
    private UserServicesImpl userServices;

    @PostMapping("/createUser")
    public String create(@RequestBody User user) {
        return userServices.create(user);
    }

    @GetMapping("/findAllUser")
    public Collection<User> findAllUser() {
        return userServices.findAllUser();
    }

    @GetMapping("/findUser/{id}")
    public User findUserById(@PathVariable Integer id) {
        return userServices.findUserById(id);
    }

    @DeleteMapping("/deleteUser/{id}")
    public String deleteUserById(@PathVariable Integer id) {
        return userServices.deleteUserById(id);
    }

    @PutMapping("/updateUserById/{id}")
    public String updateUserById(@PathVariable Integer id, @RequestBody User user) {
        return userServices.updateUserById(id, user);
    }
}

 

10. 檔案的上傳和下載

 

檔案上傳

底層採用 apache fileupload

 

1. 增加依賴

<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.5</version>
</dependency>

<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.3.3</version>
</dependency>

2. springmvc.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: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.xsd
 http://www.springframework.org/schema/mvc
 http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">


    <!--開啟註解掃描-->
    <context:component-scan base-package="com.liyong"></context:component-scan>

    <!--配置檢視解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--字首/index的/-->
        <property name="prefix" value="/"></property>
        <!--字尾 /index.jsp 的jsp-->
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!--上傳元件-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"/>
        <property name="maxUploadSize" value="#{1024*1024}"/>
    </bean>

    <!--處理響應亂碼-->
    <mvc:annotation-driven>
        <!-- 訊息轉換器 轉換響應格式 為UTF-8 -->
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes" value="text/html;charset=UTF8"></property>
            </bean>

            <!--配置fastjson-->
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json</value>
                        <value>application/json;charset=UTF-8</value>
                        <value>application/atom+xml</value>
                        <value>application/x-www-form-urlencoded</value>
                        <value>application/octet-stream</value>
                        <value>application/pdf</value>
                        <value>application/rss+xml</value>
                        <value>application/xhtml+xml</value>
                        <value>application/xml</value>
                        <value>image/gif</value>
                        <value>image/jpeg</value>
                        <value>image/png</value>
                        <value>text/event-stream</value>
                        <value>text/html</value>
                        <value>text/markdown</value>
                        <value>text/plain</value>
                        <value>text/xml</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

</beans>

3. 接收檔案上傳

package com.liyong.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/api/file")
public class FileController {

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String upload(MultipartFile file, HttpServletRequest req) throws IOException {
        System.out.println(file);
        if (file == null || file.getSize() == 0) {
            return "failed";
        }
        // 獲取servlet context 下的file 檔案路徑
        String servletPath = req.getSession().getServletContext().getRealPath("file");
        // 獲取檔名
        String name = file.getOriginalFilename();

        // 新建檔案
        File file1 = new File(servletPath, name);
        // 寫入到檔案
        file.transferTo(file1);

        return "success";
    }

}

image.png

 

檔案下載

@RequestMapping("/download")
public String download(HttpServletRequest req, HttpServletResponse res) throws IOException {
    String path = req.getSession().getServletContext().getRealPath("file");
    FileInputStream in = new FileInputStream(path + "\\QQ瀏覽器截圖20200728231741.png");

    res.setHeader("Content-Type", "application/x-msdownload");
    res.setHeader("Content-Disposition", "attachment; filename=123.png");

    ServletOutputStream outputStream = res.getOutputStream();
    outputStream.flush();

    outputStream.flush();
    int aRead = 0;
    byte b[] = new byte[1024];
    while ((aRead = in.read(b)) != -1 & in != null) {
        outputStream.write(b, 0, aRead);
    }
    outputStream.flush();
    in.close();
    outputStream.close();
    return "1";
}

 

 

11. SSM的整合

spring 和spring MVC 和Mybatis 的整合

image.png

 

1. 增加依賴

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

<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>org.example</groupId>
    <artifactId>springSSM</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>springSSM Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

        <!-- SpringMVC -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.0.11.RELEASE</version>
        </dependency>
        <!-- Spring JDBC -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.0.11.RELEASE</version>
        </dependency>
        <!-- Spring AOP -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.0.11.RELEASE</version>
        </dependency>
        <!--aspect-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.0.11.RELEASE</version>
        </dependency>
        <!-- MySQL驅動 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.6</version>
            <scope>provided</scope>
        </dependency>

        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>

        <!-- mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.5</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>

        <!--druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.20</version>
        </dependency>

        <!--jackjson-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.9.3</version>
        </dependency>

        <!--servlet-api-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
        </dependency>

        <!--<dependency>-->
        <!--  <groupId>com.alibaba</groupId>-->
        <!--  <artifactId>fastjson</artifactId>-->
        <!--  <version></version>-->
        <!--</dependency>-->

    </dependencies>

    <build>
        <finalName>springSSM</finalName>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.1.0</version>
                </plugin>
                <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>
</project>

2. 配置web.xml

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

<web-app>
    <display-name>Archetype Created Web Application</display-name>

    <!--spring 配置-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>


    <!--編碼配置-->
    <filter>
        <filter-name>encodingFilter</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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>


    <!--spring MVC 配置-->
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

3. 配置spring 配置

<?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:p="http://www.springframework.org/schema/p"
       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-4.3.xsd
">
<context:component-scan base-package="com.liyong.services"/>
    <!--配置連結池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/book?serverTimezone=GMT"></property>
    </bean>

    <!--交給loc的工廠類-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--datasource-->
        <property name="dataSource" ref="dataSource"></property>
        <!--配置mapper路徑-->
        <property name="mapperLocations" value="classpath:com/liyong/dao/*.xml"></property>
        <!--配置mybatis配置檔案路徑-->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
    </bean>

    <!--掃描自定義的mapper介面-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.liyong.dao"></property>
    </bean>

</beans>

4. 配置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:mvc="http://www.springframework.org/schema/mvc"
       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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
    <!-- 啟動註解驅動 -->
    <mvc:annotation-driven></mvc:annotation-driven>
    <!-- 掃描業務程式碼 -->
    <context:component-scan base-package="com.liyong"></context:component-scan>

    <!-- 配置檢視解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans>

5. 配置mybatis配置

<?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>
    <settings>
        <!-- 列印SQL-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <typeAliases>
        <!-- 指定⼀個包名,MyBatis會在包名下搜尋需要的JavaBean-->
        <package name="com.liyong.entity"/>
    </typeAliases>
</configuration>

 

6. 編寫entity 介面 和實現類

image.png

7. 編寫dao 介面類 和mapper 檔案

image.png

8. 編寫services介面和實現類

image.png

9. 編寫controller

image.png

 

 

其他

 

解決響應亂碼

在springmvc.xml 中新增如下程式碼。

  <!--處理響應亂碼-->
  <mvc:annotation-driven>
    <!-- 訊息轉換器 -->
    <mvc:message-converters register-defaults="true">
      <bean
        class="org.springframework.http.converter.StringHttpMessageConverter">
        <property name="supportedMediaTypes" value="text/html;charset=UTF8"></property>
      </bean>
    </mvc:message-converters>
  </mvc:annotation-driven>

 

RestApi

@RequestMapping("/rest/{id}/{name}")
public String restIndex(@PathVariable("id") Integer id, @PathVariable("name") String name) {
    System.out.println(id);
    System.out.println(name);
    return "index";
}

 

 

 

 

 

 

相關文章