SpringMVC

一、SpringMVC入门

1.MVC介绍

MVC全名是Model View Controller,是模型(model)–视图(view)-控制器(controller)的缩写,它是一种软件设计典范,是一种软件架构设计分层模式。

Model(模型)是应用程序中用于处理应用程序数据逻辑的部分。

View(视图)是应用程序中处理数据显示的部分。

Controller(控制器)是应用程序中处理用户交互的部分。

最典型的MVC就是JSP + servlet + javabean的模式。

2.MVC发展历史

Model 1(jsp+javabean)
Model 2 (jsp+servlet+javabean)
Model1和Model2的优缺点
在这里插入图片描述

3.目前市场上MVC框架

3.1 SpringMVC(主流MVC框架)

是Spring框架的一部分(子框架),是实现对Servlet技术进行封装。

3.2 Struts

3.3 Jfinal

二、SpringMVC配置式开发

1.SpringMVC运行原理(执行过程)

在这里插入图片描述

2.需求

用户提交一个请求,服务端处理器接受到请求后,给出一条信息,在相应页面中显示该条信息

3.开发步骤

  1. 导入jar包
  2. 配置web.xml,注册SpringMVC前端控制器(中央调度器)
  3. 编写SpringMVC后端控制器
  4. 编写springmvc配置文件,注册后端控制器(注意id写法格式)
  5. 编写跳转资源页面

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <!-- 注册springmvc前端控制器(中央调度器) -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--指定springmvc配置文件的路径以及名称-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
</web-app>

springmvc后端控制器

package com.java.handlers;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//后端控制器
public class MyController implements Controller {
    @Override
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        ModelAndView mv = new ModelAndView();
        System.out.println("进入到后端控制器方法!");
        mv.addObject("msg","Hello SpringMVC!");
        mv.setViewName("/jsp/welcome.jsp");
        return mv;
    }
}

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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 注册后端控制器 -->
    <bean id="/my.do" class="com.java.handlers.MyController"></bean>
</beans>

