SpringMVC

SpringMVC

1、什么是MVC

  • MVC代表Model、View、Controller,是一种软件设计规范

  • 是将逻辑、数据、显示分离的方法来组织代码

  • MVC主要作用是降低显示与逻辑之间的双向耦合

  • MVC不是一种设计模式,而是架构模式

Model(模型层):包含数据和模型,现在一般都分为数据层Dao和服务处Service

View(视图层):代表用户界面

Controller(控制层):主要负责接受用户请求,将用户数据交给模型层处理,处理后再将返回的数据返回给视图层

2、初识SpringMVC

2.1、SpringMVC执行原理

简略:

发起的请求被前置控制器处理,使用请求参数生成代理请求,找到对应的控制器,控制器调用模型层,对数据进行处理,然后将控制器将返回的数据交给前置控制器,前置控制器使用模型与视图渲染结果,将结果返回控制中心,最后将结果返回给请求者

  1. DispatcherServlet表示前置控制器,是整个SpringMVC的控制中心。用户发出请求,DispatcherServlet接收请求并拦截请求。

    我们假设请求的url为 : http://localhost:8080/SpringMVC/hello

    如上url拆分成三部分:

    http://localhost:8080服务器域名

    SpringMVC是部署在服务器上的web站点

    hello表示控制器

    通过分析,如上url表示为:请求位于服务器localhost:8080上的SpringMVC站点的hello控制器。

  2. HandlerMapping为处理器映射。DispatcherServlet调用HandlerMapping,HandlerMapping根据请求url查找Handler。

  3. HandlerExecution表示具体的Handler,其主要作用是根据url查找控制器,如上url被查找控制器为:hello。

  4. HandlerExecution将解析后的信息传递给DispatcherServlet,如解析控制器映射等。

  5. HandlerAdapter表示处理器适配器,其按照特定的规则去执行Handler。

  6. Handler让具体的Controller执行。

  7. Controller将具体的执行信息返回给HandlerAdapter,如ModelAndView。

  8. HandlerAdapter将视图逻辑名或模型传递给DispatcherServlet。

  9. DispatcherServlet调用视图解析器(ViewResolver)来解析HandlerAdapter传递的逻辑视图名。

  10. 视图解析器将解析的逻辑视图名传给DispatcherServlet。

  11. DispatcherServlet根据视图解析器解析的视图结果,调用具体的视图。

  12. 最终视图呈现给用户

3、使用注解配置SpringMVC

项目结构图:

image-20200407185016537

