SpringMVC学习

如果不喜欢博客样式,可以查看文档:SpringMVC学习文档


SpringMVC学习

1. SpringMVC介绍

Spring Web MVC是基于Servlet API构建的原始Web框架,从一开始就已包含在Spring Framework中。 正式名称“ Spring Web MVC”来自其源模块的名称(spring-webmvc),但它通常被称为“ Spring MVC”。

SpringMVC结构如下:
SpringMVC学习_第1张图片

2. 开始SpringMVC

2.1 添加maven依赖

pom.xml


    <dependency>
      <groupId>commons-logginggroupId>
      <artifactId>commons-loggingartifactId>
      <version>1.2version>
    dependency>


    
    <dependency>
      <groupId>com.alibabagroupId>
      <artifactId>fastjsonartifactId>
      <version>1.2.62version>
    dependency>

    
    <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>javax.servlet-apiartifactId>
      <version>4.0.1version>
      <scope>providedscope>
    dependency>

    
    <dependency>
      <groupId>javax.servlet.jspgroupId>
      <artifactId>jsp-apiartifactId>
      <version>2.1version>
      <scope>providedscope>
    dependency>

    
    <dependency>
      <groupId>javax.servlet.jsp.jstlgroupId>
      <artifactId>jstlartifactId>
      <version>1.2version>
    dependency>

    
    <dependency>
      <groupId>javax.servlet.jsp.jstlgroupId>
      <artifactId>jstl-apiartifactId>
      <version>1.2version>
    dependency>
    
    <dependency>
      <groupId>org.glassfish.webgroupId>
      <artifactId>jstl-implartifactId>
      <version>1.2version>
    dependency>

    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webmvcartifactId>
      <version>5.2.6.RELEASEversion>
    dependency>


    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webartifactId>
      <version>5.2.6.RELEASEversion>
    dependency>

    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-contextartifactId>
      <version>5.2.6.RELEASEversion>
    dependency>

2.2 编写SpringMVC分发器

web.xml



<web-app>
  <display-name>Archetype Created Web Applicationdisplay-name>
  
  <servlet>
    <servlet-name>springmvcdemoservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    <load-on-startup>1load-on-startup>
  servlet>
  
  <servlet-mapping>
    <servlet-name>springmvcdemoservlet-name>
    <url-pattern>*.dourl-pattern>
  servlet-mapping>
  
web-app>

2.3 编写Controller

HelloController.java

package edu.mju.controller;

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 HelloController implements Controller {
     
    @Override
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
     
        ModelAndView modelAndView = new ModelAndView();
        //封装要显示到视图中的数据
        modelAndView.addObject("msg","Hello,SpringMVC!");
        //视图名
        modelAndView.setViewName("HelloMsg");
        return modelAndView;
    }
}

2.4 编写SpringMVC配置文件

    1. 配置HandlerMapping
    1. 配置HandlerAdapter
    1. 配置渲染器
    1. 配置请求和处理器

springmvcdemo-servlet.xml


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       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/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">

    
    <bean id="handlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
    
    <bean id="handlerAdapter" class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
    
    <bean id="jspviewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        
        <property name="prefix" value="/WEB-INF/jsp/"/>
        
        <property name="suffix" value=".jsp"/>
    bean>
    
    <bean name="/hello.do" class="edu.mju.controller.HelloController"/>

beans>

2.5 编写视图文件

HelloMsg.jsp

<%@page isELIgnored="false" %>


${msg}


2.6 总结

2.6.1 要点

    1. modelAndView.setViewName("HelloMsg")视图名与视图文件名一致,
    1. DispatcherServlet是核心分发器。
    1. SpringMVC配置文件进行如下四步:
      • 配置HandlerMapping
      • 配置HandlerAdapter
      • 配置渲染器
      • 配置请求和处理器

2.6.2 DispatcherServlet初始化参数表

