Spring MVC学习笔记

作者: 琅筑 | 来源:发表于2018-06-02 15:30 被阅读122次

MVC的简介

  • 前端控制器Front Controller(MVC)也称之为调度器(Dispatcher)---->控制器(Controller)
  • 控制器(Controller)了解所有的业务细节,负责业务数据的抽取,我们的视图模板(View template)了解所有的前端特性,负责页面呈现,我们的前端控制器(Front Controller)负责分发调度
  • MVC的核心思想是业务数据抽取同业务数据呈现相分离-->这也是一种解耦合

MVC的概念

Model + View + Controller

View:视图层,为用户提供一个UI,重点关注数据的呈现

Model:模型层,业务数据的信息表示,数据的载体,关注支撑业务的信息构成,通常是多个业务实体的组合

Controller:控制层,调用业务逻辑产生合适的数据(Model)传递数据给视图层用于呈现

什么是MVC?
  • MVC是一种架构模式

程序分层,分工合作,即相互独立,又协同工作。

  • MVC是一种思考方式

需要将什么信息展示给用户?(Model) 如何布局?(View) 调用那些业务逻辑?(Controller)

SpringMVC中的基本概念

SpringMVC中的静态概念

  • DispatcherServlet
  • Controller
  • HandlerAdapter(适配器):在DispatcherServlet内部使用的一个类
  • HandlerInterceptor
  • HandlerMapping:
    • help DispatcherServlet to get the right Controller请求到来之后使用哪一个Controller响应请求
    • Wrap Controller with HandlerInterceptor
  • HandlerExecutionChain
    • preHandler->Controller method --> postHandle --> afterCompletion
  • ModelAndView
  • ViewResolver 视图解析器:告诉DispatcherServlet使用哪个View来呈现视图。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版本以上就可以默认的支持我们的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/>

    <!--扩充了注解驱动,可以将请求的url参数绑定到Controller中某个方法的参数-->
    <mvc:annotation-driven/>

    <!--静态资源处理: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>

基础的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";
    }
}

基础的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中的参数 比如:host:8080/hello/userId=100
    • @PathVariable用来匹配Restful标准的URL 比如:host:8080/hello/{userId},看起来更加的酷
  • HttpServletRequest and/or HttpSession

binding 页面扁平的文本信息绑定到多层次的文本对象

数据的绑定:

@ModelAttribute

添加数据之后的请求重定向:

  • 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,一个用来控制显示上传的页面,一个用来执行上传的逻辑

@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) 是一种轻量级的数据交换格式
  • Restful Web Service

Spring MVC 提供了一种ViewResolver

ContentNegotiatingViewResolver--->针对不同的请求对象提供不同的数据格式

  • 人--> JSPView
  • 机器 --> JsonView

标记json数据格式方法:

  • ResponseEntity
  • @ResponseBody/@ResquestBody

相关文章

网友评论

    本文标题:Spring MVC学习笔记

    本文链接:https://www.haomeiwen.com/subject/awersftx.html