首先配置pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>SpringMVCStudy</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>springmvc-01</module>
    </modules>

    <properties>
        <maven.compiler.source>1.9</maven.compiler.source>
        <maven.compiler.target>1.9</maven.compiler.target>
    </properties>


    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/Java</directory>
                <excludes>
                    <exclude>**/*.java</exclude>
                </excludes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.* </include>
                </includes>
            </resource>
        </resources>
    </build>

</project>

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

    <!-- 自动扫描包,让指定包下的注解生效,由IOC容器统一管理 -->
    <context:component-scan base-package="com.zhang.controller"/>
    <!-- 让Spring MVC不处理静态资源 -->
    <mvc:default-servlet-handler />
    <!--
    支持mvc注解驱动
        在spring中一般采用@RequestMapping注解来完成映射关系
        要想使@RequestMapping注解生效
        必须向上下文中注册DefaultAnnotationHandlerMapping
        和一个AnnotationMethodHandlerAdapter实例
        这两个实例分别在类级别和方法级别处理。
        而annotation-driven配置帮助我们自动完成上述两个实例的注入。
     -->
    <mvc:annotation-driven />

    <!-- 视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          id="internalResourceViewResolver">
        <!-- 前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <!-- 后缀 -->
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

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>
        <!--通过初始化参数指定SpringMVC配置文件的位置,进行关联-->
        <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>

    <!--所有请求都会被springmvc拦截 -->
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

中/ 和 /* 的区别:< url-pattern > / </ url-pattern > 不会匹配到.jsp, 只针对我们编写的请求;即:.jsp 不会进入spring的 DispatcherServlet类 。< url-pattern > /* </ url-pattern > 会匹配 *.jsp,会出现返回 jsp视图 时再次进入spring的DispatcherServlet 类,导致找不到对应的controller所以报404错。

  • 注意web.xml版本问题,要最新版!
  • 注册DispatcherServlet
  • 关联SpringMVC的配置文件
  • 启动级别为1
  • 映射路径为 / 【不要用/*,会404】

HelloController:

package com.zhang.controller;

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

@Controller
public class HelloController {

    @RequestMapping("/hello")
    public String hello(Model model){
        model.addAttribute("msg","helloword");
        return "hello";
    }

}

@Controller修饰代表它是一个controller

可以接受请求

@RequestMapping("/hello")表示可以接收hello请求

model存放的是下个页面可以读取的信息

return “hello”; 用hello和视图解析器的前缀和后缀进行拼接变成了WEB-INF/jsp/hello.jsp

,然后转到该页面

可能遇到的问题:访问出现404,排查步骤:

  1. 查看控制台输出,看一下是不是缺少了什么jar包。
  2. 如果jar包存在,显示无法输出,就在IDEA的项目发布中,添加lib依赖!
  3. 重启Tomcat 即可解决!

3.1、Controller

  • 控制器负责提供访问应用程序的行为,通常通过接口和注解两种方式实现

  • 控制器负责解析用户请求并将其转化为一个模型

  • 在Spring MVC中一个控制器类可以包含多个方法

  • 在Spring MVC中,对于Controller的配置方式有很多种

@Controller注解类型用于声明Spring类的实例是一个控制器,它会被spring托管

spring为了能扫描到所写的注解需要在springmvc-servlet.xml中加入

<context:component-scan base-package=“com.zhang.controller”/>

在controller中return的页面都是可以复用的

3.2、RequestMapping

RequestMapping是可以将我们的url地址映射到一个控制器类或者一个处理方法上

当我们需要将其映射到一个类上时可以这么写:

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

    @RequestMapping("/hello")
    public String hello(Model model){
        model.addAttribute("msg","helloword");
        return "hello";
    }

}

映射到一个类上以后再访问就需要使用

http://localhost:8080/zhang/hello

它会先将url中的zhang对@RequestMapping("/zhang")进行匹配,再用hello匹配@RequestMapping("/hello")

当直接写到方法上:

@Controller
public class HelloController {

    @RequestMapping("/hello")
    public String hello(Model model){
        model.addAttribute("msg","helloword");
        return "hello";
    }

}

http://localhost:8080/hello

3.3、RestFul风格

改变helloController代码为:

@Controller
public class HelloController {

    @RequestMapping("/hello")
    public String hello(int a,int b,Model model){
        int i = a+b;
        model.addAttribute("msg",i);
        return "hello";
    }

}

那么我们可以通过这种url访问到hello

http://localhost:8080/hello?a=1&b=2 结果是3

RestFul风格则是改变了以往的url风格

传统:

​ http://127.0.0.1/item/queryItem.action?id=1 查询,GET

​ http://127.0.0.1/item/saveItem.action 新增,POST

​ http://127.0.0.1/item/updateItem.action 更新,POST

​ http://127.0.0.1/item/deleteItem.action?id=1 删除,GET或POST

RestFul:

​ http://127.0.0.1/item/1 查询,GET

​ http://127.0.0.1/item 新增,POST

​ http://127.0.0.1/item 更新,PUT

​ http://127.0.0.1/item/1 删除,DELETE

RestFul是根据不同的请求类型来判断调用哪中方法

修改controller代码:

@Controller
public class HelloController {

    @RequestMapping("/hello/{a}/{b}")
    public String hello(@PathVariable("a") int a,@PathVariable("b") int b, Model model){
        int i = a+b;
        model.addAttribute("msg",i);
        return "hello";
    }

}
  • @PathVariable的作用是让方法参数绑定到一个url模板变量中

  • 将int a绑定到url中{a},将int b绑定到url中{b}

  • 那么我们现在需要通过http://localhost:8080/hello/1/2这样的url来访问

如何实现不同的提交方式,来调用不同的代码:

修改controller代码:

@Controller
public class HelloController {

    //@RequestMapping(value = "/hello/{a}/{b}",method = RequestMethod.GET) 等同于下面的注解
    @GetMapping("/hello/{a}/{b}")
    public String getHello(@PathVariable("a") int a,@PathVariable("b") int b, Model model){
        int i = a+b;
        model.addAttribute("msg",i);
        return "hello";
    }
//@RequestMapping(value = "/hello/{a}/{b}",method = RequestMethod.Post)  等同于下面的注解
    @PostMapping("/hello/{a}/{b}")
    public String postHello(@PathVariable("a") int a,@PathVariable("b") int b, Model model){
        int i = a+b;
        model.addAttribute("msg",i);
        return "hello";
    }

}
  • @GetMapping("/hello/{a}/{b}"),@PostMapping("/hello/{a}/{b}")这两个注解的区别就是读取不同方式传递的请求,一个是Get一个Post

  • 所以当访问的时候,url地址栏上写的都是http://localhost:8080/hello/1/2,但是我们可以通过不同的方式来选择调用不同类型的方法

    注意所有个地址栏的url请求都是get方式的,其他方式的请求需要在html中进行编写

RestFul风格的好处:

1.对比传统风格的url更加简洁

2.安全性提高了,因为传统的url会暴露自己代码里的变量名称,url则不会

4、转发和重定向

在springmvc中转发是直接使用return加想要显示的页面的路径来实现

@GetMapping("/hello/{a}/{b}")
public String getHello(@PathVariable("a") int a,@PathVariable("b") int b, Model model){
    int i = a+b;
    model.addAttribute("msg",i);
    return "hello";
}

这里的return "hello"就是一个转发

<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
      id="internalResourceViewResolver">
    <!-- 前缀 -->
    <property name="prefix" value="/WEB-INF/" />
    <!-- 后缀 -->
    <property name="suffix" value=".jsp" />
</bean>

当把xml中的视图解析器前缀中的jsp去掉

在代码中就可以使用hello页面的路径进行调用

@GetMapping("/hello/{a}/{b}")
public String getHello(@PathVariable("a") int a,@PathVariable("b") int b, Model model){
    int i = a+b;
    model.addAttribute("msg",i);
    return "jsp/hello";
}

重定向则是通过在转发发的路径前面加上redirect:来实现的

    @GetMapping("/hello")
    public String getHello(Model model){
        model.addAttribute("msg","hh");
        return "redirect:index.jsp";
    }

当访问

http://localhost:8080/hello

的时候就会自动跳转到

http://localhost:8080/index.jsp?msg=hh

一下内容转载于https://blog.csdn.net/liubin5620/article/details/79922692

转发和重定向的区别:

  • 转发是正常的直接return加路径,重定向是return “redirect:”+路径;
  • 转发浏览器的Url地址栏不变,重定向改变
  • 转发是浏览器端执行,重定向是客户端执行
  • 转发时客户端会发送一次请求,重定向客户端至少发送两次请求
  • 转发时保存的信息不会丢失,重定向则会丢失model信息

转发和重定向的选择
1、重定向的速度比转发慢,因为浏览器还得发出一个新的请求,如果在使用转发和重定向都无所谓的时候建议使用转发。

2、因为转发只能访问当前WEB的应用程序,所以不同WEB应用程序之间的访问,特别是要访问到另外一个WEB站点上的资源的情况,这个时候就只能使用重定向了。

转发和重定向的应用场景
在上面我已经提到了,转发是要比重定向快,因为重定向需要经过客户端,而转发没有。有时候,采用重定向会更好,若需要重定向到另外一个外部网站,则无法使用转发。另外,重定向还有一个应用场景:避免在用户重新加载页面时两次调用相同的动作。

例如,当提交产品表单的时候,执行保存的方法将会被调用,并执行相应的动作;这在一个真实的应用程序中,很有可能将表单中的所有产品信息加入到数据库中。但是如果在提交表单后,重新加载页面,执行保存的方法就很有可能再次被调用。同样的产品信息就将可能再次被添加,为了避免这种情况,提交表单后,你可以将用户重定向到一个不同的页面,这样的话,这个网页任意重新加载都没有副作用;

但是,使用重定向不太方便的地方是,使用它无法将值轻松地传递给目标页面。而采用转发,则可以简单地将属性添加到Model,使得目标视图可以轻松访问。由于重定向经过客户端,所以Model中的一切都会在重定向时丢失。但幸运的是,在Spring3.1版本以后,我们可以通过Flash属性,解决重定向时传值丢失的问题。

要使用Flash属性,必须在Spring MVC的配置文件中添加一个。然后,还必须再方法上添加一个新的参数类型:org.springframework.web.servlet.mvc.support.RedirectAttributes。

如下所示:

 @RequestMapping(value="saveProduct",method=RequestMethod.POST)
public String saveProduct(ProductForm productForm,RedirectAttributes redirectAttributes){
 //执行产品保存的业务逻辑等
  
 //传递参数
   redirectAttributes.addFlashAttribute("message","The product is saved successfully");
   
 //执行重定向
  return "redirect:/……";
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值