参数 说明
contextClass 实现ConfigurableWebApplicationContext的类,该Servlet将实例化并在本地配置它。默认情况下,使用XmlWebApplicationContext。
contextConfigLocation 传递给上下文实例的字符串(由contextClass指定),以指示可以在哪里找到上下文。 该字符串可能包含多个字符串(使用逗号作为分隔符)以支持多个上下文。 对于具有两次定义的bean的多个上下文位置,以最新位置为准。
namespace WebApplicationContext的命名空间。默认为[servlet-name]-servlet
throwExceptionIfNoHandlerFound 在找不到请求的处理程序时是否引发NoHandlerFoundException。 然后可以使用HandlerExceptionResolver捕获该异常(例如,通过使用@ExceptionHandler控制器方法),然后将其作为其他任何异常进行处理。
默认情况下,它设置为false,在这种情况下,DispatcherServlet将响应状态设置为404(NOT_FOUND),而不会引发异常。
请注意,如果还配置了默认servlet处理,则始终将未解决的请求转发到默认servlet,并且永远不会引发404。

3. 使用注解开发

3.1 配置SpringMVC映射文件

resources目录底下,新建mvc.xml文件,配置如下


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.3.xsd
       http://www.springframework.org/schema/tx
       https://www.springframework.org/schema/tx/spring-tx.xsd">
    
    <bean id="jspviewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        
        <property name="prefix" value="/WEB-INF/jsp/"/>
        
        <property name="suffix" value=".jsp"/>
    bean>
    
    <context:component-scan base-package="edu.mju.controller"/>
beans>

:扫描edu.mju.controller包底下的注解

3.2 使用注解编写Controller

HelloController2.java

package edu.mju.controller;

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
public class HelloController2 {
     

    @RequestMapping("/hello2")
    public ModelAndView hello(HttpServletRequest req, HttpServletResponse resp){
     
        ModelAndView modelAndView = new ModelAndView();
        //封装要显示到视图中的数据
        modelAndView.addObject("msg","Hello,SpringMVC--annotation!");
        //视图名
        modelAndView.setViewName("HelloMsg2");
        return modelAndView;
    }
}

  • @Controller:声明这是控制器
  • @RequestMapping("/xxx"):请求映射到控制器方法

3.3 web.xml配置SpringMVC映射文件



<web-app>
  <display-name>Archetype Created Web Applicationdisplay-name>
  
  <servlet>
    <servlet-name>springmvcdemoservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:mvc.xmlparam-value>
    init-param>
    <load-on-startup>1load-on-startup>
  servlet>
  
  <servlet-mapping>
    <servlet-name>springmvcdemoservlet-name>
    <url-pattern>*.dourl-pattern>
  servlet-mapping>
  
web-app>

初始化参数表参考上面2.6.2

3.4 在渲染器指定文件底下,新建JSP页面

<%@page isELIgnored="false" %>


${msg}


3.5 启动服务器

浏览器输入:http://localhost:8080/SpringMVC/hello2.do
页面显示:Hello,SpringMVC–annotation! 则配置成功。

4. Controller配置总结

4.1 URL对应Bean方式

通过访问/hello.do,就会寻找name为/hello.do的Bean


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       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/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">

    
    <bean id="handlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
    
    <bean id="handlerAdapter" class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
    
    <bean id="jspviewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        
        <property name="prefix" value="/WEB-INF/jsp/"/>
        
        <property name="suffix" value=".jsp"/>
    bean>
    
    <bean name="/hello.do" class="edu.mju.controller.HelloController"/>

beans>

4.2 URL分配Bean方式

该配置可适用通配符


<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="mappings">
        <props>
            
            <prop key="/hello.do">helloControllerprop>
        props>
    property>
bean>

<bean id="helloController" class="edu.mju.controller.HelloController"/>

4.3 URL匹配Bean(Spring5已移除)

该方法在Spring5已被移除


<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>

<bean id="helloController" class="edu.mju.controller.HelloController"/>

4.4 注解方式

在SpringMVC配置文件中加入:


<context:component-scan base-package="edu.mju.controller"/>

在Controller中加入注解:

package edu.mju.controller;

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
public class HelloController2 {
     

    @RequestMapping("/hello2.do")
    public ModelAndView hello(HttpServletRequest req, HttpServletResponse resp){
     
        ModelAndView modelAndView = new ModelAndView();
        //封装要显示到视图中的数据
        modelAndView.addObject("msg","Hello,SpringMVC--annotation!");
        //视图名
        modelAndView.setViewName("HelloMsg2");
        return modelAndView;
    }
}

5 结果跳转方式

5.1 通过ModelandView对象

