Java:SpringMVC的使用(1)

news2024/9/28 11:20:49

目录

  • 第一章、SpringMVC基本了解
    • 1.1 概述
    • 1.2 SpringMVC处理请求原理简图
  • 第二章、SpringMVC搭建框架
    • 1、搭建SpringMVC框架
      • 1.1 创建工程【web工程】
      • 1.2 导入jar包
      • 1.3 编写配置文件
        • (1) web.xml注册DispatcherServlet
        • (2) springmvc.xml
        • (3) index.html
      • 1.4 编写请求处理器【Controller|Handler】
      • 1.5 准备页面进行,测试
  • 第三章 @RequestMapping详解
    • 3.1 @RequestMapping注解位置
    • 3.2 @RequestMapping注解属性
    • 3.3 @RequestMapping支持Ant 风格的路径(了解)
  • 第四章 @PathVariable 注解
    • 4.1 @PathVariable注解位置
    • 4.2 @PathVariable注解作用
    • 4.3 @PathVariable注解属性
  • 第五章 REST【RESTful】风格CRUD
    • 5.1 REST的CRUD与传统风格CRUD对比
    • 5.2 REST风格CRUD优势
    • 5.3 实现PUT&DELETE提交方式步骤
    • 5.4 源码解析HiddenHttpMethodFilter
  • 第六章 SpringMVC处理请求数据
    • 6.1 处理请求参数
    • 6.2 处理请头
    • 6.3 处理Cookie信息
    • 6.4 使用原生Servlet-API
  • 第七章 SpringMVC处理响应数据
    • 7.1 使用ModelAndView
    • 7.2 使用Model、ModelMap、Map
    • 7.3 SpringMVC中域对象
  • 第八章 SpringMVC处理请求响应乱码
    • 8.1 源码解析CharacterEncodingFilter
    • 8.2 处理请求与响应乱码
  • 第九章 SpringMVC视图及视图解析器
    • 9.1 视图解析器对象【ViewResolver】
    • 9.2 视图对象【View】
  • 第十章 源码解析SpringMVC工作原理
    • 10.1 Controller中方法的返回值问题
    • 10.2 视图及视图解析器源码
  • 第十一章 视图控制器&重定向&加载静态资源
    • 11.1 视图控制器
    • 11.2 重定向
    • 11.3 加载静态资源
    • 11.4 源码解析重定向原理

第一章、SpringMVC基本了解

1.1 概述

  • SpringMVC是Spring子框架

  • SpringMVC是Spring 为【展现层|表示层|表述层|控制层】提供的基于 MVC 设计理念的优秀的 Web 框架,是目前最主流的MVC 框架。

  • SpringMVC是非侵入式:可以使用注解让普通java对象,作为请求处理器【Controller】

  • SpringMVC是用来代替Servlet

Servlet作用

  1. 处理请求
    • 将数据共享到域中
  2. 做出响应
    • 跳转页面【视图】

1.2 SpringMVC处理请求原理简图

  • 请求
  • DispatcherServlet【前端控制器】
    • 将请求交给Controller|Handler
  • Controller|Handler【请求处理器】
    • 处理请求
    • 返回数据模型
  • ModelAndView
    • Model:数据模型
    • View:视图对象或视图名
  • DispatcherServlet渲染视图
    • 将数据共享到域中
    • 跳转页面【视图】
  • 响应
    在这里插入图片描述

第二章、SpringMVC搭建框架

1、搭建SpringMVC框架

1.1 创建工程【web工程】

  • web项目结构
    在这里插入图片描述

  • 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">
    </web-app>
    
  • 添加web模块
    在这里插入图片描述

  • 添加web模块
    在这里插入图片描述

1.2 导入jar包

  • E:\java-file\spring\spring_all\spring_mvc\pom.xml
    <!--spring-webmvc-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.1</version>
    </dependency>
    
    <!-- 导入thymeleaf与spring5的整合包 -->
    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring5</artifactId>
        <version>3.0.12.RELEASE</version>
    </dependency>
    
    <!--servlet-api-->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
        <scope>provided</scope>
    </dependency>
    

1.3 编写配置文件

(1) web.xml注册DispatcherServlet

  • url配置:/
  • init-param(初始化参数):contextConfigLocation,设置springmvc.xml配置文件路径【管理容器对象】
  • <load-on-startup>:设置DispatcherServlet优先级【启动服务器时,创建当前Servlet对象】
// src/main/webapp/WEB-INF/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>DispatcherServlet</servlet-name>
	    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	<!--        设置springmvc.xml配置文件路径【管理容器对象】-->
	    <init-param>
	        <param-name>contextConfigLocation</param-name>
	        <param-value>classpath:springmvc.xml</param-value>
	    </init-param>
	<!--        设置DispatcherServlet优先级【启动服务器时,创建当前Servlet对象】-->
	    <load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
	    <servlet-name>DispatcherServlet</servlet-name>
	    <url-pattern>/</url-pattern>
	</servlet-mapping>

