1.Spring MVC概述:

Spring MVC是Spring提供的一个强大而灵活的web框架。借助于注解,Spring MVC提供了几乎是POJO的开发模式,使得控制器的开发和测试更加简单。这些控制器一般不直接处理请求,而是将其委托给Spring上下文中的其他bean,通过Spring的依赖注入功能,这些bean被注入到控制器中。

Spring MVC主要由DispatcherServlet、处理器映射、处理器(控制器)、视图解析器、视图组成。他的两个核心是两个核心:

处理器映射:选择使用哪个控制器来处理请求 
视图解析器:选择结果应该如何渲染


2.SpringMVC运行原理


1) Http请求 :客户端请求提交到DispatcherServlet。 
(2) 寻找处理器 :由DispatcherServlet控制器查询一个或多个HandlerMapping,找到处理请求的Controller。 
(3) 调用处理器 :DispatcherServlet将请求提交到Controller。 
(4)(5)调用业务处理和返回结果 :Controller调用业务逻辑处理后,返回ModelAndView。 
(6)(7)处理视图映射并返回模型 : DispatcherServlet查询一个或多个ViewResoler视图解析器,找到ModelAndView指定的视图。 
(8) Http响应 :视图负责将结果显示到客户端。


3.配置文件


1.添加Web.xml配置文件中关于SpringMVC的配置

<!--configure the setting of springmvcDispatcherServlet and configure the mapping-->
  <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:springmvc-servlet.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>




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

    <!--扫描注解包的范围-->
    <context:component-scan base-package="C"/>


     <!--开启默认servlet-handler-->

3.

在WEB-INF文件夹下创建名为jsp的文件夹,用来存放jsp视图。创建一个 hello.jsp


4.

建立Controller包

5.编写Controller代码

@Controller
@RequestMapping("/mvc")
public class MVCController {
    @RequestMapping("/index")
    public String hello(){
        return "hello";
    }

}




6. 启动服务器,键入  http://localhost:8080/项目名/mvc/index即可访问hello.jsp


4.Spring MVC常用注解

@Controller

负责注册一个bean 到spring 上下文中。

@RequestMapping

注解为控制器指定可以处理哪些 URL 请求。

其中参数常见有以下两个

@RequestMapping(value = "/upload",method = RequestMethod.POST)

一个代表URl请求,第二个代表提交方式(Get方式提交得意作为另个一方法进行重载)

@RequestParam@RequestParam 5.

自动装箱

创建一实体类User

public class User {
    private String name;
    private String pwd;
    private String email;

    public String getName() {
        return name;
    }

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

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}


Controller里编写方法

该方法由前台表单提供name pwd email 三个参数


再次Spring MVC自动装箱封装成User对象


@RequestMapping(value = "/register",method = RequestMethod.POST)
public String  register(User user){
    System.out.println(user.getName);
    return "index";
}


6、参数传递

有两种方法可以向前台传递参数


①耦合


可以使用 HttpSession 来存储参数,这里运用是以前学习的Servlet技术,不再赘述。


②解耦


在我们程序运行过程时并不需要数据长时间存在,可能只需要在一次转发时,存放在Session就太占用资源了


我们就需要flash作用域了


@RequestMapping(value = "/register",method = RequestMethod.POST)
public String register(User user, RedirectAttributesModelMap redirectAttributesModelMap){
    redirectAttributesModelMap.addFlashAttribute("user",user);
    return "redirect:index";//redirect:代表重定向
}



user键值对只会存在重定向后下一次刷新之前。


如果不需要重定向时可以使用ModelMap,作用域是一次request


@RequestMapping(value = "/register",method = RequestMethod.POST)
public String register(User user, ModelMap modelMap){
   modelMap.addAttribute("user",user);
    return "redirect:index";
}


并不是的,这时我们需要在类之前加一个注解


@SessionAttributes("user")
public class MVCController {

此注解的作用是把

ModelMap中键为user的作用域提升到session,并且在request作用域中仍然存在

7.文件上传及下载


在存在文件上传时,form表单中有一个属性要特别设置


就是enctype


enctype 属性规定在发送到服务器之前应该如何对表单数据进行编码,它有三个值

默认的编码方式(空格转换为 "+" 加号,特殊符号转换为 ASCII HEX 值)。使用get方式提交时,把表单数据(name1=value1&name2=value2...)以键值对append到url后,用  '?' 分割url和参数。使用post方式提交时,把表单数据以键值对放在请求体中传输。


2.multipart/form-data:表单数据被编码为一条消息,页上的每个<input>对应消息中的一个部分,用boundary=--------36243265420146"分割各个部分(boundary值由浏览器生成)。它不会对字符进行编码, 一般用于传输二进制文件




3. text/plain:表单数据中的空格转换为 "+" 加号,但不对特殊字符编码。(get方式会这样,post时不会)


<form method="post" enctype="multipart/form-data">
@RequestMapping(value = "/upload",method = RequestMethod.POST)
public String upload(@RequestParam("file") MultipartFile file) throws IOException {
    String fileName=file.getOriginalFilename();
    file.transferTo(new File("F:\\upload",fileName));
    return "redirect:list";
}


@RequestMapping("/download")
public void download(String fileName, HttpServletResponse response) throws IOException {
    //添加报文头,只有在报文里添加了"Content-disposition", "attachment; filename="打开文件的时候就会以下载文件的形式弹出,
    //response.setContentType(MIME)的作用是使客户端浏览器,区分不同种类的数据,并根据不同的MIME调用浏览器内不同的程序嵌入模块来处理相应的数据。
   // 例如web浏览器就是通过MIME类型来判断文件是GIF图片。通过MIME类型来处理json字符串。
    response.addHeader("Content-Disposition","attachment;filename="+fileName);
    response.setContentType("application/octet-stream");
    OutputStream out=response.getOutputStream();
    InputStream in=new FileInputStream(new File("F:\\upload",fileName));
    IOUtils.copy(in,out);
    out.close();//out要从in中获得数据,就是依赖于in,所以要求out先关闭
    in.close();
}