• 学习SpringMVC——如何获取请求参数


    @RequestParam
    
    @PathVariable
    
    @QueryParam
    
    @CookieValue
    
    @ModelAndView
    
    @ModelAttribute

    一、spring mvc如何匹配请求路径——“请求路径哪家强,RequestMapping名远扬”

    @RequestMapping是用来映射请求的,比如get请求,post请求,或者REST风格与非REST风格的。 该注解可以用在类上或者方法上,如果用于类上,表示该类中所有方法的父路径。

    @Controller的注解,该注解在SpringMVC 中,负责处理由DispatcherServlet 分发的请求,它把用户请求的数据经过业务处理层处理之后封装成一个Model ,然后再把该Model 返回给对应的View 进行展示。

    RequestMapping可以实现模糊匹配路径,比如:
    
      ?:匹配一个字符
    
      *:匹配任意字符
    
      **:匹配多层路径
    
      /springmvc/**/lastTest 就可以匹配/springmvc/firstTest/secondTest/lastTest这样的路径
    

    二、spring mvc如何获取请求的参数——“八仙过海,各显神通”  

    1. @PathVariable

      该注解用来映射请求URL中绑定的占位符。通过@PathVariable可以将URL中占位符的参数绑定到controller处理方法的入参中

    @RequestMapping("/testPathVariable/{id}")
    public String testPathVariable(@PathVariable(value="id") Integer id){
        System.out.println("testPathVariable:" + id);
        return SUCCESS;
    }
    <a href="springmvc/testPathVariable/1">testPathVariable</a><br/><br/>
    

      

    2. @RequestParam

      该注解也是用来获取请求参数的。那么该注解和@PathVariable有何不同呢?

    @RequestMapping(value="/testRequestParam")
    public String testRequestParam(@RequestParam(value="username") String username, @RequestParam(value="age", required=false, defaultValue="0") int age){
        System.out.println("testRequestParam" + " username:" + username + " age:" +age);
        return SUCCESS;
    }

    注:@PathVariable和@RequestParam之间的一些区别

    请求参数是以键值对出现的,我们通过@RequestParam来获取到如username或age后的具体请求值

    增删改都是通过post方式发送出去的
    

    总结下,如何发送put和delete的请求:

    1.在web.xml中配置HiddenHttpMethodFilter

    <!-- 配置HiddenHttpMethodFilter:可以把POST请求转为DELETE或POST请求 -->
    <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>
    <input type="hidden" name="_method" value="DELETE"/>
    

      

    2.发送post请求

    3.请求中是个隐藏域,name为”_mothod”,value为put或delete

      

    3. @CookieValue

    也是一种映射,映射的是一个Cookie值。

     @RequestMapping("/hellocookie")
        public String testCookieValue(@CookieValue("JSESSIONID") String cookieValue){
            System.out.println("testCookieValue: " + cookieValue);
            return "success";
        }

    index.jsp界面上添加链接

    <a href="hellocookie">hellocookie</a>

  • 相关阅读:
    Java基础系列——IO流
    如何为网站添加 CSS 暗模式(转载)
    详解 UWP (通用 Windows 平台) 中的两种 HttpClient API
    微软微服务架构 eShopOnContainers
    web开发中使用html/css全屏铺开显示
    web开发中的Cookie
    WPF依赖属性Binding实现
    SQL Server2014安装流程及注意事项
    .Net配置文件读取及修改方法封装(未加密)
    WCF开发优秀博客园推荐
  • 原文地址:https://www.cnblogs.com/tanlei-sxs/p/9981524.html
Copyright © 2020-2023  润新知