@RequestParam注解使用

版权声明:转载请注明原始链接 https://blog.csdn.net/sswqzx/article/details/84195043

1、作用:

@RequestParam:接收普通的请求参数(是springmvc中接收普通参数的注解)

2、语法:

语法:@RequestParam(value=”参数名”,required=”true/false”,defaultValue=””)

value:参数名

required:是否包含该参数,默认为true,表示该请求路径中必须包含该参数,如果不包含就报错。

defaultValue:默认参数值,如果设置了该值,required=true将失效,自动为false,如果没有传该参数,就使用默认值

3、测试环境:

环境:jdk1.8 Tomcat8.5  idea2018  manven父工程子模块
 
步骤:
1、创建web工程、引入依赖
2、配置SpringMvc入口文件 --DispatcherServlet--为总调度、web.xml里配置
3、创建Springmvc.xml文件--理解为:适配器(这里不需要自已指定适配、springmvc会自动指定)--视图解析器
4、创建 业务处理器 Controller类
5、测试
 

4、工程结构:

步骤1、2、3、参考:SpringMvc入门案例:https://blog.csdn.net/sswqzx/article/details/84171999

5、业务处理器HelloController.java

package com.day01springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

/**
 * @ Author     :ShaoWei Sun.
 * @ Date       :Created in 20:58 2018/11/16
 */
@Controller
@RequestMapping("hello")
public class HelloController2 {

    /**
     * 接收普通请求参数
     * http://localhost:8080/hello/show16?name=linuxsir
     * url参数中的name必须要和@RequestParam("name")一致
     * @return
     */
    @RequestMapping("show16")
    public ModelAndView test16(@RequestParam("name")String name){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("hello2");
        mv.addObject("msg", "接收普通的请求参数:" + name);
        return mv;
    }

    /**
     * 接收普通请求参数
     * http://localhost:8080/hello/show17
     * url中没有name参数不会报错、有就显示出来
     * @return
     */
    @RequestMapping("show17")
    public ModelAndView test17(@RequestParam(value="name",required=false)String name){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("hello2");
        mv.addObject("msg", "接收普通请求参数:" + name);
        return mv;
    }

    /**
     * 接收普通请求参数
     * http://localhost:8080/hello/show18?name=998 显示为998
     * http://localhost:8080/hello/show18?name 显示为hello
     * @return
     */
    @RequestMapping("show18")
    public ModelAndView test18(@RequestParam(value="name",required=true,defaultValue="hello")String name){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("hello2");
        mv.addObject("msg", "接收普通请求参数:" + name);
        return mv;
    }

}

6、测试:

 

 

猜你喜欢

转载自blog.csdn.net/sswqzx/article/details/84195043