</web-app>

(2) springmvc.xml

  • 开启组件扫描
  • 配置视图解析器【解析视图(设置视图前缀&后缀)】
    • 注意<property name="prefix" value="/WEB-INF/pages"/>中的pages是可变的,代表的是WEB-INF文件下的文件名
// src/main/resources/springmvc.xml
<!--    - 开启组件扫描-->
<context:component-scan base-package="com.atguigu"></context:component-scan>
<!--    - 配置视图解析器【解析视图(设置视图前缀&后缀)】-->
<bean class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
<!--        配置字符集属性-->
    <property name="characterEncoding" value="UTF-8"/>
<!--        配置模板引擎属性-->
    <property name="templateEngine">
<!--            配置内部bean -->
        <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
<!--                配置模块的解析器属性 -->
            <property name="templateResolver">
<!--                    配置内部bean -->
                <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
                    <!-- 视图前缀 -->
                    <property name="prefix" value="/WEB-INF/pages/"/>
                    <!-- 视图后缀 -->
                    <property name="suffix" value=".html"/>
<!--                        <property name="templateMode" value="HTML5"/>-->
                    <!-- 配置字符集 -->
                    <property name="characterEncoding" value="UTF-8" />
                </bean>
            </property>
        </bean>
    </property>
</bean> 

(3) index.html

demo演示:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>

<a th:href="@{/HelloController}">发送请求</a>

</body>
</html>

1.4 编写请求处理器【Controller|Handler】

  • 使用**@Controller**注解标识请求处理器
  • 使用**@RequestMapping**注解标识处理方法【URL】
  • src/main/java/com/atguigu/controller/HelloController.java
    package com.atguigu.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller    // 标识当前类是一个请求处理器类
    public class HelloController {
    
        /**
         * 配置url【/】,会映射(跳转)到 WEB-INF/index.html
         * @return
         */
        @RequestMapping("/")
        public String toIndex(){
            //            /WEB-INF/pages/index.html
            // 物理视图名 = 视图前缀+逻辑视图名+视图后缀
            // 物理视图名 = "/WEB-INF/pages/" + "index" + ".html"
            return "index";
        }
    }
    
    

1.5 准备页面进行,测试

tomcat集成到idea
在这里插入图片描述
测试
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

第三章 @RequestMapping详解

@RequestMapping注解作用:为指定的类或方法设置相应URL

3.1 @RequestMapping注解位置

  • 书写在类上面
    • 作用:为当前类设置映射URL
    • 注意:不能单独使用,需要与方法上的@RequestMapping配合使用
  • 书写在方法上面
    • 作用:为当前方法设置映射URL
    • 注意:可以单独使用

注意:当类和类中方法都有@RequestMapping注解时,此时路径应为/类的RequestMapping路径/方法的RequestMapping路径

3.2 @RequestMapping注解属性

  • value属性

    • 类型:String[]
    • 作用:设置URL信息
  • path属性

    • 类型:String[]
    • 作用:与value属性作用一致
  • method属性

    • 类型:RequestMethod[]

      public enum RequestMethod {
      GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE
      }
      
    • 作用:为当前URL【类或方法】设置请求方式【POST、DELETE、PUT、GET】

    • 注意:

      • 默认情况:所有请求方式均支持
      • 如请求方式不支持,会报如下错误
        • 405【Request method ‘GET’ not supported】
  • params

    • 类型:String[]
    • 作用:为当前URL设置请求参数
    • 注意:如设置指定请求参数,但URL中未携带指定参数,会报如下错误
      • 400【Parameter conditions “lastName” not met for actual request parameters:】
  • headers

    • 类型:String[]
    • 作用:为当前URL设置请求头信息
    • 注意:如设置指定请求头,但URL中未携带请求头,会报如下错误
      • 404:请求资源未找到
  • 示例代码

    @RequestMapping(value = {"/saveEmp","/insertEmp"},
                    method = RequestMethod.GET,
                    params = "lastName=lisi",
                    headers = "User-Agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.84 Safari/537.36")
    public String saveEmp(){
        System.out.println("添加员工信息!!!!");
    
        return SUCCESS;
    }
    
@RequestMapping(method = RequestMethod.POST)
public @interface PostMapping {}
@RequestMapping(method = RequestMethod.GET)
public @interface GetMapping {}
@RequestMapping(method = RequestMethod.PUT)
public @interface PutMapping {}
@RequestMapping(method = RequestMethod.DELETE)
public @interface DeleteMapping {}

3.3 @RequestMapping支持Ant 风格的路径(了解)

  • 常用通配符

    a) ?:匹配一个字符

    b) *:匹配任意字符

    c) **:匹配多层路径

  • 示例代码

    @RequestMapping("/testAnt/**")
    public String testAnt(){
        System.out.println("==>testAnt!!!");
        return SUCCESS;
    }
    