通过设置ModelandView()对象,根据View的名称,和视图渲染器跳转到 指定页面
指定页面:视图渲染器的前缀+视图名(ViewName)+视图渲染器的后缀

ModelAndView modelAndView = new ModelAndView();
//封装要显示到视图中的数据
modelAndView.addObject("msg","Hello,SpringMVC--annotation!");
//视图名
modelAndView.setViewName("HelloMsg2");

5.2 通过ServletAPI对象

  1. HttpServletResponse输出语句
package edu.mju.controller;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Controller
public class HelloController3 {
     
    @RequestMapping("/hello3.do")
    public void hello(HttpServletRequest req, HttpServletResponse resp) throws IOException {
     
        resp.getWriter().println("hello,SpringMVC by HttpServlet api!");
    }
}
  1. HttpServletResponse重定向
package edu.mju.controller;

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

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

@Controller
public class HelloController3 {
     
    @RequestMapping("/hello3.do")
    public void hello(HttpServletRequest req, HttpServletResponse resp) throws IOException {
     
        //resp.getWriter().println("hello,SpringMVC by HttpServlet api!");
        //重定向
        resp.sendRedirect("index.jsp");

    }
}

  1. HttpServletResponse请求转发
package edu.mju.controller;

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

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

@Controller
public class HelloController3 {
     
    @RequestMapping("/hello3.do")
    public void hello(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
     
        //resp.getWriter().println("hello,SpringMVC by HttpServlet api!");
        //重定向
        //resp.sendRedirect("index.jsp");
        //请求转发
        req.getRequestDispatcher("index.jsp").forward(req,resp);
    }
}

5.3 通过SpringMVC实现——不配置视图渲染器

5.3.1 转发实现(一)

package edu.mju.controller;

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

@Controller
public class HelloController4 {
     
    @RequestMapping("/hello4.do")
    public String hello()  {
     
        //转发
        return "index.jsp";
    }
}

5.3.2 转发实现(二)

package edu.mju.controller;

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

@Controller
public class HelloController4 {
     
    @RequestMapping("/hello4.do")
    public String hello()  {
     
        //转发1
        //return "index.jsp";
        //转发2
        return "forward:index.jsp";
    }
}

5.3.3 重定向

package edu.mju.controller;

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

@Controller
public class HelloController4 {
     
    @RequestMapping("/hello4.do")
    public String hello()  {
     
        //转发1
        //return "index.jsp";
        //转发2
        //return "forward:index.jsp";
        //重定向
        return "redirect:index.jsp";
    }
}

5.4 通过SpringMVC实现——配置视图渲染器

5.4.1 请求转发

package edu.mju.controller;

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

@Controller
public class HelloController5 {
     
    @RequestMapping("/hello5.do")
    public String hello()  {
     
        //请求转发
        return "HelloMsg";
    }
}

5.4.2 重定向

重定向不需要视图渲染器

package edu.mju.controller;

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

@Controller
public class HelloController5 {
     
    @RequestMapping("/hello5.do")
    public String hello()  {
     
        return "redirect:index.jsp";
    }
}

6 数据的处理

6.1 简单提交数据的处理

6.1.1 提交的域名称和处理方法的参数名称一致

DataController.java

package edu.mju.controller;

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

@Controller
public class DataController {
     
    @RequestMapping("/data.do")
    public String data(String data){
     
        System.out.println("数据:"+data);
        return "index.jsp";
    }
}

这里的处理方法的参数为data,运行后在浏览器输入如下地址:

http://localhost:8080/springmvcdemo/data.do?data=数据

此时,后台会输出

数据:数据

6.1.2 提交的域名称和处理方法的参数名称不一致

添加@RequestParam("xxx")属性,xxx是提交的域的名称

DataController.java

package edu.mju.controller;

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

@Controller
public class DataController {
     
    @RequestMapping("/data.do")
    public String data(@RequestParam("datas") String data){
     
        System.out.println("数据:"+data);
        return "index.jsp";
    }
}

这里的处理方法的参数为data,运行后在浏览器输入如下地址:

http://localhost:8080/springmvcdemo/data.do?datas=123

此时,后台会输出

数据:123

6.2 复杂提交数据的处理

6.2.1 提交数据为对象

表单的域名和对象的属性名一致

User.java

