前一篇我们探讨了关于springboot的配置文件和Controller的使用,本篇我们来一起探讨一下关于springboot如何传递参数的知识。

  参数传递我们最常见的就是在url后通过?/&两个符号来将参数传递到后台,当然springboot也是也一样,我们可以通过这种方式将参数传递到后台,那么后台如何接收这些参数呢?下面我们一起学习一下:

  这里我们将用到@RequestParam注解,这个注解有三个参数分别是:value、required、defaultValue,具体的用法,下面一一为大家介绍。

    @RequestMapping(value = "/par1", method = RequestMethod.GET)
    public String reqPar1(@RequestParam("name") String name){
        return name;
    }

  通过@RequestParam注解声明接收用户传入的参数,这样当我们在浏览器输入http://localhost:8080/par1?name=123

    @RequestMapping(value = "/par2", method = RequestMethod.GET)
    public String reqPar2(@RequestParam(value = "name", required = false) String name){
        if(null != name){
            return name;
        }else{
            return "未传入参数";
        }
    }

  我们看到第一个接口我们并没有写value和required,其实第一个接口是简写,等同于

@RequestParam(value = "name", required = true)

  required=true:该参数不能为空;相反required=false:该参数能为空

    @RequestMapping(value = "/par3", method = RequestMethod.GET)
    public String reqPar3(@RequestParam(value = "name", defaultValue = "null") String name){
        return name;
    }

  最后说一下defaultValue看字面意思,估计你已经想到它的作用了,是的当我们未穿入该参数时的默认值。

  下面我们先看一下博客园中博客地址的链接:http://www.cnblogs.com/AndroidJotting/p/8232686.html,请大家注意红色位置,这样的参数传递是不是很有趣,我们并不用设置参数的key,那么这是怎么实现的呢?请接着看。

    @RequestMapping(value = "/par4/{id}", method = RequestMethod.GET)
    public Integer reqPar4(@PathVariable("id") Integer id){
        return id;
    }

  这样是不是和博客园的访问很像,这样我们便可以直接将传递参数加在url后面。最后再来活学活用一下:

    @RequestMapping(value = "/{id}/par5", method = RequestMethod.GET)
    public Integer reqPar5(@PathVariable("id") Integer id){
        return id;
    }

  OK到这里关于参数传递的内容就和大家分享完毕,最后再给大家补充一个小知识:

  resources资源springboot默认只映射static、templates两个文件夹下的文件,那么如何进行拓展呢?很简单,比如我们在resources下新建一个image资源,这是我们需要打开项目的主类:xxApplication

@SpringBootApplication
public class Springboot1Application extends WebMvcConfigurerAdapter {

    public static void main(String[] args) {
        SpringApplication.run(Springboot1Application.class, args);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        super.addResourceHandlers(registry);
        //这种方式会在默认的基础上增加/image/**映射到classpath:/image/,不会影响默认的方式,可以同时使用。
        registry.addResourceHandler("/image/**")
                .addResourceLocations("classpath:/image/");
    }
}

  这样简单一配置,我们就完成了上面的需求。

  下一篇springboot持久化操作

分类:

技术点:

相关文章: