前一篇咱们探讨了关于springboot的配置文件和Controller的使用,本篇咱们来一块儿探讨一下关于springboot如何传递参数的知识。html
参数传递咱们最多见的就是在url后经过?/&两个符号来将参数传递到后台,固然springboot也是也同样,咱们能够经过这种方式将参数传递到后台,那么后台如何接收这些参数呢?下面咱们一块儿学习一下:spring
这里咱们将用到@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=123springboot
@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,其实第一个接口是简写,等同于app
@RequestParam(value = "name", required = true)
required=true:该参数不能为空;相反required=false:该参数能为空ide
@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,那么这是怎么实现的呢?请接着看。ui
@RequestMapping(value = "/par4/{id}", method = RequestMethod.GET) public Integer reqPar4(@PathVariable("id") Integer id){ return id; }
这样是否是和博客园的访问很像,这样咱们即可以直接将传递参数加在url后面。最后再来活学活用一下:url
@RequestMapping(value = "/{id}/par5", method = RequestMethod.GET) public Integer reqPar5(@PathVariable("id") Integer id){ return id; }
OK到这里关于参数传递的内容就和你们分享完毕,最后再给你们补充一个小知识:spa
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持久化操做