第四章 @PathVariable 注解

4.1 @PathVariable注解位置

@Target(ElementType.PARAMETER)

  • 书写在参数前面

4.2 @PathVariable注解作用

  • 获取URL中占位符参数

  • 占位符语法:{}

  • 示例代码

    <a th:href="@{/EmpController/testPathVariable/1001}">测试PathVariable注解</a><br>
    
    /**
     * testPathVariable
     * @return
     */
    @RequestMapping("/testPathVariable/{empId}")
    public String testPathVariable(@PathVariable("empId") Integer empId){
        System.out.println("empId = " + empId);
        return SUCCESS;
    }
    

4.3 @PathVariable注解属性

  • value属性
    • 类型:String
    • 作用:设置占位符中的参数名
  • name属性
    • 类型:String
    • 作用:与name属性的作用一致
  • required属性
    • 类型:boolean
    • 作用:设置当前参数是否必须入参【默认值:true】
      • true:表示当前参数必须入参,如未入参会报如下错误
        • Missing URI template variable ‘empId’ for method parameter of type Integer
      • false:表示当前参数不必须入参,如未入参,会装配null值

第五章 REST【RESTful】风格CRUD

5.1 REST的CRUD与传统风格CRUD对比

  • 传统风格CRUD

    • 功能 URL 请求方式
    • 增 /insertEmp POST
    • 删 /deleteEmp?empId=1001 GET
    • 改 /updateEmp POST
    • 查 /selectEmp?empId=1001 GET
  • REST风格CRUD

    • 功能 URL 请求方式
    • 增 /emp POST
    • 删 /emp/1001 DELETE
    • 改 /emp PUT
    • 查 /emp/1001 GET

5.2 REST风格CRUD优势

  • 提高网站排名
    • 排名方式
      • 竞价排名
      • 技术排名
  • 便于第三方平台对接

5.3 实现PUT&DELETE提交方式步骤

  • 注册过滤器HiddenHttpMethodFilter
    <!--    注册过滤器  -->
       <filter>
           <filter-name>HiddenHttpMethodFilter</filter-name>
           <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
       </filter>
       <filter-mapping>
           <filter-name>HiddenHttpMethodFilter</filter-name>
    <!--        所有的请求都需要经过过滤器  -->
           <url-pattern>/*</url-pattern>
       </filter-mapping>
    
    
  • 设置表单的提交方式为POST
  • 设置参数:_method=PUT或_method=DELETE
    <h3>修改员工--PUT方式提交</h3>
    <form th:action="@{/emp}" method="post">
        <input type="hidden" name="_method" value="PUT">
        <input type="submit" value="修改员工信息">
    </form>
    
    <h3>删除员工--DELETE方式提交</h3>
    <form th:action="@{/emp/1001}" method="post">
        <input type="hidden" name="_method" value="DELETE">
        <input type="submit" value="删除员工信息">
    </form>
    

5.4 源码解析HiddenHttpMethodFilter

public static final String DEFAULT_METHOD_PARAM = "_method";

private String methodParam = DEFAULT_METHOD_PARAM;

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
      throws ServletException, IOException {

   HttpServletRequest requestToUse = request;

   if ("POST".equals(request.getMethod()) && request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == null) {
      String paramValue = request.getParameter(this.methodParam);
      if (StringUtils.hasLength(paramValue)) {
         String method = paramValue.toUpperCase(Locale.ENGLISH);
         if (ALLOWED_METHODS.contains(method)) {
            requestToUse = new HttpMethodRequestWrapper(request, method);
         }
      }
   }

   filterChain.doFilter(requestToUse, response);
}
/**
	 * Simple {@link HttpServletRequest} wrapper that returns the supplied method for
	 * {@link HttpServletRequest#getMethod()}.
	 */
	private static class HttpMethodRequestWrapper extends HttpServletRequestWrapper {

		private final String method;

		public HttpMethodRequestWrapper(HttpServletRequest request, String method) {
			super(request);
			this.method = method;
		}

		@Override
		public String getMethod() {
			return this.method;
		}
	}

第六章 SpringMVC处理请求数据

使用Servlet处理请求数据

  1. 请求参数
    • String param = request.getParameter();
  2. 请求头
    • request.getHeader();
  3. Cookie
    • request.getCookies();

6.1 处理请求参数

  • 默认情况:可以将请求参数名,与入参参数名一致的参数,自动入参【自动类型转换】