4.web.xml中urlpattern配置问题

  1. 配置/和配置/*的区别
    配置/*会拦截所有请求,导致报404
  2. 静态资源无法访问解决方案(三种)

第一种:在web.xml中进行配置

<servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.jpg</url-pattern>
    </servlet-mapping>

第二种:在springmvc.xml加上下面的配置

<mvc:default-servlet-handler/>

第三种:在springmvc.xml中加上下面的配置

<mvc:resources mapping="/images/**" location="/images"></mvc:resources>

三.SpringMVC注解式开发

1.搭建环境

  1. 后端控制器无需实现接口,添加相应注解
  2. springmvc配置文件无需注册controller
  3. springmvc配置文件中添加组件扫描器、注解驱动
    mvc:annotation-driven/会自动注册DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter两个bean,并提供了:数据绑定支持,@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,读写XML的支持(JAXB),读写JSON的支持(Jackson)等等。

2.涉及常用注解

@Controller、@RequestMapping(类体上【命名空间】、方法上)、@Scope

package com.java.handlers;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//后端控制器
@Controller //该注解表示将当前类交给spring容器管理
@RequestMapping("/springmvc") //该注解起到限定范围的作用
public class MyController {
    @RequestMapping("/hadleRequest")
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        ModelAndView mv = new ModelAndView();
        System.out.println("进入到后端控制器方法!");
        mv.addObject("msg","Hello SpringMVC!");
        mv.setViewName("/jsp/welcome.jsp");
        return mv;
    }
}

<?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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!--注册组件扫描器-->
    <context:component-scan base-package="com.java.handlers"></context:component-scan>
    <!--注册注解驱动-->
    <mvc:annotation-driven/>
    <!--静态资源无法放行第二种解决方案-->
    <!--<mvc:default-servlet-handler/>-->
    <!--静态资源无法放行第三种解决方案-->
    <mvc:resources mapping="/images/**" location="/images/"></mvc:resources>
</beans>

3.视图解析器(前缀、后缀)
在springmvc中注册视图解析器

<!--注册视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
package com.java.handlers;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//后端控制器
@Controller //该注解表示将当前类交给spring容器管理
@Scope("prototype")
@RequestMapping("/springmvc") //该注解起到限定范围的作用
public class MyController {
    @RequestMapping("/hello")
    public String hello() {
        return "welcome";
    }
}

4.处理器方法常用的参数(五类)

  1. HttpServletRequest
  2. HttpServletResponse
  3. HttpSession
  4. 用于承载数据的Model、Map、ModelMap
  5. 请求中所携带的请求参数

5接收请求参数

  1. 逐个接收(涉及注解@RequestParam)
<%--
  Created by IntelliJ IDEA.
  User: PengHao
  Date: 2019/7/29
  Time: 11:24
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
    <form action="springmvc/hello" method="post">
      <input type="text" name="username"> <br/>
      <input type="text" name="age"><br/>
      <input type="submit" name="提交">
    </form>
  </body>
</html>

package com.java.handlers;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//后端控制器
@Controller //该注解表示将当前类交给spring容器管理
@Scope("prototype")
@RequestMapping("/springmvc") //该注解起到限定范围的作用
public class MyController {
    @RequestMapping("/hello")
    public ModelAndView hello(String username,int age) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("username",username);
        modelAndView.addObject("age",age);
        modelAndView.setViewName("welcome");
        return modelAndView;
    }
}

public ModelAndView hello(@RequestParam("username") String name,int age) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("username",name);
        modelAndView.addObject("age",age);
        modelAndView.setViewName("welcome");
        return modelAndView;
    }
  1. 以对象形式整体接收
package com.java.pojo;

public class Star {
    private String username;
    private int age;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

package com.java.handlers;

import com.java.pojo.Star;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//后端控制器
@Controller //该注解表示将当前类交给spring容器管理
@Scope("prototype")
@RequestMapping("/springmvc") //该注解起到限定范围的作用
public class MyController {
    @RequestMapping("/hello")
    public ModelAndView hello(Star star) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("username",star.getUsername());
        modelAndView.addObject("age",star.getAge());
        modelAndView.setViewName("welcome");
        return modelAndView;
    }
}

  1. 域属性参数的接收
	private String username;
    private int age;

    //域属性,也称为对象属性
    private Parter parter;
<form action="springmvc/hello" method="post">
      用户名:<input type="text" name="username"> <br/>
      年龄:<input type="text" name="age"><br/>
      伴侣名称:<input type="text" name="Parter.name"><br/>
      <input type="submit" name="提交">
    </form>
 public ModelAndView hello(Star star) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("username",star.getUsername());
        modelAndView.addObject("age",star.getAge());
        modelAndView.addObject("Parter",star.getParter().getName());
        modelAndView.setViewName("welcome");
        return modelAndView;
    }
  1. 数组或集合参数的接收
<%--
  Created by IntelliJ IDEA.
  User: PengHao
  Date: 2019/7/29
  Time: 11:24
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
    <form action="springmvc/hello" method="post">
      <input type="checkbox" name="interest" value="a1">a1</br>
      <input type="checkbox" name="interest" value="a2">a2</br>
      <input type="checkbox" name="interest" value="a3">a3</br>
      <input type="submit" name="提交">
    </form>
  </body>
</html>

package com.java.handlers;

import com.java.pojo.Star;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

//后端控制器
@Controller //该注解表示将当前类交给spring容器管理
@Scope("prototype")
@RequestMapping("/springmvc") //该注解起到限定范围的作用
public class MyController {
    //数组接收参数
    /*@RequestMapping("/hello")
    public void hello(String[] interest) {
        for (String string:interest){
            System.out.println(string);
        }
    }*/
    //集合接收参数
    @RequestMapping("/hello")
    public void hello(@RequestParam List<String> interest){
        for (String string:interest){
            System.out.println(string);
        }
    }
}

  1. restfull风格,传参(涉及注解@ PathVariable)
//后端控制器
@Controller //该注解表示将当前类交给spring容器管理
@Scope("prototype")
@RequestMapping("/springmvc") //该注解起到限定范围的作用
public class MyController {
    //restful风格传参
    @RequestMapping("/{name}/{age}/hello")
    public void hello(@PathVariable String name,@PathVariable int age){
        System.out.println(name+age);
    }
}

访问路径:http://localhost:8080/springmvc/zhangsan/20/hello
6. 接收json字符串(涉及注解@RequestBody,注册mvc注解驱动,导入jackson包)

