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

SpringMVC的学习笔记(整合)

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

SpringMVC的学习笔记(整合)

目录

一、什么是SpringMVC?

SpringMVC执行的流程

SpringMVC开发步骤

 @RequestMapping注解详解

SpringMVC要优化的方面

1、客户端提交数据的5种优化

2、控制器方法的返回值优化

3、资源跳转的优化

SpringMVC中文编码设置

解决方案

SpringMVC中的Ajax请求


一、什么是SpringMVC?

它是基于MVC开发模式的框架,用来优化MVC三层中的控制器。它是Spring家族的一员。它也具备IOC和AOP。

SpringMVC 也叫Spring web mvc。是Spring 框架的一部分,是在Spring3.0 后发布的。

  什么是MVC?
  它是一种开发模式,它是模型视图控制器的简称.所有的web应用都是基于MVC开发.
  M:模型层,包含实体类bean,业务逻辑层service,数据访问层mapper
  V:视图层,html,javaScript,vue等都是视图层,用来显现数据
  C:控制器,它是用来接收客户端的请求,并返回响应到客户端的组件,Servlet就是组件

SpringMVC执行的流程

执行流程说明:

  1. 向服务器发送HTTP请求,请求被前端控制器 DispatcherServlet 捕获。
  2. DispatcherServlet 根据中的配置对请求的URL进行解析,得到请求资源标识符(URI)。然后根据该URI,调用 HandlerMapping 获得该Handler配置的所有相关的对象(包括Handler对象以及Handler对象对应的拦截器),最后以 HandlerExecutionChain 对象的形式返回。
  3. DispatcherServlet 根据获得的Handler,选择一个合适的 HandlerAdapter。
  4. 提取Request中的模型数据,填充Handler入参,开始执行Handler(Controller)。在填充Handler的入参过程中,根据你的配置,Spring将帮你做一些额外的工作:

HttpMessageConveter:将请求消息(如Json、xml等数据)转换成一个对象,将对象转换为指定的响应信息。

数据转换:对请求消息进行数据转换。如String转换成Integer、Double等。

数据格式化:对请求消息进行数据格式化。如将字符串转换成格式化数字或格式化日期等。

数据验证:验证数据的有效性(长度、格式等),验证结果存储到BindingResult或Error中。

  1. Handler(Controller)执行完成后,向 DispatcherServlet 返回一个 ModelAndView 对象。
  2. 根据返回的ModelAndView,选择一个适合的 ViewResolver(必须是已经注册到Spring容器中的ViewResolver)返回给DispatcherServlet。
  3. ViewResolver 结合Model和View,来渲染视图。
  4. 视图负责将渲染结果返回给客户端

SpringMVC开发步骤

1、创建一个web的maven工程

 2、修改pom.xml文件,添加SpringMVC的依赖,添加Servlet的依赖



    4.0.0

    com.lin.spring
    springmvc_001_demo
    1.0-SNAPSHOT
    
    war
    
    
        
        
            org.springframework
            spring-webmvc
            5.2.5.RELEASE
        

        
        
            javax.servlet
            javax.servlet-api
            3.1.0
            
            provided
        
    

    
        
            
                src/main/java
                
                    ***.properties
                
            
            
                src/main/resources
                
                    ***.properties
                
            
        
    


x


 3、添加SpringMVC的配置文件,指定包扫描,添加视图解析器ViewResolver。




    
    

    
    
        
        
        
        
    

4、在web.xml文件中注册springMVC框架(所有的web请求都是基于servlet的)

1、用了SpringMVC框架的web项目请求执行的流程


                                          核心处理器
  index.jsp<--------------->DispatcherServlet<------------------->SpringMVC的处理器是一个普通的方法
  one.jsp  <--------------->DispatcherServlet<------------------->SpringMVC的处理器是一个普通的方法

前端发送请求到tomcat服务器,请求被SpringMVC的大哥前端控制器 DispatcherServlet 捕获,然后DispatcherServlet将请求转发给控制层controller中对应的普通方法

2、为啥要在web.xml文件中注册DispatcherServlet类?

因为这个类不在我们自己的源码中,所以不能通过@WebServlet注解指定该类的访问路径,所以只能在web.xml文件中注册使用。




    
    
        springmvc
        org.springframework.web.servlet.DispatcherServlet
        
        
        
        
            contextConfigLocation
            
            classpath:springmvc.xml
        
        
        
        1
    
    
        springmvc
        
        *.action
        *.test
    