<h2>测试SpringMVC处理请求数据</h2>
<h3>处理请求参数</h3>
<a th:href="@{/requestParam1(stuName='zs', stuAge=18)}">测试处理请求参数1</a>
/**
* 获取请求参数
* @return
*/
@RequestMapping("/requestParam1")
public String requestParam1(String stuName,Integer stuAge){
   System.out.println("stuName = "+ stuName);
   System.out.println("stuAge = "+ stuAge);
   return SUCCESS;
}
  • SpringMVC支持POJO入参

    • 要求:请求参数名与POJO的属性名保持一致

    • 示例代码

      <form th:action="@{/saveEmp}" method="POST">
          id:<input type="text" name="id"><br>
          LastName:<input type="text" name="lastName"><br>
          Email:<input type="text" name="email"><br>
          Salary:<input type="text" name="salary"><br>
          <input type="submit" value="添加员工信息">
      </form>
      
      /**
       * 获取请求参数POJO
       * @return
       */
      @RequestMapping(value = "/saveEmp",method = RequestMethod.POST)
      public String saveEmp(Employee employee){
          System.out.println("employee = " + employee);
          return  SUCCESS;
      }
      
  • @RequestParam注解

    • 作用:如请求参数与入参参数名不一致时,可以使用@RequestParam注解设置入参参数名

    • 属性

      • value
        • 类型:String
        • 作用:设置需要入参的参数名
      • name
        • 类型:String
        • 作用:与value属性作用一致
      • required
        • 类型:Boolean
        • 作用:设置当前参数,是否必须入参
          • true【默认值】:表示当前参数必须入参,如未入参会报如下错误
            • 400【Required String parameter ‘sName’ is not present】
          • false:表示当前参数不必须入参,如未入参,装配null值
      • defaultValue
        • 类型:String
        • 作用:当装配数值为null时,指定当前defaultValue默认值
    • 示例代码

      <h2>测试SpringMVC处理请求数据</h2>
      <h3>处理请求参数</h3>
      <a th:href="@{/requestParam1(sName='zs', stuAge=18)}">测试处理请求参数1</a>
      
      /**
       * 获取请求参数
       * @return
       */
      @RequestMapping("/requestParam1")
      public String requestParam1(@RequestParam(value = "sName",required = false,
                                              defaultValue = "zhangsan")
                                              String stuName,
                                  Integer stuAge){
          System.out.println("stuName = " + stuName);
          System.out.println("stuAge = " + stuAge);
          return SUCCESS;
      }
      

6.2 处理请头

  • 语法:@RequestHeader注解

  • 属性

    • value
      • 类型:String
      • 作用:设置需要获取请求头名称
    • name
      • 类型:String
      • 作用:与value属性作用一致
    • required
      • 类型:boolean
      • 作用:【默认值true】
        • true:设置当前请求头是否为必须入参,如未入参会报如下错误
          • 400【Required String parameter ‘sName’ is not present】
        • false:表示当前参数不必须入参,如未入参,装配null值
    • defaultValue
      • 类型:String
      • 作用:当装配数值为null时,指定当前defaultValue默认值
  • 示例代码

    <a th:href="@{/testGetHeader}">测试获取请求头</a>
    
    /**
     * 获取请求头
     * @return
     */
    @RequestMapping(value = "/testGetHeader")
    public String testGetHeader(@RequestHeader("Accept-Language")String al,
                                @RequestHeader("Referer") String ref){
        System.out.println("al = " + al);
        System.out.println("ref = " + ref);
        return SUCCESS;
    }
    

6.3 处理Cookie信息

  • 语法:@CookieValue获取Cookie数值

  • 属性

    • value
      • 类型:String
      • 作用:设置需要获取Cookie名称
    • name
      • 类型:String
      • 作用:与value属性作用一致
    • required
      • 类型:boolean
      • 作用:【默认值true】
        • true:设置当前Cookie是否为必须入参,如未入参会报如下错误
          • 400【Required String parameter ‘sName’ is not present】
        • false:表示当前Cookie不必须入参,如未入参,装配null值
    • defaultValue
      • 类型:String
      • 作用:当装配数值为null时,指定当前defaultValue默认值
  • 示例代码

    <a th:href="@{/setCookie}">设置Cookie信息</a><br>
    <a th:href="@{/getCookie}">获取Cookie信息</a><br>
    
    /**
         * 设置Cookie
         * @return
         */
        @RequestMapping("/setCookie")
        public String setCookie(HttpSession session){
    //        Cookie cookie = new Cookie();
            System.out.println("session.getId() = " + session.getId());
            return SUCCESS;
        }
    
        /**
         * 获取Cookie
         * @return
         */
        @RequestMapping("/getCookie")
        public String getCookie(@CookieValue("JSESSIONID")String cookieValue){
            System.out.println("cookieValue = " + cookieValue);
            return SUCCESS;
        }
    

6.4 使用原生Servlet-API

  • 将原生Servlet相关对象,入参即可
@RequestMapping("/useRequestObject")
public String useRequestObject(HttpServletRequest request){}

第七章 SpringMVC处理响应数据