<%--
  Created by IntelliJ IDEA.
  User: PengHao
  Date: 2019/7/29
  Time: 11:24
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.7.2.min.js"></script>
    <script type="text/javascript">
      $(function () {
          $("#myButton").click(function () {
              var data1 = {username:"zhangsan",age:23};
              $.ajax({
                  url:"${pageContext.request.contextPath}/springmvc/hello",
                  type:"POST",
                  contentType:"application/json",
                  data:JSON.stringify(data1),
              })
          })
      })
    </script>
    <title>$Title$</title>
  </head>
  <body>
    <button id="myButton">点击我呀!</button>
  </body>
</html>

package com.java.handlers;

import com.java.pojo.Star;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

//后端控制器
@Controller //该注解表示将当前类交给spring容器管理
@Scope("prototype")
@RequestMapping("/springmvc") //该注解起到限定范围的作用
public class MyController {
    //接收json字符串并封装成对象
    @RequestMapping("/hello")
    public void hello(@RequestBody Star star){
        System.out.println(star);
    }
}

<!--静态资源无法放行第三种解决方案-->
    <mvc:resources mapping="/images/**" location="/images/"></mvc:resources>
    <mvc:resources mapping="/js/**" location="/js/"></mvc:resources>

6 . 获取请求头中参数(涉及注解@RequestHeader)

//后端控制器
@Controller //该注解表示将当前类交给spring容器管理
@Scope("prototype")
@RequestMapping("/springmvc") //该注解起到限定范围的作用
public class MyController {
    //接收json字符串并封装成对象
    @RequestMapping("/hello")
    public void hello(@RequestHeader String host,@RequestHeader String cookie){
        System.out.println(host + "------------"+cookie);
    }
}

7 .处理器方法的返回值
7.1 ModelAndView
7.2 String

//后端控制器
@Controller //该注解表示将当前类交给spring容器管理
@Scope("prototype")
@RequestMapping("/springmvc") //该注解起到限定范围的作用
public class MyController {
    //接收json字符串并封装成对象
    @RequestMapping("/hello")
    public String hello(String username, int age, Model model, Map<String,Object> map, ModelMap modelMap){
        System.out.println(username+ "-----------"+age);
        model.addAttribute("username",username);
        map.put("age",age);
        modelMap.addAttribute("gender","female");
        return "welcome";
    }
}

7.2.2 中文乱码问题

//后端控制器
@Controller //该注解表示将当前类交给spring容器管理
@Scope("prototype")
@RequestMapping("/springmvc") //该注解起到限定范围的作用
public class MyController {
    //接收json字符串并封装成对象
    @RequestMapping(value = "/hello",produces = "text/html;charset=utf-8")
    @ResponseBody
    public String hello(){
        return "china:瓷器";
    }
}

7.3 void

package com.java.handlers;

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

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//后端控制器
@Controller //该注解表示将当前类交给spring容器管理
@Scope("prototype")
@RequestMapping("/springmvc") //该注解起到限定范围的作用
public class MyController {
    //接收json字符串并封装成对象
    @RequestMapping(value = "/hello",produces = "text/html;charset=utf-8")
    public void hello(HttpServletResponse response) throws IOException {
        String json = "{\"name\":\"weilong\",\"flavor\":\"hot\"}";
        response.getWriter().print(json);
    }
}

7.4 Object(涉及注解@ResponseBody,注册mvc注解驱动,导入jackson2.5包)

package com.java.handlers;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

//后端控制器
@Controller //该注解表示将当前类交给spring容器管理
@Scope("prototype")
@RequestMapping("/springmvc") //该注解起到限定范围的作用
public class MyController {
    //接收json字符串并封装成对象
    @RequestMapping(value = "/hello",produces = "text/html;charset=utf-8")
    @ResponseBody
    public Object hello() {
        return "aaa";
    }
}

8 .请求转发与重定向
请求转发

package com.java.handlers;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;


//后端控制器
@Controller //该注解表示将当前类交给spring容器管理
@Scope("prototype")
@RequestMapping("/springmvc") //该注解起到限定范围的作用
public class MyController {
    @RequestMapping("/hello")
    public ModelAndView hello(@RequestParam("username") String name,int age) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("username",name);
        modelAndView.addObject("age",age);
        modelAndView.setViewName("welcome");
        return modelAndView;
    }
}

<%--
  Created by IntelliJ IDEA.
  User: PengHao
  Date: 2019/7/29
  Time: 17:27
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    欢迎页面!${username}--${age}
</body>
</html>

重定向到jsp

package com.java.handlers;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;