package edu.mju.entity;
public class User {
     
    private int id ;
    private String name;
    private String pwd;

    public int getId() {
     
        return id;
    }

    public void setId(int id) {
     
        this.id = id;
    }

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

DataController.java

<!--其他地方一致-->
@RequestMapping("/user.do")
public String user(User user){
     
    System.out.println(JSONObject.toJSONString(user));
    return "index.jsp";
}

运行后在浏览器输入如下地址:

http://localhost:8080/springmvcdemo/user.do?name=labi&pwd=xiaoxin
此时,后台会输出

{
     "id":0,"name":"labi","pwd":"xiaoxin"}

6.3 数据显示

通过ModelandView和ModelMap均可以将数据封装显示到视图层中。
区别:

  • ModelandView需要视图解析器,可以指定跳转的视图。
  • ModelMap不需要视图解析器,不可以指定跳转的视图。

6.3.1 通过ModelandView

通过该方法,需要配置视图渲染器


<bean id="jspviewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
    
    <property name="prefix" value="/WEB-INF/jsp/"/>
    
    <property name="suffix" value=".jsp"/>
bean>

HelloController.java

public class HelloController implements Controller {
     
    @Override
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
     
        ModelAndView modelAndView = new ModelAndView();
        //封装要显示到视图中的数据
        modelAndView.addObject("msg","Hello,SpringMVC!");
        //视图名
        modelAndView.setViewName("HelloMsg");
        return modelAndView;
    }
}

这里的modelAndView.addObject("msg","Hello,SpringMVC!");相当于req.setAttribute("msg","Hello,SpringMVC!")

6.3.2 通过ModelMap

ModelMap必须作为参数

DataController.java

<!--其他一致-->
@RequestMapping("/modelMap.do")
public String data(@RequestParam("datas") String data, ModelMap model){
     
    model.addAttribute("data",data);
    System.out.println("数据:"+data);
    return "index.jsp";
}

index.jsp

<%@page isELIgnored="false" %>


Hello World!index.jsp page

${ data }

运行后在浏览器输入如下地址:

http://localhost:8080/springmvcdemo/modelMap.do?datas=itdatas

运行结果如图:
SpringMVC学习_第2张图片

6.4 乱码处理

在上面的数据处理时,当我们的数据为中文时,获取到的数据会出现乱码。

SpringMVC中,处理乱码通过过滤器来处理。

    1. 在web.xml添加如下代码
    
    <filter>
      <filter-name>CharacterEncodingFilterfilter-name>
      <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
      <init-param>
        <param-name>encodingparam-name>
        <param-value>utf-8param-value>
      init-param>
    filter>
    <filter-mapping>
      <filter-name>CharacterEncodingFilterfilter-name>
      <url-pattern>/url-pattern>
    filter-mapping>
    
    
    1. 页面编码统一为UTF8
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    
    1. tomcat统一编码为UTF8

    idea配置tomcat:VM options:-Dfile.encoding=UTF-8

6.5 JSON处理

6.5.1 相关jar包


<dependency>
    <groupId>com.fasterxml.jackson.jaxrsgroupId>
    <artifactId>jackson-jaxrs-json-providerartifactId>
    <version>2.11.1version>
dependency>

6.5.2 配置json转换器

mvc.xml

    
    <bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/plain;charset=UTF-8value>
            list>
        property>
    bean>
    <bean id="jackson2HttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
    
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="stringHttpMessageConverter"/>
                <ref bean="jackson2HttpMessageConverter"/>
            list>
        property>
    bean>

6.5.3 Controller.java

package edu.mju.controller;

import edu.mju.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

@Controller
public class JsonController {
     
    @RequestMapping("/json.do")
    @ResponseBody
    public List<User> json(){
     
        List<User> users = new ArrayList<User>();
        users.add(new User(1,"one","ow"));
        users.add(new User(2,"two","ow2"));
        users.add(new User(3,"three","ow3"));
        return users;
    }
}

@ResponseBody:响应为主体内容

User.java

package edu.mju.entity;

public class User {
     
    private int id ;
    private String name;
    private String pwd;

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

    public int getId() {
     
        return id;
    }