7.1 使用ModelAndView

  • 语法:使用ModelAndView对象作为方法返回值类型,处理响应数据

  • ModelAndView是模型数据视图对象的集成对象,源码如下

    public class ModelAndView {
    
       /** View instance or view name String. */
       //view代表view对象或viewName【建议使用viewName】
       @Nullable
       private Object view;
    
       /** Model Map. */
       //ModelMap集成LinkedHashMap,存储数据
       @Nullable
       private ModelMap model;
        
        /**
        	设置视图名称
    	 */
    	public void setViewName(@Nullable String viewName) {
    		this.view = viewName;
    	}
    
    	/**
    	 * 获取视图名称
    	 */
    	@Nullable
    	public String getViewName() {
    		return (this.view instanceof String ? (String) this.view : null);
    	}
    
        /**
    	 获取数据,返回Map【无序,model可以为null】
    	 */
    	@Nullable
    	protected Map<String, Object> getModelInternal() {
    		return this.model;
    	}
    
    	/**
    	 * 获取数据,返回 ModelMap【有序】
    	 */
    	public ModelMap getModelMap() {
    		if (this.model == null) {
    			this.model = new ModelMap();
    		}
    		return this.model;
    	}
    
    	/**
    	 * 获取数据,返回Map【无序】
    	 */
    	public Map<String, Object> getModel() {
    		return getModelMap();
    	}
        
        /**
        	设置数据
        */
        public ModelAndView addObject(String attributeName, @Nullable Object attributeValue) {
    		getModelMap().addAttribute(attributeName, attributeValue);
    		return this;
    	}
        
        
    }
         
    
  • 底层实现原理

    • 数据共享到request域
    • 跳转路径方式:转发
  • 示例代码

    <h2>测试SpringMVC处理响应数据</h2>
    <h3>1、测试响应数据--ModelAndView</h3>
    <a th:href="@{/ResponseDataController/testModelAndView}">测试处理请求参数1</a>
    <br>
    
    @Controller
    @RequestMapping("/ResponseDataController")
    public class ResponseDataController {
    
       @RequestMapping("/testModelAndView")
       public ModelAndView testModelAndView(){
           ModelAndView mv = new ModelAndView();
    //        设置数据
           mv.addObject("stuName","lisi");
    //        设置视图
           mv.setViewName("response_success");
           return mv;
       }
    }
    
    <h2>响应数据--成功页面</h2>
    stuName:<span th:text="${stuName}"></span>
    

7.2 使用Model、ModelMap、Map

  • 语法:使用Model、ModelMap、Map作为方法入参,处理响应数据

  • 示例代码

    <h3>2、测试响应数据--ModelOrModelMapOrMap</h3>
    <a th:href="@{/ResponseDataController/testModelOrModelMapOrMap}">测试处理响应参数2</a>
    <br>
    
       /**
         * 使用Map、Model、ModelMap处理响应数据
         * @return
         */
      //    @RequestMapping("/testModelOrModelMapOrMap")
      //    public String testModelOrModelMapOrMap(Map<String,Object> map){
              设置数据--Map方式
      //        map.put("stuName","zhangsan");
      //
      //        return "response_success";
      //    }
      
          @RequestMapping("/testModelOrModelMapOrMap")
          public String testModelOrModelMapOrMap(Model model){
      //        设置数据--Model/ModelMap方式
              model.addAttribute("stuName","wangwu");
      
              return "response_success";
          }
    
    <h2>响应数据--成功页面</h2>
    stuName:<span th:text="${stuName}"></span>
    
  • 底层实现原理

    • 数据共享到request域
    • 跳转路径方式:转发

7.3 SpringMVC中域对象

  • SpringMVC封装数据,默认使用request域对象

  • session域的使用

    • 方式一

      /**
       * 测试响应数据【其他域对象】
       * @return
       */
      @GetMapping("/testScopeResponsedata")
      public String testScopeResponsedata(HttpSession session){
          session.setAttribute("stuName","xinlai");
          return "response_success";
      }
      
    • 方式二

      @Controller
      @SessionAttributes(value = "stuName") //将request域中数据,同步到session域中
      public class TestResponseData {
      
      	@RequestMapping("/testSession")
          public String testSession( Map<String, Object> map ){
      //        设置数据--数据在Session域
              map.put("stuName","sunqi");
      
              return "response_success";
          }
      }
      

第八章 SpringMVC处理请求响应乱码

JavaWeb解决乱码:三行代码

  • 解决POST请求乱码
    在这里插入图片描述
  • 解决GET请求乱码【Tomcat8及以后,自动解决】
    在这里插入图片描述
  • 解决响应乱码
    在这里插入图片描述

8.1 源码解析CharacterEncodingFilter

public class CharacterEncodingFilter extends OncePerRequestFilter {

   //需要设置字符集
   @Nullable
   private String encoding;
   //true:处理请乱码
   private boolean forceRequestEncoding = false;
   //true:处理响应乱码
   private boolean forceResponseEncoding = false;
    
    public String getEncoding() {
		return this.encoding;
	}
    
    public boolean isForceRequestEncoding() {
		return this.forceRequestEncoding;
	}
    
