1. SpringMVC初识

1 SpringMVC的介绍

  1. springMVC是Spring框架的一部分,是基于java实现的一个轻量级web框架
  2. 学习SpringMVC框架最核心的就是DispatcherServlet的设计,掌握好DispatcherServlet是掌握SpringMVC的核心关键

2 基于XML的HelloWorld

  1. 创建maven项目–右键项目–Add Framework Support–勾选Web Application(4.0)
  2. 添加pom依赖
<dependencies>
    <!--可以不导该包,因为下面的包会把这个包的内容一起导入进来-->
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.2.3.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>5.2.3.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.2.3.RELEASE</version>
    </dependency>
</dependencies>
  1. 编写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_4_0.xsd"
         version="4.0">
    <!--配置DispatcherServlet-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--1. 关联springmvc的配置文件,其实init-param参数配置,可以在servlet中通过ServletConfig读取到 -->
        <!--2. 默认将springmvc的配置文件添加到/WEB-INF/的目录下,但配置文件名称必须是"<servlet-name>-servlet.xml",例如"springmvc-servlet.xml"
            3. 但本例中,想把配置文件放到resources文件夹下,也就是classpath对应的路径中,因此有如下配置-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <!--1. /*和/都表示拦截所有请求,/会拦截的请求不包含*.jsp,而/*的范围更大,还会拦截*.jsp这些请求,而DispatcherServlet中处理不了jsp文件,因此配成/*时,访问jsp文件会报错-->
        <!--2. 配置为/后,想请求一个内部的html页面会报错
                1. 当前web.xml文件会继承tomcat下的web.xml文件,而在tomcat-web.xml文件中,包含一个DefaultServlet处理类,用来处理静态资源
                2. 使用了/的方式会覆盖父web.xml对静态资源的处理,所以此时所有静态资源的访问,也需要由DispatcherServlet进行处理,而DispatcherServlet也处理不了html文件,因此会报404,请求不到
                3. jsp能处理是因为在父web.xml中,使用了JspServlet的处理类单独处理jsp文件,因此jsp文件会交给tomcat进行处理,而不是我们定义的DispatcherServlet,自然也不会报错-->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!--1. 为了html好用,可以添加如下内容,为了使用DefaultServlet,需要添加catalina.jar-->
    <!--2. 可以在web下直接创建html文件,通过http://localhost:8080/linux.html请求,发现好用-->
    <servlet>
        <servlet-name>default</servlet-name>
        <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
</web-app>
  1. applicationContext.xml:在resources下编写spring配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--配置前缀,最后/必须存在-->
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <!--配置后缀-->
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!--需要加/否则不生效-->
    <bean id="/hello" class="com.mashibing.controller.HelloController"></bean>
</beans>
  1. HelloController.java:需要导入servlet和jsp的jar包,否则编译不过去
package com.mashibing.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 {
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        //创建模型和视图对象
        ModelAndView mv = new ModelAndView();
        //将需要的值传递到model中
        mv.addObject("msg","helloSpringMVC");
        //设置要跳转的视图,也就是要跳转的页面的名称
        mv.setViewName("hello");
        return mv;
    }
}
  1. 创建hello.jsp页面
<%--
  Created by IntelliJ IDEA.
  User: root
  Date: 2020/3/5
  Time: 20:25
  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>
${msg}
</body>
</html>
  1. Artifacts–右键WEB-INF–Create Directory–lib–右键lib–Add Copy Of–Library Files–选中Tomcat中没有的所有jar包
  2. 配置tomcat,发送请求:http://localhost:8080/hello

3 基于注解的HelloWorld

  1. 添加pom依赖
  2. web.xml
  3. spring配置文件:applicationContext.xml
<!--注意添加该条,保证Spring能够管理HelloController对象-->
<context:component-scan base-package="com.mashibing"></context:component-scan>
  1. HelloController.java
package com.mashibing.controller;

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

@Controller
public class HelloController{
    /*
    * 1. @RequestMapping:就是用来标识此方法用来处理什么请求
    * 2. /可以取消,取消后默认也是从当前项目的根目录开始查找,一般在编写的时候看个人习惯
    * 3. @RequestMapping也可以用来加在类上,添加在类上时,表示为当前类的所有方法的请求地址添加一个前置路径,访问的时候必须要添加此路径,即需要访问/hello/hello才能访问到hello方法
    * 4. 当包含多个Controller,同时在不同Controller中包含同名请求时,需要在类上也添加@RequestMapping注释,因为很可能不同模块不同人编写,结果起了同样的名字,访问时就会报错
    * */
    @RequestMapping("/hello")
    public String hello(Model model){
        model.addAttribute("msg","hello,SpringMVC");
        //1. 视图解析器会将这个字符串与自身定义的前缀后缀进行拼接,从而找到真正要请求的jsp文件
        //2. 此处也可以返回一个视图对象,那么就不用视图解析器再对字符串进行处理了
        return "hello";
    }
}
  1. 编写hello.jsp
  2. 输入请求http://localhost:8080/hello

4 @RequestMapping