5、在webapp目录下新建admin目录,在admin目录下新建main.jsp页面

 6、开发控制器(相当于Servlet),它是一个普通的类。

@Controller// 交给SpringMVC创建对象,是一个控制层组件
public class HelloServlet {
    
    // http://localhost:8080/springmvc/demo.action
    // 当浏览器发送的请求路径是 /demo 的时候,就会来执行这个/demo注解所对应的方法。
    @RequestMapping("/demo")
    public String demo(){
        System.out.println("服务器被访问到了.......");
        return "main";  //可以直接跳到/admin/main.jsp页面上
    }

    // 当浏览器发送的请求路径是 /my.test 的时候,就会来执行这个注解所对应的方法。
    @RequestMapping("/my.test")
    public String demo2(){
        System.out.println("服务器被访问到了2.......");
        // 返回要跳转的视图名称,交给ViewResolver处理解析
        return "test";  //可以直接跳到/admin/test.jsp页面上
    }
}

7、web目录下的index.jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

  
    index.jsp
  
  
    index.jsp
    <%--向tomcat服务器发送请求:/项目根路径/demo.action --%>
    <%--http://localhost:8080/springmvc/demo.action--%>
    访问服务器
    访问服务器2
  

个人理解2022.6.17

当前端发送http://localhost:8080/springmvc/my.test给tomcat服务器时,这个请求会被Springmvc的DispatcherResolver拦截,然后DispatcherServlet将请求转发给控制层controller中对应的普通方法,就是@RequestMapping("/my.test")这个注解对应的方法:

public String demo2(){
        System.out.println("服务器被访问到了2.......");
        return "test";  //可以直接跳到/admin/test.jsp页面上
    }

这个方法执行后返回"test",会被SpringMVC的视图解析器ViewResolver解析处理,加上前缀和后缀变成 /admin/test.jsp,然后将这个页面渲染后转发到这个页面中。

总结:

浏览器发送请求给服务器,若请求地址符合前端控制器DispatcherServlet的url-pattern,该请求就会被前端控制器DispatcherServlet处理。
前端控制器会读取SpringMVC的核心配置文件,通过扫描组件找到控制器带@Controller注解的类,将请求地址和控制器中@RequestMapping注解的value属性值进行匹配,若匹配成功,该注解所标识的控制器方法就是处理请求的方法。

处理请求的方法需要返回一个字符串类型的视图名称,该视图名称会被视图解析器解析,加上前缀和后缀组成视图的路径,对视图进行渲染,最终转发到视图所对应页面

 @RequestMapping注解详解

@RequestMapping注解详解
  此注解就是来映射服务器访问的路径.
  1)此注解可加在方法上,请求路径对应的某个方法
  @RequestMapping("/demo")
    public String demo(){
        System.out.println("服务器被访问到了.......");
        return "main";  //可以直接跳到/admin/main.jsp页面上
    }
  访问服务器

  2)此注解可以加在类上,相当于是包名(虚拟路径),区分不同类中相同的action的名称
  @RequestMapping("/user")
  public class DemoAction1 {..}
  访问服务器

  3)此注解可区分get请求和post请求
  @Controller
    public class ReqAction {
        @RequestMapping(value = "/req",method = RequestMethod.GET)
        public String req(){
            System.out.println("我是处理get请求的........");
            return "main";
        }
        @RequestMapping(value = "/req" ,method = RequestMethod.POST)
        public String req1(){
            System.out.println("我是处理post请求的........");
            return "main";
        }
    }

SpringMVC要优化的方面
  1. 客户端提交数据的优化
  2. 控制器方法的返回值优化
  3.  资源跳转的优化
  4. 携带数据进行资源跳转的优化
  5. 简化返回处理(服务器响应优化)

1、客户端提交数据的5种优化
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    数据提交的方式


    

1.单个提交数据



姓名:
年龄:

2.对象封装提交数据

姓名:
年龄:

<%--仅限于超链接或地址拦提交数据.它是一杠一值提交数据,一杠一大括号接收对应的数据,使用注解@PathVariable来解析. --%>

3.动态占位符提交数据

动态占位符提交数据

4.请求参数和接收形参名不一致

