栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

4、SpringMVC

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

4、SpringMVC

第一章 SpringMVC 1.1 Spring概述
  • SpringMVC是Spring子框架,是Spring 为展现层提供的基于 MVC 设计理念的优秀的 Web 框架
  • SpringMVC通过一套 MVC 注解,让 POJO 成为处理请求的控制器【请求处理器】,而无须实现任何接口。
    • SpringMVC是非侵入式
    • @Component、@Repository、@Service、@Controller
1.2 SpringMVC基本工作原理

1.3 搭建SpringMVC步骤
  • 创建web工程,打包方式设置war

  • 导入jar包

    
    
        org.springframework
        spring-webmvc
        5.3.1
    
    
    
        org.thymeleaf
        thymeleaf-spring5
        3.0.12.RELEASE
    
    
    
        javax.servlet
        javax.servlet-api
        4.0.1
        provided
    
    
  • 在web.xml中注册DispatcherServlet【前端控制器】

    • url设置为【/】
    • 设置springmvc.xml配置文件的路径,从而管理SpringMVC容器对象
    • 设置DispatcherServlet的优先级【启动服务器,创建当前DispatcherServlet】
  • 创建springmvc.xml配置文件

    • 名称:springmvc.xml
    • 位置:src/main/resouces
    • 内容
      • 开启组件扫描
      • 配置视图解析器
  • 创建Controller【请求处理器】

    • @Controller:标识当前类是一个请求处理器类
    • @RequestMapping:将指定URL映射到指定方法或类上
  • 创建相关页面,进行测试

springmvc.xml


    
    
    
    
        
        
            
                
                    
                        
                        
                        
                        
                        
                    
                
            
        
    


web.xml


    
        HiddenHttpMethodFilter
        org.springframework.web.filter.HiddenHttpMethodFilter
    
    
        HiddenHttpMethodFilter
        
        