4.1 属性值
  1. value:要匹配的请求
  2. method:限制发送请求的方式: method={RequestMethod.POST}
  3. params:表示请求要接受的参数,如果定义了这个属性,那么发送的时候必须要添加该参数
    1. 直接写参数的名称:params = {“username”}
    2. 表示请求不能包含的参数:params = {"!username"}
    3. 表示请求中需要要包含的参数但是可以限制值:params = {“username!=123”,“age”}
  4. headers:request中必须包含指定的header值,该方法才能处理请求
  5. consumes:方法只处理Content-Type为指定值的请求,在request中,Content-Type用来告诉服务器当前发送的数据是什么格式
  6. produces:方法只处理Accept中包含指定值的请求,在request中,Accept用来告诉服务器,客户端能认识哪些格式,最好返回这些格式中的其中一种
package com.mashibing.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/mashibing")
public class HelloController{

    @RequestMapping("/hello")
    public String hello(Model model){
        model.addAttribute("msg","hello,SpringMVC");
        return "hello";
    }
    @RequestMapping(value = "/hello2",method = RequestMethod.POST)
    public String hello2(){
        return "hello";
    }

    @RequestMapping(value = "/hello3",params = {"username!=123","age"})
    public String hello3(String username){
        System.out.println(username);
        return "hello";
    }

    @RequestMapping(value = "/hello4",headers = {"User-Agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:73.0) Gecko/20100101 Firefox/73.0"})
    public String hello4(){
        return "hello";
    }
}

4.2 通配符
  1. @RequestMapping包含三种模糊匹配的方式
    1. ?:能替代任意一个字符
    2. *: 能替代任意多个字符和一层路径
    3. **:能代替多层路径
@RequestMapping(value = "/**/h*llo?")
public String hello5(){
    System.out.println("hello5");
    return "hello";
}

5 @PathVariable

  1. 可以获取请求路径中的值
  2. 如果不加@PathVariable,默认为url中,?name="zhangsan"中的这个name
@RequestMapping(value = "/pathVariable/{name}")
//如果参数列表中名称与url中占位符名称不一样,可以为PathVariable添加属性,表示该变量匹配url中哪个变量,建议填写
public String pathVariable(@PathVariable("name") String name){
    System.out.println(name);
    return "hello";
}

6 REST

  1. REST为表现层状态转化,是目前最流行的一个互联网软件架构,可以降低开发的复杂性,提高系统的可伸缩性
  2. 我们在获取资源的时候就是进行增删改查的操作,如果是原来的架构风格,需要发送四个请求
    1. 查询:localhost:8080/query?id=1
    2. 增加:localhost:8080/insert
    3. 删除:localhost:8080/delete?id=1
    4. 更新:localhost:8080/update?id=1
  3. 按照此方式发送请求的时候比较麻烦,需要定义多种请求,而在HTTP协议中,有不同的发送请求的方式,分别是GET、POST、PUT、DELETE等,我们如果能让不同的请求方式表示不同的请求类型就可以简化我们的查询
    1. 查询:localhost:8080/book/1:发送get请求
    2. 增加:localhost:8080/book:发送post请求
    3. 删除:localhost:8080/book/1:发送delete请求
    4. 更新:localhost:8080/book/1:发送put请求
  4. 我们在发送请求的时候只能发送post或者get,没有办法发送put和delete请求,因此需要在页面中,对请求类型进行转换,这也就是REST表现层状态转换的名称由来
  5. RestController.java
package com.mashibing.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Controller
public class RestController {

    @RequestMapping(value = "/user",method = RequestMethod.POST)
    public String add(){
        System.out.println("添加");
        return "success";
    }

    @RequestMapping(value = "/user/{id}",method = RequestMethod.DELETE)
    public String delete(@PathVariable("id") Integer id){
        System.out.println("删除:"+id);
        return "success";
    }

    @RequestMapping(value = "/user/{id}",method = RequestMethod.PUT)
    public String update(@PathVariable("id") Integer id){
        System.out.println("更新:"+id);
        return "success";
    }

    @RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
    public String query(@PathVariable("id") Integer id){
        System.out.println("查询:"+id);
        return "success";
    }
}
  1. 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_4_0.xsd"
         version="4.0">
    <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>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!--添加过滤器,该过滤器可以完成请求方式的转换,将post请求转换为put或delete-->
    <filter>
        <filter-name>hiddenFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>hiddenFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>
  1. rest.jsp
<%--
    Created by IntelliJ IDEA.
    User: root
        Date: 2020/3/6
            Time: 23:01
                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="/user" method="post">
            <input type="submit" value="增加">
        </form>
        <form action="/user/1" method="post">
            <!--在form表单中,需要配置一个input,name固定为_method,value配置为想转换成的请求-->
            <input name="_method" value="delete" type="hidden">
            <input type="submit" value="删除">
        </form>
        <form action="/user/1" method="post">
            <input name="_method" value="put" type="hidden">
            <input type="submit" value="修改">
        </form>
        <a href="/user/1">查询</a><br/>
    </body>
</html>
  1. success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isErrorPage="true" %>
<html>
    <head>
        <title>Title</title>
    </head>
    <body>
        666
    </body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值