姓名:
年龄:

5.手动提取数据request.getParameter(name)

姓名:
年龄:
package com.lin.springmvc.controller;

import com.lin.springmvc.bean.User;
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.RequestParam;

import javax.servlet.http.HttpServletRequest;


@Controller
public class DataSubmitAction {

    
    @RequestMapping("/dataone")
    public String dataOne(String myName,int age){

        System.out.println("获取到前端数据了,name=" + myName + ",age=" + age);
        return "success";
    }

    
    @RequestMapping("/datatwo")
    public String dataTwo(User user){

        System.out.println(user);// User{uName='阿吉', age=21}
        return "success";
    }

    
    @RequestMapping("/datathree/{uName}/{age}")
    public String dataThree(@PathVariable("uName")String name,@PathVariable int age){

        System.out.println("获取到前端数据了,name=" + name + ",age=" + age);
        // 获取到前端数据了,name=张三,age=26

        return "success";
    }

    
    @RequestMapping("/datafour")
    public String dataFour(@RequestParam("name") String uName,@RequestParam("age") String uAge){

        System.out.println("获取到前端数据了,name=" + uName + ",age=" + uAge);

        return "success";
    }

    
    @RequestMapping("/datafive")
    public String dataFive(HttpServletRequest request){
        String name = request.getParameter("name");
        Integer age = Integer.valueOf(request.getParameter("age"));

        System.out.println("获取到前端数据了,name=" + name + ",age=" + age);

        return "success";
    }
}

2、控制器方法的返回值优化
  1. String:服务器端资源的地址,会自动拼接前缀和后缀后然后转发展示。还可以屏蔽自动拼接字符串,可以指定返回的路径.
  2. Object:返回json格式的对象.自动将对象或集合转为json.使用的jackson工具进行转换,必须要添加jackson依赖.一般用于ajax请求.
  3. void:无返回值,一般用于ajax请求.
  4. 基本数据类型,用于ajax请求.
  5. ModelAndView:返回数据和视图对象,现在用的很少.

3、资源跳转的优化
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

  
    $Title$
  
  
    

测试资源跳转的四种方式


1.请求转发到页面上
2.请求转发到action方法上
3.重定向到页面上
4.重定向到action方法上
package com.lin.springmvc.controller;

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


@Controller
public class JumpAction {

    @RequestMapping("/one")
    public String forwardToPage(){
        System.out.println("请求转发到target.jsp页面.......");

        // 这个返回的字符串会被SpringMVC的视图解析器加上前缀/myPage/,加上后缀.jsp变成/myPage/target.jsp
        // 默认使用请求转发的方式转发到这个页面上/myPage/target.jsp
        return "target";
    }

    @RequestMapping("/two")
    public String forwardToAction(){
        System.out.println("请求转发到action方法中......");
        // 倘若返回的字符串中包含 forward:
        // 就会被视图解析器解析是要进行转发到action,所以不会进行前缀和后缀的拼接
        // forward: 表示我要进行资源的转发了,转发请求路径是 /other.action
        return "forward:/other.action";

        // 要请求转发这样是错误的,会变成 /myPage//other.action.jsp
//        return "/other.action";
    }

    @RequestMapping("/three")
    public String redirectToPage(){
        System.out.println("重定向到target.jsp页面.....");

        // redirect: 表示我要重定向了,视图解析器会屏蔽前缀后缀的拼接,重定向到 /myPage/target.jsp
        return "redirect:/myPage/target.jsp";
    }

    @RequestMapping("/four")
    public String redirectToAction(){
        System.out.println("重定向到action方法.....");

        return "redirect:/other.action";
    }
}

 

SpringMVC中文编码设置
    

5.手动提取数据request.getParameter(name)

姓名:
年龄:
    @RequestMapping("/datafive")
    public String dataFive(HttpServletRequest request){
        String name = request.getParameter("name");
        Integer age = Integer.valueOf(request.getParameter("age"));

        System.out.println("获取到前端数据了,name=" + name + ",age=" + age);

        return "success";
    }

乱码: 

解决方案