    public void setId(int id) {
     
        this.id = id;
    }

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

6.5.4 前端页面

<%@page isELIgnored="false" %>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>


    
    


Hello World!index.jsp page

${ data }
ID 用户名 密码

7 Restful风格

参考:https://www.runoob.com/w3cnote/restful-architecture.html

REST全称是Representational State Transfer,中文意思是表述(编者注:通常译为表征)性状态转移。 它首次出现在2000年Roy Fielding的博士论文中,Roy Fielding是HTTP规范的主要编写者之一。 他在论文中提到:“我这篇文章的写作目的,就是想在符合架构原理的前提下,理解和评估以网络为基础的应用软件的架构设计,得到一个功能强、性能好、适宜通信的架构。REST指的是一组架构约束条件和原则。” 如果一个架构符合REST的约束条件和原则,我们就称它为RESTful架构。

REST本身并没有创造新的技术、组件或服务,而隐藏在RESTful背后的理念就是使用Web的现有特征和能力, 更好地使用现有Web标准中的一些准则和约束。虽然REST本身受Web技术的影响很深, 但是理论上REST架构风格并不是绑定在HTTP上,只不过目前HTTP是唯一与REST相关的实例。 所以我们这里描述的REST也是通过HTTP实现的REST。

可以使用@PathVariable访问捕获的URI变量,如下面的示例所示

@GetMapping("/owners/{ownerId}/pets/{petId}")
public Pet findPet(@PathVariable Long ownerId, @PathVariable Long petId) {
     
    // ...
}

您可以使用全局模式和通配符来映射请求:

符号 描述 案例
? 匹配一个字符 /pages/t?st.html=/pages/test.html=/pages/t3st.html
* 匹配路径段中的零个或多个字符 /projects/*/versions=/projects/spring/versions/projects/spring/boot/versions
** 匹配零个或多个路径段,直到路径结束 /resources/**=/resources/file.png=/resources/images/file.png
{name} 匹配路径段并将其捕获为名为name的变量 /projects/{project}/versions=/projects/spring/versions,project=spring
{name:[a-z]+} 将正则表达式[a-z] +匹配为一个名为"name的路径变量 /projects/{project:[a-z]+}/versions=/projects/spring/versions/projects/spring1/versions

7.1 案例

DataController.java

package edu.mju.controller;

import com.alibaba.fastjson.JSONObject;
import edu.mju.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class DataController {
     
    @RequestMapping("/{id}/{uid}/delete.do")
    public String data(@PathVariable int uid,@PathVariable int id){
     
        System.out.println("id="+id);
        System.out.println("uid="+uid);
        return "/index.jsp";
    }
}

运行访问如下网址:

http://localhost:8080/springmvcdemo/1/2/delete.do
运行结果为:

id=1
uid=2

8 文件上传

8.1 导入文件上传jar包

pom.xml

    
    <dependency>
      <groupId>commons-iogroupId>
      <artifactId>commons-ioartifactId>
      <version>2.7version>
    dependency>

    
    <dependency>
      <groupId>commons-fileuploadgroupId>
      <artifactId>commons-fileuploadartifactId>
      <version>1.4version>
    dependency>

8.2 配置SpringMVC的解析器

mvc.xml

    
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        
        <property name="defaultEncoding" value="utf-8"/>
        
        <property name="maxUploadSize" value="10485760000"/>
        
        <property name="maxInMemorySize" value="40960"/>
    bean>

8.3 文件上传控制器

FileUploadController.java

package edu.mju.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

@Controller
public class FileUploadController {
     
    @RequestMapping("/upload.do")
    public String fileupload(@RequestParam("file") CommonsMultipartFile files , HttpServletRequest req) throws IOException {
     
        //获取文件名
        String filename = files.getOriginalFilename();
        //获取上传文件的路径
        String path = req.getRealPath("/fileUpload");
        System.out.println(path);
        InputStream is = files.getInputStream();
        OutputStream os = new FileOutputStream(new File(path,filename));

        int len = 0 ;
        byte[] buffer = new byte[1024];
        while((len=is.read(buffer))!=-1){
     
            os.write(buffer,0,len);
        }

        os.close();
        is.close();

        return "/index.jsp";
    }
}

@RequestParam(xxx"):该注解必须加,且与jsp页面name相同

8.4 JSP文件上传页面

fileUpload.jsp

<%@page isELIgnored="false" %>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>


Hello World!index.jsp page

file:

9 SpringMVC拦截器

9.1 实现HandlerInterceptor接口

MyIntercceptor.java

package edu.mju.interceptor;

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

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

public class MyIntercceptor implements HandlerInterceptor {
     
    /**
     *  在请求处理的方法之前执行
     * @param request
     * @param response
     * @param handler
     * @return true:执行下一个拦截器  false:不执行下一个拦截器
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
     
        System.out.println("------------------处理前------------------");
        response.sendRedirect(request.getContextPath()+"/index.jsp");
        return false;
    }


    /**
     *  在请求处理的方法执行之后执行
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
     
        System.out.println("------------------处理后------------------");
    }

    /**
     *  在DispatcherServlet处理后执行
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
     

    }
}

9.2 配置拦截器

mvc.xml


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.3.xsd
       http://www.springframework.org/schema/tx
       https://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    
    <mvc:interceptors>
        <mvc:interceptor>
            
            <mvc:mapping path="/**"/>
            <bean class="edu.mju.interceptor.MyIntercceptor"/>
        mvc:interceptor>
    mvc:interceptors>


    
    <context:component-scan base-package="edu.mju.controller"/>
beans>

9.3 实现简单登陆拦截器

9.3.1 实体类

User.java

package edu.mju.entity;
public class User {
     
    private Integer id ;
    private String name;
    private String pwd;

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

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

    public String getPwd() {
     
        return pwd;
    }

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

这里的ID需要设置为Integer类型,否则为空时,无法类型转换!

9.3.2 自定义拦截器

LoginIntercceptor.java

package edu.mju.interceptor;

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

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

public class LoginIntercceptor implements HandlerInterceptor {
     
    //允许通过的地址
    private List<String> allowedAddress;

    public void setAllowedAddress(List<String> allowedAddress) {
     
        this.allowedAddress = allowedAddress;
    }

    public List<String> getAllowedAddress() {
     
        return allowedAddress;
    }

    /**
     * 在请求处理的方法之前执行
     * @param request
     * @param response
     * @param handler
     * @return true:执行下一个拦截器  false:不执行下一个拦截器
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
     
        String url = request.getRequestURL().toString();
        //判断session中是否有值
        Object user = request.getSession().getAttribute("user");
        if(user!=null){
     
            return true;
        }
        for(String temp:allowedAddress){
     
            if(url.endsWith(temp)){
     
                return true;
            }
        }
        response.sendRedirect(request.getContextPath()+"/login.jsp");
        return false;
    }


    /**
     *  在请求处理的方法执行之后执行
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
     
        System.out.println("------------------处理后------------------");
    }

    /**
     *  在DispatcherServlet处理后执行
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
     

    }
}

9.3.3 配置拦截器

mvc.xml


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.3.xsd
       http://www.springframework.org/schema/tx
       https://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
    <mvc:interceptors>
        <mvc:interceptor>
            
            <mvc:mapping path="/**"/>
            <bean class="edu.mju.interceptor.LoginIntercceptor">
                <property name="allowedAddress">
                    <list>
                        <value>login.dovalue>
                        <value>login.jspvalue>
                    list>
                property>
            bean>
        mvc:interceptor>
    mvc:interceptors>

    
    <bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/plain;charset=UTF-8value>
            list>
        property>
    bean>
    <bean id="jackson2HttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
    
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="stringHttpMessageConverter"/>
                <ref bean="jackson2HttpMessageConverter"/>
            list>
        property>
    bean>

    
    <context:component-scan base-package="edu.mju.controller"/>

beans>

9.3.4 编写控制器

UserController.java

package edu.mju.controller;

import edu.mju.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;
@Controller
public class UserController {
     
    @RequestMapping(value = "/login.do" , method = RequestMethod.POST)
    public String login(User user, HttpSession session){
     
        if("xiaoxin".equals(user.getName()) && "xiaoxin".equals(user.getPwd())){
     
            session.setAttribute("user",user);
            return "redirect:/index.jsp";
        }
        return "redirect:/login.jsp";
    }
}

9.3.5 前端登陆页面

login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    登陆界面


用户名:
密码

喜欢的朋友,欢迎帮我点个star:docsify——gitee地址

你可能感兴趣的:(Java框架,spring,mvc)