    public void setForceResponseEncoding(boolean forceResponseEncoding) {
		this.forceResponseEncoding = forceResponseEncoding;
	}
    
    public void setForceEncoding(boolean forceEncoding) {
    	// 合并了forceRequestEncoding和forceResponseEncoding 
		this.forceRequestEncoding = forceEncoding;
		this.forceResponseEncoding = forceEncoding;
	}
    
 	@Override
	protected void doFilterInternal(
			HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {

		// 字符集
		String encoding = getEncoding();
		
		if (encoding != null) {
			if (isForceRequestEncoding() || request.getCharacterEncoding() == null) {
				// 解决请求乱码
				request.setCharacterEncoding(encoding);
			}
			if (isForceResponseEncoding()) {
				// 解决响应乱码
				response.setCharacterEncoding(encoding);
			}
		}
        
		filterChain.doFilter(request, response);
	
    }
    
    
}

8.2 处理请求与响应乱码

  • SpringMVC底层默认处理响应乱码

  • SpringMVC处理请求乱码步骤

    1. 注册CharacterEncodingFilter
      • 注册CharacterEncodingFilter必须是第一Filter位置
    2. 为CharacterEncodingFilter中属性encoding赋值
    3. 为CharacterEncodingFilter中属性forceRequestEncoding赋值
  • 示例代码

    <!--    必须是第一过滤器位置-->
     <!--    注册CharacterEncodingFilter,解决乱码问题 -->
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
         <!--   设置初始化的字符集 -->
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <!--   解决请求及响应乱码 -->
        <init-param>
            <param-name>forceRequestEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    

第九章 SpringMVC视图及视图解析器

9.1 视图解析器对象【ViewResolver】

  • 概述:SpringMVC中所有的视图解析器对象均实现了ViewResolver接口

  • 作用:使用ViewResolver,将View从ModelAndView中解析出来

    • 在SpringMVC中,无论方法返回的是ModelAndView还是String,最终底层都会封装为ModelAndView

    在这里插入图片描述

9.2 视图对象【View】

  • 概述:SpringMVC中所有的视图对象【View】均实现了view接口
  • 作用:视图渲染
    1. 将数据共享到域中【request,session,application(ServletContext)】
    2. 跳转路径【转发或重定向】

第十章 源码解析SpringMVC工作原理

10.1 Controller中方法的返回值问题

  • 无论方法返回是ModelAndView还是String,最终SpringMVC底层,均会封装为ModelAndView对象

    //DispatcherServlet的1061行代码
    ModelAndView mv = null;
    mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
    
  • SpringMVC解析mv【ModelAndView】

    //DispatcherServlet的1078行代码
    processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
    
  • ThymeleafView对象中344行代码【SpringMVC底层处理响应乱码】

    //computedContentType="text/html;charset=UTF-8"
    response.setContentType(computedContentType);
    
  • WebEngineContext对象中783行代码【SpringMVC底层将数据默认共享到request域】

    this.request.setAttribute(name, value);
    

10.2 视图及视图解析器源码

  • 视图解析器将View从ModelAndView中解析出来

    • ThymeleafViewResolver的837行代码

      //底层使用反射的方式,newInstance()创建视图对象
      final AbstractThymeleafView viewInstance = BeanUtils.instantiateClass(getViewClass());
      

第十一章 视图控制器&重定向&加载静态资源

11.1 视图控制器

  • 作用:如果没有业务逻辑处理,只是单纯的跳转页面,可以通过视图控制器跳转
  • 语法:view-controller
  • 步骤
    1. 添加<mvc:view-controller>标签:为指定URL映射html页面
    2. 添加<mvc:annotation-driven>
      • 有20+种功能
      • 配置了<mvc:view-controller>标签之后会导致其他请求路径都失效,添加<mvc:annotation-driven>解决
        <!--  添加视图控制器  -->
        <mvc:view-controller path="/" view-name="index"></mvc:view-controller>
        <mvc:view-controller path="/toRestPage" view-name="rest_page"></mvc:view-controller>
        <mvc:view-controller path="/toRequestDataPage" view-name="toRequestDataPage"></mvc:view-controller>
        <mvc:view-controller path="/toResponseDataPage" view-name="toResponseDataPage"></mvc:view-controller>
        <!--  配置了<mvc:view-controller>标签之后会导致其他请求路径都失效,添加<mvc:annotation-driven>解决  -->
        <mvc:annotation-driven></mvc:annotation-driven>
    

11.2 重定向

  • 语法:return "redirect: / xxx.html";

11.3 加载静态资源

  • DefaultServlet加载静态资源到服务器

    • 静态资源:html、css、js等资源
    • tomcat->conf->web.xml关键代码如下:
    <servlet>
            <servlet-name>default</servlet-name>
            <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
            <init-param>
                <param-name>debug</param-name>
                <param-value>0</param-value>
            </init-param>
            <init-param>
                <param-name>listings</param-name>
                <param-value>false</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
    <servlet-mapping>
            <servlet-name>default</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    
  • 发现问题