//后端控制器
@Controller //该注解表示将当前类交给spring容器管理
@Scope("prototype")
@RequestMapping("/springmvc") //该注解起到限定范围的作用
public class MyController {
    @RequestMapping("/hello")
    public ModelAndView hello(@RequestParam("username") String name,int age) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("username",name);
        modelAndView.addObject("age",age);
        modelAndView.setViewName("redirect:/jsp/welcome.jsp");
        return modelAndView;
    }
}

<%--
  Created by IntelliJ IDEA.
  User: PengHao
  Date: 2019/7/29
  Time: 17:27
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    欢迎页面!${param.username}--${param.age}
</body>
</html>

重定向到另一个处理器方法

package com.java.handlers;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;


//后端控制器
@Controller //该注解表示将当前类交给spring容器管理
@Scope("prototype")
@RequestMapping("/springmvc") //该注解起到限定范围的作用
public class MyController {
    @RequestMapping("/hello")
    public ModelAndView hello(@RequestParam("username") String name,int age) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("username",name);
        modelAndView.addObject("age",age);
        modelAndView.setViewName("redirect:some");
        return modelAndView;
    }
    @RequestMapping("/some")
    public ModelAndView some(@RequestParam("username") String name,int age) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("welcome");
        return modelAndView;
    }
}

<%--
  Created by IntelliJ IDEA.
  User: PengHao
  Date: 2019/7/29
  Time: 17:27
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    欢迎页面!${param.username}--${param.age}
</body>
</html>

  1. 文件上传(注册mvc注解驱动、文件上传解析器,导入相关jar包)
    单文件
<?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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!--注册组件扫描器-->
    <context:component-scan base-package="com.java.handlers"></context:component-scan>
    <!--注册注解驱动-->
    <mvc:annotation-driven/>
    <!--注册视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!--注册文件上传解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"></property>
    </bean>
    <!--静态资源无法放行第二种解决方案-->
    <!--<mvc:default-servlet-handler/>-->
    <!--静态资源无法放行第三种解决方案-->
    <mvc:resources mapping="/images/**" location="/images/"></mvc:resources>
</beans>
package com.java.handlers;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;