@RequestMapping(value = "/testAnt/?
	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;
		}
	}


  • 使用步骤

    • 注册HiddenHttpMethodFilter
    • 表单
      • 表单必须以POST方式提交
      • 表单中必须携带_method参数【PUT或DELETe(不区分大小写)】
  • 示例代码

    增加POST

    查询GET 查询员工信息

    删除DELETE

    修改PUT

    @Controller
    public class EmployeeController {
    
        private static final String SUCCESS = "success";
    
        
        //    @RequestMapping(value = "/emp",method = RequestMethod.POST)
        @PostMapping("/emp")
        public String saveEmp(){
            System.out.println("==>添加员工信息!");
            return SUCCESS;
        }
    
        
        //    @RequestMapping(value = "/emp",method = RequestMethod.GET)
        @GetMapping("/emp/{empId}")
        public String getEmpById(@PathVariable("empId")Integer empId){
            System.out.println("==>查询员工信息!empId:"+empId);
            return SUCCESS;
        }
    
        
        //    @RequestMapping(value = "/emp",method = RequestMethod.DELETE)
        @DeleteMapping("/emp/{empId}")
        public String deltEmpById(@PathVariable("empId")Integer empId){
            System.out.println("==>删除员工信息!empId:"+empId);
            return SUCCESS;
        }
    
        
        //    @RequestMapping(value = "/emp",method = RequestMethod.PUT)
        @PutMapping("/emp")
        public String updateEmp(){
            System.out.println("==>修改员工信息");
            return SUCCESS;
        }
    
    }
    
    
    
    
    
        
            HiddenHttpMethodFilter
            org.springframework.web.filter.HiddenHttpMethodFilter
        
        
            HiddenHttpMethodFilter
            
            
    @GetMapping("/testRequestData")
    public String testRequestData(String username,Integer age){
        System.out.println("username = " + username);
        System.out.println("age = " + age);
        return SUCCESS;
    }
    
    
  • 4.2 @RequestParam注解详解
    • 作用:将指定的参数名,设置处理请求方法的入参参数中

    • 属性

      • value:设置需要入参的参数名

      • name:与value作用一致

      • required:表示被@RequestParam注解标识的参数,是否必须入参

        • true:表示必须入参,如未入参,会报错400

        • false:表示不必须入参,如未入参,不会报错,会将null装配

      • defaultValue:设置当前入参的默认值【当参数为null时,不显示null显示默认值】

    • 示例代码

      测试@RequestParam
      
      
      @GetMapping("/testRequestParam")
      public String testRequestParam(@RequestParam(value = "eId",required = false,defaultValue = "100001") Integer empId,
                                     @RequestParam("eName") String empName){
          System.out.println("empId = " + empId);
          System.out.println("empName = " + empName);
          return SUCCESS;
      }
      
      
    4.3 SpringMVC支持POJO入参
    • 概述:入参时,参数名与POJO中的属性一致,SpringMVC支持POJO自动入参

      • 支持级联属性赋值
    • 示例代码

      处理入参为POJO
      
      员工编号:
      员工姓名:
      员工邮箱:
      员工薪资:
      员工部门编号:
      员工部门名称:
      @PostMapping("/testPOJO")
      public String testPOJO(Employee employee){
          System.out.println("employee = " + employee);
          return SUCCESS;
      }
      
      
    第五章 SpringMVC处理响应数据【重点】 5.1 SpringMVC处理响应数据概述
    • SpringMVC提供了以下两种种途径输出模型数据
      • 使用ModelAndView作为方法的返回值类型,处理响应数据
      • 使用Model、Map、ModelMap作为方法入参,处理响应数据
    • SpringMVC中处理方法无论返回String还是ModelAndView或其他,最终底层都会封装为ModelAndView对象
    5.2 源码解析ModelAndView对象
    public class ModelAndView {
    
       
        //理解:视图对象或视图名称【推荐使用视图名称】
       @Nullable
       private Object view;
       
       
        //public class ModelMap extends LinkedHashMap {
       @Nullable
       private ModelMap model;
        
        
        
    	@Nullable
    	protected Map getModelInternal() {
    		return this.model;
    	}
    
    	
    	public ModelMap getModelMap() {
    		if (this.model == null) {
    			this.model = new ModelMap();
    		}
    		return this.model;
    	}
    
    	
    	public Map getModel() {
    		return getModelMap();
    	}
        
        
    	public ModelAndView addObject(String attributeName, @Nullable Object attributeValue) {
    		getModelMap().addAttribute(attributeName, attributeValue);
    		return this;
    	}
        
        
        
        public void setViewName(@Nullable String viewName) {
            this.view = viewName;
        }
    
        
        @Nullable
        public String getViewName() {
            return (this.view instanceof String ? (String) this.view : null);
        }
        
        
    }
    
    5.3 session域使用
    • SpringMVC响应数据默认存储request域中

    • 如使用其他域对象,通用方法是使用原生ServletAPI对象

      • HttpServletRequest
      • HttpSession
      • ServletContext
    • 使用session域常用方式如下

      1. 原生HttpSession对象
      2. 使用注解@SessionAttributes,可以将request域数据同步session域中
    • 示例代码

      @SessionAttributes(value = "lastName")//将request域中lastName同步到session域中
      public class DoResponseDataController {
      
      @GetMapping("/testModelAndViewAndSession")
          public ModelAndView testSession(){
              ModelAndView mv = new ModelAndView();
              //设置视图名称
              mv.setViewName("res_success");
              //将数据存储session域
      //        session.setAttribute("lastName","empChai");
              //使用注解
              mv.addObject("lastName","empChai");
              return mv;
          }
      }
      
    5.4 使用Model、Map、ModelMap作为方法入参,处理响应数据
     
        @GetMapping("/testModelOrMap")
        public String testModelOrMap(
                                    
                                    Model model){
            //设置数据
    //        map.put("username","lisi");
            //ModelMap
    //        modelMap.addAttribute("username","lisi_mp");
            //Model
            model.addAttribute("username","lisi_model");
    
            return "res_success";
        }
    
    5.5 源码解析SpringMVC工作原理【1】
    • DispatcherServlet底层

      • DispatcherServlet的1061行代码【触发Controller中相应方法】

        ModelAndView mv = null;
        //1061行代码【触发Controller中相应方法】
        mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
        
        • 1061行代码【触发Controller中相应方法】
        • 验证【无论返回String还是ModelAndView或其他,最终底层都会封装为ModelAndView对象】
      protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
         HttpServletRequest processedRequest = request;
         HandlerExecutionChain mappedHandler = null;
         boolean multipartRequestParsed = false;
      
         WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
      
         try {
            ModelAndView mv = null;
            Exception dispatchException = null;
      
            try {
               processedRequest = checkMultipart(request);
               multipartRequestParsed = (processedRequest != request);
      
               // Determine handler for the current request.
               mappedHandler = getHandler(processedRequest);
               if (mappedHandler == null) {
                  noHandlerFound(processedRequest, response);
                  return;
               }
      
               // Determine handler adapter for the current request.
               HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
      
               // Process last-modified header, if supported by the handler.
               String method = request.getMethod();
               boolean isGet = "GET".equals(method);
               if (isGet || "HEAD".equals(method)) {
                  long lastModified = ha.getLastModified(request, mappedHandler.getHandler());
                  if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {
                     return;
                  }
               }
      
               if (!mappedHandler.applyPreHandle(processedRequest, response)) {
                  return;
               }
      
               //1061行代码 Actually invoke the handler.
               mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
      
               if (asyncManager.isConcurrentHandlingStarted()) {
                  return;
               }
      
               applyDefaultViewName(processedRequest, mv);
               mappedHandler.applyPostHandle(processedRequest, response, mv);
            }
            catch (Exception ex) {
               dispatchException = ex;
            }
            catch (Throwable err) {
               // As of 4.3, we're processing Errors thrown from handler methods as well,
               // making them available for @ExceptionHandler methods and other scenarios.
               dispatchException = new NestedServletException("Handler dispatch failed", err);
            }
            processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
         }
         catch (Exception ex) {
            triggerAfterCompletion(processedRequest, response, mappedHandler, ex);
         }
         catch (Throwable err) {
            triggerAfterCompletion(processedRequest, response, mappedHandler,
                  new NestedServletException("Handler processing failed", err));
         }
         finally {
            if (asyncManager.isConcurrentHandlingStarted()) {
               // Instead of postHandle and afterCompletion
               if (mappedHandler != null) {
                  mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
               }
            }
            else {
               // Clean up any resources used by a multipart request.
               if (multipartRequestParsed) {
                  cleanupMultipart(processedRequest);
               }
            }
         }
      }
      
    • 断点

    第六章 SpringMVC处理请求与响应乱码 6.1 发现问题
    • SpringMVC默认
      • 请求参数是乱码
      • 响应数据不乱码
    6.2 解决请求乱码

    遇到问题:解决思路如下

    1. 第一方【JDK】
    2. 第三方【jar包】
    3. 自己
    • 使用SpringMVC提供CharacterEncodingFilter解决请求乱码

      @Nullable
      private String encoding;
      
      private boolean forceRequestEncoding = false;
      
      
      @Nullable
      public String getEncoding() {
          return this.encoding;
      }
      
      
      public boolean isForceRequestEncoding() {
          return this.forceRequestEncoding;
      }
      
      @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);
      }
      
    • 使用CharacterEncodingFilter步骤

      • 注册CharacterEncodingFilter
        • URL:配置/*
        • 注意:注册在第一过滤器的位置
      • 设置初始化参数:encoding=UTF-8
      • 设置初始化参数:forceRequestEncoding=true
    • 示例代码

      
      
          CharacterEncodingFilter
          org.springframework.web.filter.CharacterEncodingFilter
          
              encoding
              UTF-8
          
          
              forceRequestEncoding
              true
          
      
      
          CharacterEncodingFilter
          /*
      
      
    第七章 View【视图】与ViewResolver【视图解析器】 7.1 ViewResolver对象
    • 作用:将View从ViewResolver中解析出来

    • ViewResolver常用实现类

      • ThymeleafViewResolver
        • 解析出ThymeleafView对象&RedirectView对象
    • 源码解析

    7.2 View对象

    JavaWeb中响应数据

    1. 将数据共享到域中,使用Thymeleaf渲染
    2. 使用响应流,直接响应数据
    • 作用:渲染模型数据,将模型里的数据以某种形式呈现给客户。
      • 将数据共享到域中
      • 消息转换器作用:使用响应流,直接响应数据【response.getWriter().write(“”)】
    • View常用实现类
      • ThymeleafView对象
        • 默认存储request域
      • RedirectView【重定向视图对象】
        • 需要将数据共享session域
    7.3 源码解析View及ViewResolver
    • ViewResolver

    • View

      • ThymeleafView中,默认处理响应乱码

      • Thymeleaf中,默认将数据共享到request域

    第八章 SpringMVC中三个常用实战功能 8.1 视图控制器【mvc:view-controller】
    • 语法,mvc:view-controller

    • 作用:将指定URL映射到指定页面

    • 注意:使用视图控制器【ViewController】会导致其他Controller无法正常使用,必须添加如下标签

      mvc:annotation-driven

    • 示例代码

      
      
      	
      	
          
      	
          
      
      
    8.2 SpringMVC中重定向
    • 语法:return “redirect:/xxx.html”;

      • 【redirect:】是重定向语法要求
      • 【redirect:/】使用上下文路径(绝对路径)
    • 注意:

      • 重定向使用的RedirectView对象,改对象由ThymeleafViewResolver解析

      • 重定向视图对象源码

        • 【redirect:/】使用上下文路径(绝对路径)【原理】

    8.3 SpringMVC中静态资源加载问题
    • SpringMVC中默认无法加载静态资源【html、css、js、image等】

    • 无法加载静态资源【原因】:

      • 在Tomcat服务器下,本质上使用DefaultServlet【Tomcat服务器提供的】加载静态资源

      • 使用SpringMVC后,导致DefaultServlet失效,所以无法加载静态资源

        • 原理:前端控制器【DispatcherServlet】的URL覆盖了DefaultServlet中的URL

          • DefaultServlet在tomcat中配置【conf->web.xml中】

    • 解决方案

      • 装配default-servlet-handler,解决上述问题

      • 语法:

      • 原理:DefaultServletHttpRequestHandler,它会对进入 DispatcherServlet 的请求进行筛查,如果发现是没有经过映射的请求,就将该请求交由 WEB 应用服务器默认的 Servlet 处理,如果不是静态资源的请求,才由 DispatcherServlet 继续处理。

      • 注意:如配置标签,也会导致Controller无法使用,需要添加如下标签解决

    • 示例代码

      
      
      
      
      
      
    转载请注明:文章转载自 www.mshxw.com
    本文地址:https://www.mshxw.com/it/918425.html
    我们一直用心在做
    关于我们 文章归档 网站地图 联系我们

    版权所有 (c)2021-2022 MSHXW.COM

    ICP备案号:晋ICP备2021003244-6号