    • DispatcherServlet与DefaultServlet的URL配置均为:/,导致DispatcherServlet中的配置将DefaultServlet配置的/覆盖了【DefaultServlet失效,无法加载静态资源
  • 解决方案

    <!--    解决静态资源加载问题-->
    <mvc:default-servlet-handler></mvc:default-servlet-handler>
    <!-- 添加上述标签,会导致Controller无法正常使用,需要添加mvc:annotation-driven解决 -->
    <mvc:annotation-driven></mvc:annotation-driven>
    

11.4 源码解析重定向原理

  • 创建RedirectView对象【ThymeleafViewResolver的775行代码】

    // Process redirects (HTTP redirects)
    if (viewName.startsWith(REDIRECT_URL_PREFIX)) {
        vrlogger.trace("[THYMELEAF] View \"{}\" is a redirect, and will not be handled directly by ThymeleafViewResolver.", viewName);
        final String redirectUrl = viewName.substring(REDIRECT_URL_PREFIX.length(), viewName.length());
        final RedirectView view = new RedirectView(redirectUrl, isRedirectContextRelative(), isRedirectHttp10Compatible());
        return (View) getApplicationContext().getAutowireCapableBeanFactory().initializeBean(view, REDIRECT_URL_PREFIX);
    }
    
  • RedirectView视图渲染

    • RedirectView对象URL处理【330行代码】

      在这里插入图片描述