在 web.xml 中注册字符集过滤器,即可解决 Spring 的请求参数的中文乱码问题。不过,最好将该过滤器注册在其它过滤器之前。因为过滤器的执行是按照其注册顺序进行的。

    
    
        endode
        org.springframework.web.filter.CharacterEncodingFilter
        
        
            encoding
            UTF-8
        
        
            forceRequestEncoding
            true
        
        
            forceResponseEncoding
            true
        
    
    
        endode
        
        
          success:function (sutList) {
            alert(sutList);
            // 用于拼接学生信息
            var stuInfo = "";

            // 遍历
            $.each(sutList,function (index, stu) {
              stuInfo += stu.name + "---" + stu.age + "
"; }) // 将学生信息回显到界面中 $("#stuInfo").html(stuInfo); } }) }
@Controller
public class ListStudentAction {


    
    @RequestMapping("/list")
    @ResponseBody // 此注解专门用于处理解析Ajax请求
    public List getStuList(){

        List stuList = new ArrayList<>();
        stuList.add(new Student("张三",3));
        stuList.add(new Student("李四",3));
        stuList.add(new Student("王五",3));
        System.out.println(stuList);

        // 调用json转换工具ObjectMapper进行转换
        return stuList;// SpringMVC自动将对象转换为json数组
    }
}

SpringMVC默认的参数类型(内置对象)

  不需要去创建,直接拿来使用即可.
  1)HttpServletRequest
  2)HttpServletResponse
  3)HttpSession
  4)Model
  5)Map
  6)ModelMap

注意:Map,Model,ModelMap和request一样,都使用请求作用域进行数据传递。所以服务器端想利用这三个存储数据,然后携带这些数据到别的页面或方法必须使用请求转发。

HttpServletRequest,HttpSession,Model,Map,ModelMap主要都是用来存储数据的,都有类似setAttribute(name,value);方法。只有HttpServletResponse是用来处理响应的相关问题。

    

测试SpringMVC默认的参数


去存储数据
@Controller
public class DataAction {

    @RequestMapping("/data")
    public String keepData(HttpServletRequest request, Map map, Model model, ModelMap modelMap, HttpSession session,
                           HttpServletResponse response) throws IOException {
        // 进行存储数据
        request.setAttribute("requestString","请求域中的数据");
        map.put("mapString","map中的数据");
        model.addAttribute("modelString","model中的数据");
        modelMap.addAttribute("modelMapString","modelMap中的数据");
        session.setAttribute("sessionString","session域中的数据");

        PrintWriter out = response.getWriter();
        out.println("hello from response");
        return "target";
    }
}
SpringMVC日期处理

  1)日期的提交处理
    A.单个日期处理
    要使用注解@DateTimeFormat,此注解必须搭配springmvc.xml文件中的

    B.类中全局日期处理
    注册一个注解,用来解析本类中所有的日期类型,自动转换.

// 以上日期处理有一个问题,就是每涉及一个日期提交和日期接收处理,都要使用@DateTimeFormat,这样比较麻烦
// 可以定义一个全局的日期处理,注册一个注解,用来解析本类中所有的日期类型,自动转换.

@InitBinder
public void initBinder(WebDataBinder webDataBinder){
    // 注册一个自定义的编辑器
    webDataBinder.registerCustomEditor(Date.class,new CustomDateEditor(sdf,true));
}

  2)日期的显示处理

package com.lin.springmvc.controller;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;

import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.Date;


@Controller
public class DateAction {
    // 用来格式化日期类型
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");


    
//    @RequestMapping("/date")
    // java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'java.util.Date': no matching editors or conversion strategy found
    // 日期类型和字符串不能自动转换,前端发送过来的字符串不能自动转为日期类型,需要使用@DateTimeFormat转



    
    // 以上日期处理有一个问题,就是每涉及一个日期提交和日期接收处理,都要使用@DateTimeFormat,这样比较麻烦
    // 可以定义一个全局的日期处理,注册一个注解,用来解析本类中所有的日期类型,自动转换.
    
    @InitBinder
    public void initBinder(WebDataBinder webDataBinder){
        // 注册一个自定义的编辑器
        webDataBinder.registerCustomEditor(Date.class,new CustomDateEditor(sdf,true));
    }

    @RequestMapping("/date")
    public String receiveDate(@DateTimeFormat(pattern = "yyyy-MM-dd") Date myDate){
        System.out.println(myDate);

        String beautifulDate = sdf.format(myDate);
        System.out.println(beautifulDate);
        return "date";
    }
}

 

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

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

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