Spring MVC學(xué)習(xí)筆記

MVC的簡介

  • 前端控制器Front Controller(MVC)也稱之為調(diào)度器(Dispatcher)---->控制器(Controller)
  • 控制器(Controller)了解所有的業(yè)務(wù)細節(jié),負(fù)責(zé)業(yè)務(wù)數(shù)據(jù)的抽取,我們的視圖模板(View template)了解所有的前端特性,負(fù)責(zé)頁面呈現(xiàn),我們的前端控制器(Front Controller)負(fù)責(zé)分發(fā)調(diào)度
  • MVC的核心思想是業(yè)務(wù)數(shù)據(jù)抽取同業(yè)務(wù)數(shù)據(jù)呈現(xiàn)相分離-->這也是一種解耦合

MVC的概念

Model + View + Controller

View:視圖層,為用戶提供一個UI,重點關(guān)注數(shù)據(jù)的呈現(xiàn)

Model:模型層,業(yè)務(wù)數(shù)據(jù)的信息表示,數(shù)據(jù)的載體,關(guān)注支撐業(yè)務(wù)的信息構(gòu)成,通常是多個業(yè)務(wù)實體的組合

Controller:控制層,調(diào)用業(yè)務(wù)邏輯產(chǎn)生合適的數(shù)據(jù)(Model)傳遞數(shù)據(jù)給視圖層用于呈現(xiàn)

什么是MVC?
  • MVC是一種架構(gòu)模式

程序分層,分工合作,即相互獨立,又協(xié)同工作。

  • MVC是一種思考方式

需要將什么信息展示給用戶?(Model) 如何布局?(View) 調(diào)用那些業(yè)務(wù)邏輯?(Controller)

SpringMVC中的基本概念

SpringMVC中的靜態(tài)概念

  • DispatcherServlet
  • Controller
  • HandlerAdapter(適配器):在DispatcherServlet內(nèi)部使用的一個類
  • HandlerInterceptor
  • HandlerMapping:
    • help DispatcherServlet to get the right Controller請求到來之后使用哪一個Controller響應(yīng)請求
    • Wrap Controller with HandlerInterceptor
  • HandlerExecutionChain
    • preHandler->Controller method --> postHandle --> afterCompletion
  • ModelAndView
  • ViewResolver 視圖解析器:告訴DispatcherServlet使用哪個View來呈現(xiàn)視圖。Help DispatcherServlet to Resolve the right view to render page.
  • View: V in MVC Responsible for page rendering


    SpringMVC流程.png

Spring MVC 的使用

web.xml的基本配置

注意web.xml的版本,我這里使用的是3.0版,只要是在2.3版本以上就可以默認(rèn)的支持我們的jsp的EL表達式語言,因此這里選擇比maven自動生成的頭部更高的版本。

<?xml version = "1.0" encoding = "UTF-8"?>
<web-app 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"
         version="3.0">


    <display-name>Spring MVC Study</display-name>

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

        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
   
    <servlet-mapping>
        <servlet-name>spring-mvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

spring-mvc.xml spring MVC配置文件

?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/cache"
       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/cache http://www.springframework.org/schema/cache/spring-cache.xsd">


    <!--開啟自動包掃描-->
    <context:component-scan base-package="cn.fungus.controller"/>

    <!--開啟spring-mvc的注解-->
    <context:annotation-config/>

    <!--擴充了注解驅(qū)動,可以將請求的url參數(shù)綁定到Controller中某個方法的參數(shù)-->
    <mvc:annotation-driven/>

    <!--靜態(tài)資源處理:css,js,html,img-->
    <!--<mvc:resources mapping="/resources/**" location="/resource/"/>-->

    <!--配置ViewResolver的bean-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/">

        </property>
        <property name="suffix" value=".jsp">

        </property>
    </bean>


</beans>

基礎(chǔ)的Controller編寫

package cn.fungus.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
 * create by fungus on 2018/6/2
 **/

@Controller
public class HelloWorldController {

    @RequestMapping(value = "/hello")
    public String hello() {
        return "hello";
    }
}

基礎(chǔ)的jsp頁面的編寫

<%--
  Created by IntelliJ IDEA.
  User: fungus
  Date: 2018/6/2
  Time: 13:06
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>hello world!</title>
</head>
<body>
    <h1>i am Hello World ,my father is HelloWorldController</h1>
</body>
</html>

需要會使用的注解

  • @Controller
  • @RequestMapping
  • URL template (@RequestParam and @PathVariable)
    • @RequestParam是用來匹配URL中的參數(shù) 比如:host:8080/hello/userId=100
    • @PathVariable用來匹配Restful標(biāo)準(zhǔn)的URL 比如:host:8080/hello/{userId},看起來更加的酷
  • HttpServletRequest and/or HttpSession

binding 頁面扁平的文本信息綁定到多層次的文本對象

數(shù)據(jù)的綁定:

@ModelAttribute

添加數(shù)據(jù)之后的請求重定向:

  • redirect:
  • forward:

單文件上傳

spring-mvc.xml中添加一個bean

<!--200*1024*1024即200M,resolveLazily啟動是為了推遲文件解析,以便于捕獲文件大小異常 -->
    <!--multipartResolver-->

    <!--背后依賴commons-fileupload包,所以需要引入這個包
     <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
     </dependency>
     -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

        <property name="maxUploadSize" value="209715200"/>
        <property name="defaultEncoding" value="UTF-8"/>
        <!--延遲加載-->
        <property name="resolveLazily" value="true"/>
    </bean>

POM文件中引入

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

需要添加兩個Controller,一個用來控制顯示上傳的頁面,一個用來執(zhí)行上傳的邏輯

@RequestMapping(value = "/upload", method = RequestMethod.GET)
    public String showUploadPage() {
        return "files";
    }

    @RequestMapping(value = "/doUpload", method = RequestMethod.POST)
    public String doUploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
            System.out.println("Process file(): " + file.getOriginalFilename());
            FileUtils.copyInputStreamToFile(file.getInputStream(),
                    new File("C:\\Users\\fungus\\Desktop\\load", System.currentTimeMillis() + file.getOriginalFilename()));
        }

        return "success";
    }

file.jsp

<%--
  Created by IntelliJ IDEA.
  User: fungus
  Date: 2018/6/2
  Time: 14:40
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Upload Files</title>
</head>
<body>
    <h1>上傳附件</h1>
    <form method="post" action="/doUpload" enctype="multipart/form-data">
        <input type="file" name="file"/>
        <input type="submit"/>
    </form>
</body>
</html>

success.jsp

<%--
  Created by IntelliJ IDEA.
  User: fungus
  Date: 2018/6/2
  Time: 14:44
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Success</title>
</head>
<body>
    <h1>Success</h1>
</body>
</html>

JSON

  • JSON(JavaScript Object Notation) 是一種輕量級的數(shù)據(jù)交換格式
  • Restful Web Service

Spring MVC 提供了一種ViewResolver

ContentNegotiatingViewResolver--->針對不同的請求對象提供不同的數(shù)據(jù)格式

  • 人--> JSPView
  • 機器 --> JsonView

標(biāo)記json數(shù)據(jù)格式方法:

  • ResponseEntity
  • @ResponseBody/@ResquestBody
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容