首页 > 编程语言 > 详细

springmvc笔记

时间:2020-05-10 15:02:35      阅读:31      评论:0      收藏:0      [点我收藏+]

1 快速开始

1.0 jar包依赖

技术分享图片

1.0.1 maven 的tomcat配置

<plugin>

    <groupId>org.apache.tomcat.maven</groupId>

    <artifactId>tomcat7-maven-plugin</artifactId>

    <version>2.2</version>

</plugin>

1.1 文件结构

技术分享图片

1.2 具体文件内容

1.2.1 HelloCon.java(控制器Controller)

package org.suyuesheng.spring.mvc.controler;

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

public class HelloCon implements Controller {
    @Override
    public ModelAndView handleRequest(javax.servlet.http.HttpServletRequest httpServletRequest, javax.servlet.http.HttpServletResponse httpServletResponse) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("msg", "hehe");
        modelAndView.setViewName("hello");
//        httpServletRequest.setAttribute("ss", "rr");
//        httpServletResponse.sendRedirect("https://www.cnblogs.com/mikevictor07/p/3436393.html");
        return modelAndView;
    }
}

1.2.2 springMvc-servlet.xml(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">
<!--BeanNameUrlHandlerMapping和SimpleControllerHandlerAdapter可以省略-->
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">

        <property name="prefix" value="/WEB-INF/jsp/"/>

        <property name="suffix" value=".jsp"/>
    </bean>

    <bean id="/hello" class="org.suyuesheng.spring.mvc.controler.HelloCon"/>

</beans>

1.2.3 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>springmvc01</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>springmvc01</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

1.2.4 hello.jsp

<%--
  Created by IntelliJ IDEA.
  Date: 2020/5/4
  Time: 3:35
  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>

2 spring mvc的路

技术分享图片

https://www.jianshu.com/p/8a20c547e245

SpringMVC执行流程:
1.用户发送请求至前端控制器DispatcherServlet
2.DispatcherServlet收到请求调用处理器映射器HandlerMapping。
3.处理器映射器根据请求url找到具体的处理器,生成处理器执行链HandlerExecutionChain(包括处理器对象和处理器拦截器)一并返回给DispatcherServlet。
4.DispatcherServlet根据处理器Handler获取处理器适配器HandlerAdapter执行HandlerAdapter处理一系列的操作,如:参数封装,数据格式转换,数据验证等操作
5.执行处理器Handler(Controller,也叫页面控制器)。
6.Handler执行完成返回ModelAndView
7.HandlerAdapter将Handler执行结果ModelAndView返回到DispatcherServlet
8.DispatcherServlet将ModelAndView传给ViewReslover视图解析器
9.ViewReslover解析后返回具体View
10.DispatcherServlet对View进行渲染视图(即将模型数据model填充至视图中)。
11.DispatcherServlet响应用户。

作者:CoderZS
链接:https://www.jianshu.com/p/8a20c547e245
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

3 注解开发以及restful风格

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"
       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">

    <context:component-scan base-package="org.spring.suyuesheng.mvc"/>
<!--    <mvc:annotation-driven>会自动注册RequestMappingHandlerMapping与RequestMappingHandlerAdapter两个Bean,这是Spring MVC为@Controller分发请求所必需的-->
    <mvc:annotation-driven />
<!--    如果发现是静态资源的请求,就将该请求转由Web应用服务器默认的Servlet处理,如果不是静态资源的请求,才由DispatcherServlet继续处理。-->
    <mvc:default-servlet-handler/>
    <context:annotation-config/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">

        <property name="prefix" value="/WEB-INF/jsp/"/>

        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

控制器配置??

package org.spring.suyuesheng.mvc.controller;


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

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

    //从地址栏输入,默认是get方法
    @RequestMapping(value = "/h1",method = RequestMethod.GET)
    public String hello(Model model){
//        封装数据
        model.addAttribute("msg", "hello speng");
        return "hello";//被视图解析器处理ViewResolver
    }

    //restful 风格
    @RequestMapping("/h1/{a}/{b}")
    public String helloRestFul(@PathVariable int a, @PathVariable int b, Model model){
        model.addAttribute("msg", a+b);
        return "hello";
    }

    @GetMapping("/h2")
    public String helloGet(Model model){
        model.addAttribute("msg", "get");
        return "hello";
    }

    @PostMapping("/h2")
    public String helloPost(Model model){

        model.addAttribute("msg", "get");
        return "hello";
    }
}