//后端控制器
@Controller //该注解表示将当前类交给spring容器管理
@Scope("prototype")
@RequestMapping("/springmvc") //该注解起到限定范围的作用
public class MyController {
    @RequestMapping("/fileUpload")
    public String fileUpload(MultipartFile img) {
        String path = "d:/";
        String fileName = img.getOriginalFilename();
        File file = new File(path, fileName);
        try {
            img.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "welcome";
    }
}

多文件

<%--
  Created by IntelliJ IDEA.
  User: PengHao
  Date: 2019/7/29
  Time: 11:24
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
    <form action="springmvc/fileUpload" method="post" enctype="multipart/form-data">
      <input type="file" name="imgs"> <br/>
      <input type="file" name="imgs"> <br/>
      <input type="file" name="imgs"> <br/>
      <input type="submit" name="上传">
    </form>
  </body>
</html>

package com.java.handlers;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

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


//后端控制器
@Controller //该注解表示将当前类交给spring容器管理
@Scope("prototype")
@RequestMapping("/springmvc") //该注解起到限定范围的作用
public class MyController {
    @RequestMapping("/fileUpload")
    public String fileUpload(@RequestParam MultipartFile[] imgs, HttpSession session) {
        String path = session.getServletContext().getRealPath("/");
        for (MultipartFile img: imgs) {
            String filename = img.getOriginalFilename();
            File file = new File(path,filename);
            try {
                img.transferTo(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "welcome";
    }
}

  1. 文件下载
package com.java.handlers;

import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.io.*;


//后端控制器
@Controller //该注解表示将当前类交给spring容器管理
@Scope("prototype")
@RequestMapping("/springmvc") //该注解起到限定范围的作用
public class MyController {
    @RequestMapping("/fileDowload")
    public ResponseEntity<byte[]> dowload() throws IOException {
        //指定下载文件
        File file = new File("d:/a.jpg");
        InputStream is = new FileInputStream(file);
        //创建字节数组,并且设置数组大小为预估的文件字节数
        byte[] body = new byte[is.available()];
        //将输入流中字符存储到缓存数组中
        is.read(body);
        //获取下载显示的文件名,并解决中文乱码
        String name = file.getName();
        String downLoadFileName = new String(name.getBytes("UTF-8"), "ISO-8859-1");
        //设置Http响应头信息,并且通知浏览器以附件的形式进行下载
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Disposition","attachment;filename="+downLoadFileName);
        //设置Http响应状态信息
        HttpStatus status = HttpStatus.OK;
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(body,httpHeaders,status);
        return responseEntity;
    }
}

  1. 拦截器(实现HandleInterceptor接口:注册拦截器mvc:interceptors)
package com.java.interceptors;


import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//自定义拦截器
public class FirstInterceptor implements HandlerInterceptor {
    //该方法执行时机:处理器方法执行之前执行
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        System.out.println("拦截器preHandle()执行!");
        return false;
    }
    //该方法执行时机:处理器方法执行之后执行
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }
    //该方法执行时机:所有工作执行完成之后,响应给浏览器客户端之前执行
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

a:拦截全部请求

<?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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!--注册组件扫描器-->
    <context:component-scan base-package="com.java.handlers"></context:component-scan>
    <!--注册注解驱动-->
    <mvc:annotation-driven/>
    <!--注册视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!--注册拦截器-->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean id="" class="com.java.interceptors.FirstInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>
    <!--静态资源无法放行第二种解决方案-->
    <!--<mvc:default-servlet-handler/>-->
    <!--静态资源无法放行第三种解决方案-->
    <mvc:resources mapping="/images/**" location="/images/"></mvc:resources>
    <mvc:resources mapping="/js/**" location="/js/"></mvc:resources>
</beans>

b:拦截指定请求

<?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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!--注册组件扫描器-->
    <context:component-scan base-package="com.java.handlers"></context:component-scan>
    <!--注册注解驱动-->
    <mvc:annotation-driven/>
    <!--注册视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!--注册拦截器-->
    <mvc:interceptors>
        <mvc:interceptor>
            <!--<mvc:mapping path="/springmvc/hello"/>-->
            <mvc:mapping path="/**"/>
            <mvc:exclude-mapping path="/springmvc/hello2"/>
            <bean id="" class="com.java.interceptors.FirstInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>
    <!--静态资源无法放行第二种解决方案-->
    <!--<mvc:default-servlet-handler/>-->
    <!--静态资源无法放行第三种解决方案-->
    <mvc:resources mapping="/images/**" location="/images/"></mvc:resources>
    <mvc:resources mapping="/js/**" location="/js/"></mvc:resources>
</beans>

c:多个拦截器执行流程

<?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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!--注册组件扫描器-->
    <context:component-scan base-package="com.java.handlers"></context:component-scan>
    <!--注册注解驱动-->
    <mvc:annotation-driven/>
    <!--注册视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!--注册拦截器-->
    <mvc:interceptors>
        <mvc:interceptor>
            <!--<mvc:mapping path="/springmvc/hello"/>-->
            <mvc:mapping path="/**"/>
            <!--<mvc:exclude-mapping path="/springmvc/hello2"/>-->
            <bean id="" class="com.java.interceptors.FirstInterceptor"></bean>
        </mvc:interceptor>
        <mvc:interceptor>
            <!--<mvc:mapping path="/springmvc/hello"/>-->
            <mvc:mapping path="/**"/>
            <!--<mvc:exclude-mapping path="/springmvc/hello2"/>-->
            <bean id="" class="com.java.interceptors.SecondInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>
    <!--静态资源无法放行第二种解决方案-->
    <!--<mvc:default-servlet-handler/>-->
    <!--静态资源无法放行第三种解决方案-->
    <mvc:resources mapping="/images/**" location="/images/"></mvc:resources>
    <mvc:resources mapping="/js/**" location="/js/"></mvc:resources>
</beans>
First拦截器preHandle()执行!
Second的preHandle()执行!
handle22-----------22123
Second的postHandle()执行!
First拦截器postHandle执行!
Second的afterCompletion()执行!
First拦截器afterCompletion执行!

在这里插入图片描述
12. Spring和SpringMVC父子容器关系
在Spring整体框架的核心概念中,容器是核心思想,就是用来管理Bean的整个生命周期的,而在一个项目中,容器不一定只有一个,Spring中可以包括多个容器,而且容器有上下层关系,目前最常见的一种场景就是在一个项目中引入Spring和SpringMVC这两个框架,那么它其实就是两个容器,Spring是父容器,SpringMVC是其子容器,并且在Spring父容器中注册的Bean对于SpringMVC容器中是可见的,而在SpringMVC容器中注册的Bean对于Spring父容器中是不可见的,也就是子容器可以看见父容器中的注册的Bean,反之就不行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值