    • 执行重定向【RedirectView的627行代码】
      在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/339602.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Android 进阶——Framework核心 之Binder Java成员类详解(三)

文章大纲引言一、Binder Java家族核心成员关系图二、Binder Java家族核心成员源码概述1、android.os.IBinder1.1、boolean transact(int code, Parcel data, Parcel reply, int flags) send a call to an IBinder object1.2、String getInterfaceDescriptor()1.3、boolean ping…

【宝塔部署SpringBoot前后端不分离项目】含域名访问部署、数据库、反向代理、Nginx等配置

一定要弄懂项目部署的方方面面。当服务器上部署的项目过多时&#xff0c;端口号什么时候该放行、什么时候才会发生冲突&#xff1f;多个项目使用redis怎么防止覆盖&#xff1f;Nginx的配置会不会产生站点冲突&#xff1f;二级域名如何合理配置&#xff1f;空闲的时候要自己用服…

【生成式AI】谁拥有生成式 AI 平台?

文章目录市场的价值将增长点技术栈&#xff1a;基础架构、模型和应用程序生成式 AI 应用程序留存率和差异化方面举步维艰生成式 AI 应用程序公司面临的一些问题模型提供商尚未达到大规模商业规模基础设施供应商是目前的最大赢家系统性的护城河技术栈早期阶段出现在生成人工智能…

[个人笔记] Zabbix实现自定义脚本监控Agent端

系统工程 - 运维篇 第三章 Zabbix实现自定义脚本监控Agent端系统工程 - 运维篇系列文章回顾前言实施步骤前置条件Zabbix实现自定义脚本监控Agent端Zabbix实现ssh免密登录OpenWrt服务器编写自定义sh脚本监控OpenWrt&#xff0c;zabbix测试监控功能Windows及Linux安装Zabbix-Agen…

IDEA自定义自动导包设置

JetBrains公司的intellij Idea堪称JAVA编程界的苹果&#xff0c;用户体验非常好 下面介绍一下IDEA的一个能显著提升写代码效率的非常好用的功能设置—— Auto Import 在使用IDEA编程时&#xff0c;我们会经常使用到下面两个快捷键 CTRLALTO(Windows) 自动导包快捷键CTRLALTL(W…

安全渗透测试中的一款免费开源的超级关键词URL采集工具

安全渗透测试中的一款免费开源的超级关键词URL采集工具。 #################### 免责声明&#xff1a;工具本身并无好坏&#xff0c;希望大家以遵守《网络安全法》相关法律为前提来使用该工具&#xff0c;支持研究学习&#xff0c;切勿用于非法犯罪活动&#xff0c;对于恶意使…

flutter 升级到 3.7.3 报错 Unable to find bundled Java version

大家好&#xff0c;我是 17。 Android studio 是2020 年的版本&#xff0c;有点老&#xff0c;昨天突发想法&#xff0c;升级到了 Android Studio Electric Eel 2022.1。 计划今天和明天写那个 Flutter WebView 优化的文章&#xff0c;这篇是 在 Flutter 中使用 webview_flut…

Android-Service详解

前言 Service 是长期运行在后台的应用程序组件 。 Service 是和应用程序在同一个进程中&#xff0c;所以应用程序关掉了&#xff0c;Service也会关掉。可以理解为 Service是不能直接处理耗时操作的&#xff0c;如果直接把耗时操作放在 Service 的 onStartCommand() 中&#xff…

健康码互通方案优化

背景 解决不同场景一码通–全国互认互扫 技术方案设计目标&#xff1a;安全、高可用、可拓展、高性能、易用性。 健康码二维码优化 要设计一个能互通的二维码&#xff0c;二维码需要放入的信息会更多&#xff0c;因为需要塞进去更多的内容。而二维码会因为字符串的长度而导致…

Redis实例绑定CPU物理核优化Redis性能

进入本次Redis性能调优之前&#xff0c;首先要知道CPU结构也会影响Redis的性能。接下来&#xff0c;具体了解一下&#xff01;为什么CPU结构也会影响Redis的性能&#xff1f;主流的 CPU 架构一个 CPU 处理器中一般有多个物理核&#xff0c;每个物理核都可以运行应用程序。每个物…

docker-微服务篇

docker学习笔记1.docker简介1.1为什么会出现docker&#xff1f;1.2docker理念1.3虚拟机&#xff08;virtual machine&#xff09;1.4容器虚拟化技术1.5一次构建到处运行2.docker安装2.1前提条件2.2docker基本构成2.3docker安装步骤*2.4测试镜像3.docker常用命令3.1 启动docker3…

微信小程序 java ssm Springboot学生作业提交管理系统

系统具有良好的集成性&#xff0c;提供标准接口&#xff0c;以实现与其他相关系统的功能和数据集成。开放性好&#xff0c;便于系统的升级维护、以及与各种信息系统进行集成。功能定位充分考虑平台服务对象的需求。 一个微信小程序由.js、.json、.wxml、.wxss四种文件构成&…

zookeeper和kafka集群从0到1搭建(保姆教程)

一、环境准备 1、准备3台机器 主机名称 主机IP zookeeper版本 kafka版本 主机名称主机IPzookeeper版本kafka版本worker01192.168.179.128zookeeper-3.4.14.tar.gzkafka_2.12-2.2.1.tgzworker02192.168.179.129zookeeper-3.4.14.tar.gzkafka_2.12-2.2.1.tgzworker03192.168.1…

Arduino IDE 2.0.6中 ESP32开发环境搭建笔记

Arduino IDE 2.0.6中 ESP32开发环境搭建 Arduino IDE2.0 已上线一段时间&#xff0c;以后ESP32的学习转至新的IDE中 &#xff0c;需对开发环境进行。 Arduino IDE&#xff12;.&#xff10;与&#xff11;.&#xff10;有很大差异。原来环境搭建方法已完全不同。下文主要记录环…

Docker进阶 - 13. Docker 容器监控之 CAdvisor+InfluxDB+Granfana (CIG) 简介

目录 1. CIG 产生原因 2. CIG 是什么 3. CIG 详细介绍 1. CIG 产生原因 使用docker stats命令可以看到当前宿主机上所有容器的CPU,内存以及网络流量等数据&#xff0c;简单的监控够用。但是docker stats统计结果只能是当前宿主机的全部容器&#xff0c;数据资料是实时的&am…

外包干了5年,寄了

前两天有读者想我资讯&#xff1a; 我是一名软件测试工程师&#xff0c;工作已经四年多快五年了。现在正在找工作&#xff0c;由于一直做的都是外包的项目。技术方面都不是很深入&#xff0c;现在找工作都是会问一些&#xff0c;测试框架&#xff0c;自动化测试&#xff0c;感…

微信公众号(二)每日推送详细教程(ChatGPT对话机器人)

微信公众号&#xff08;二&#xff09;每日推送详细教程&#xff08;ChatGPT对话机器人&#xff09;1.准备阶段1.1 基础性配置1.2 申请ChatGPT账号2. 配置阶段2.1 配置application.yml文件2.2 EnableChatGPT注解3. 部署效果图如下 1.准备阶段 1.1 基础性配置 首先下载源码…

Vue3+SpringBoot实现【登录】【毛玻璃】【渐变色】

首先创建Login.vue&#xff0c;编写界面和样式 这个是渐变色背景&#xff0c;登陆框背景为白色 <template><div class"wrapper"><div style"margin: 200px auto; background-color: #fff; width: 350px; height: 300px;padding: 20px;border-r…

hadoop高可用+mapreduce on yarn集群搭建

虚拟机安装 本次安装了四台虚拟机&#xff1a;hadoop001、hadoop002、hadoop003、hadoop004&#xff0c;安装过程略过 移除虚拟机自带jdk rpm -qa | grep -i java | xargs -n1 rpm -e --nodeps关闭防火墙 systemctl stop firewalld systemctl disable firewalld.service给普…

MyBatis-Plus基本CRUD

MyBatis-Plus基本CRUD三、基本CRUD1、BaseMapper2、插入3、删除a>通过id删除记录b>通过id批量删除记录c>通过map条件删除记录4、通过id修改一条记录5、查询a>根据id查询用户信息b>根据多个id查询多个用户信息c>通过map条件查询用户信息d>查询所有数据6、通…