4 转发和重定向

4.1 相关文件

跳过

4.1.1 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.spring.suyueshneg</groupId>
  <artifactId>sptumvc-03</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <repositories>
    <repository>
      <id>alimaven</id>
      <name>aliyun maven</name>
      <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
      <releases>
        <enabled>true</enabled>
      </releases>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
    </repository>
  </repositories>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.19</version>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.22</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.4</version>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.9.4</version>
    </dependency>


    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.1.1</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.2</version>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.8</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>

  <build>
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.xml</include>
          <include>**/*.properties</include>
        </includes>
      </resource>
      <resource>
        <directory>src/main/resources</directory>
      </resource>
    </resources>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.1</version>
          <configuration>
            <source>1.8</source>
            <target>1.8</target>
            <encoding>utf-8</encoding>
          </configuration>
        </plugin>
        <plugin>

          <groupId>org.apache.tomcat.maven</groupId>

          <artifactId>tomcat7-maven-plugin</artifactId>

          <version>2.2</version>

        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

4.1.2 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>springmvc03</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvcconfig.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc03</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

4.1.3 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" 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/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <mvc:default-servlet-handler/>
    <mvc:annotation-driven/>
    <context:component-scan base-package="org.spring.suyuesheng.mvc03"/>
    <context:annotation-config/>


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

</beans>

4.1.4 研究转发和重定向的控制器

package org.spring.suyuesheng.mvc03.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;


@Controller
@RequestMapping("/hello")
public class ReHelloController {

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

    //转发
    @RequestMapping("/h2")
    public String hello2(Model model, HttpServletRequest request){
        model.addAttribute("hello", "hi");
        request.setAttribute("hh",12);
        //也可以通过在url后面加东西传递数据
        return "forward:/hello/h8?username=77";
    }

    //重定向
    @RequestMapping("/h3")
   public String hello3(Model model){
        return "redirect:https://www.cnblogs.com/sogeisetsu/";
   }
//   传递参数
    @RequestMapping("/h4")
    public String hello4(RedirectAttributes model){
        model.addAttribute("username", "77");
        //相当于 redirect:/hello/h5?username=77
        return "redirect:/hello/h5";

    }

    @RequestMapping("/h5")
    public String hello5(Model model,String username){
        System.out.println(username);
        return "helllo";
    }
//    重定向传递参数隐藏传递
    @RequestMapping("/h6")
    public String hello6(RedirectAttributes model){
        model.addFlashAttribute("username", "liuji");
        return "redirect:/hello/h7";
    }

    @RequestMapping("/h7")
    public String hello7(@ModelAttribute(value = "username") String username, ModelMap modelMap){
        /*
        * model.addFlashAttribute("username", "liuji");
        * 可以用@ModelAttribute,或者用ModelMap获得
        * */
        System.out.println(username);
        //通过ModelMap获得??
        System.out.println("modelmap能获得吗?");
        System.out.println("modelmap.get(\"username\")"+modelMap.get("username"));
        System.out.println(modelMap);
        return "helllo";
    }

    @RequestMapping("/h8")
    public String hello8(Model model,HttpServletRequest request,String username){
        //转发无法通过model传递参数
        System.out.println(model.getAttribute("hello"));
        //可以通过传统的request传递参数
        System.out.println(request.getAttribute("hh"));
        System.out.println(">>"+username);
        return "helllo";
    }
}

4.2 转发和重定向的基本实现

转发

转发只能在同一服务器的同一项目,url不变,request和response不变

springmvc实现转发的基本形式??

@RequestMapping("/h2")
public String hello2(Model model, HttpServletRequest request){
    model.addAttribute("hello", "hi");
    request.setAttribute("hh",12);
    return "forward:/hello/h8";
}

可以看到,所谓转发,即在返回字符串到到视图解析器(ViewResolver)的地方,在字符串前面写一个forward然后后面写路径。/指的是从tomcat规定的虚拟路径开始,走的是绝对路径;没有/或者前面是./表示是相对路径,是从当前目录开始的。 return "forward:/hello/h8"就是一个绝对路径转发

重定向

重定向,可以访问不同服务器的资源,url发生改变,request发生改变

重定向的基本形式??

@RequestMapping("/h3")
public String hello3(Model model){
    return "redirect:https://www.cnblogs.com/sogeisetsu/";
}

重定向就是在路径前面加一个redirect,其余和转发一样。但必须要注意一点,springmvc实现重定向和传统的servlet实现重定向是不同的,传统的的重定向的根路径是服务器的根路径,springmvc实现重定向的根路径是当前web项目的根路径(即从虚拟路径开始,如果tomcat没有设定虚拟路径的话那就是从服务器的根路径开始)

4.2.1 转发和重定向区别

  • 重定向的特点:redirect
    1. 地址栏发生变化
    1. 重定向可以访问其他站点(服务器)的资源
    1. 重定向是两次请求。不能使用request对象来共享数据
  • 转发的特点:forward
    1. 转发地址栏路径不变
    1. 转发只能访问当前服务器下的资源
    1. 转发是一次请求,可以使用request对象来共享数据

4.3 转发和重定向的参数问题

注意,探讨的是springmvc在转发和重定向时通过model来传参数,就单纯传参而言,传参的方式是多种多样的,本文不探讨传统的servlet传递数据的方式,只讨论通过model传参时转发和重定向的区别

4.3.1 转发传递参数

通过model转发无法传递参数,可以通过request传参(当然,仅传参而言方法是多种多样的,这里只介绍一个)??

//转发
@RequestMapping("/h2")
public String hello2(Model model, HttpServletRequest request){
    model.addAttribute("hello", "hi");
    request.setAttribute("hh",12);
    return "forward:/hello/h8";
}
@RequestMapping("/h8")
public String hello8(Model model,HttpServletRequest request){
    //转发无法通过model传递参数
    System.out.println(model.getAttribute("hello"));
    //可以通过传统的request传递参数
    System.out.println(request.getAttribute("hh"));
    return "helllo";
}

即通过request的setAttributegetAttribute传参。

还有一种方法是通过在url后面加东西传递数据,比如return "forward:/hello/h8?username=77"

4.3.2 重定向传递参数

可以通过在url后面加东西实现,比如return "redirect:/hello/h8?username=77"只是此方法没有太麻烦,且不是通过model传递

有一个专门服务于重定向的接口RedirectAttributes,该接口继承了Model接口。public interface RedirectAttributes extends Model

4.3.2.1 RedirectAttributesaddAttribute方法传递参数

比如这样model.addAttribute("username", "77");相当于是在重定向的url后面加上参数??

//   传递参数
@RequestMapping("/h4")
public String hello4(RedirectAttributes model){
    model.addAttribute("username", "77");
    //相当于 redirect:/hello/h5?username=77
    return "redirect:/hello/h5";

}

//接收参数
@RequestMapping("/h5")
public String hello5(Model model,String username){
    System.out.println(username);
    return "helllo";
}

这种方法很不安全,参数直接暴露

4.3.2.2 RedirectAttributesaddFlashAttribute方法

这种方式也能达到重新向带参,而且能隐藏参数,其原理就是放到session中,session在跳到页面后马上移除对象。所以你刷新一下后这个值就会丢掉

//    重定向传递参数隐藏传递
@RequestMapping("/h6")
public String hello6(RedirectAttributes model){
    model.addFlashAttribute("username", "liuji");
    return "redirect:/hello/h7";
}
//获取addFlashAttribute传递的参数
@RequestMapping("/h7")
public String hello7(@ModelAttribute(value = "username") String username, ModelMap modelMap){
       /* 
        * model.addFlashAttribute("username", "liuji");
        * 可以用@ModelAttribute,或者用ModelMap获得
        * */
    System.out.println(username);
    //通过ModelMap获得??
    System.out.println("modelmap能获得吗?");
    System.out.println("modelmap.get(\"username\")"+modelMap.get("username"));
    System.out.println(modelMap);
    return "helllo";
}

通过addFlashAttribute(name,value)传递的参数,可以用@ModelAttribute,或者用ModelMap获得

springmvc笔记

原文:https://www.cnblogs.com/sogeisetsu/p/12863183.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!