spring boot搭建网站后记之spring boot层次与URL处理

    经过第一部分,了解了Maven项目的文件分布。前端

  经过第二部分,了解了Spring MVC。数据库

  到了Spring boot中,一切都获得了简化,能够将立刻要用到的文件与Spring MVC进行对应,这样比较好理解MVC设计模式。设计模式

 

Spring boot层次

 

  DAO层:data acess object。是数据库的访问的对象。(M层)数组

  Service层:对数据库的对象进行统一的操做。业务逻辑层。(M层)浏览器

  Controller层:接受用户请求并返回数据。(C层)app

  Base层:若Service层和Controller层链接过与紧密,则加入Base层。网站

  View层:负责前端显示。(V层)ui

  

增长url访问路径 

1 @Controller 2 public class deal { 3  @ResponseBody 4     @RequestMapping(path = {"/", "/hello"}) 5     public String index() { 6         return "Hello World"; 7  } 8 }

探究:url

  Ctrl+左键进入RequestMapping,它对应到RequestMapping接口。spa

  调用@RequestMapping(path = {"/", "/hello"})方法,根据视频它对应到下面的方法:

1 @AliasFor("value") 2     String[] path() default {};

  其方法能够将{"/", "/hello"}转化成一个String数组。用户访问/或者/hello均可行。

  其效果是:

    在浏览器中输入127.0.0.1:8080/或者是127.0.0.1:8080/hello均可以看到hello world的页面。

  值得注意的是,在controller文件中没有定义path变量,可是在@RequestMapping却能够用,说明@RequestMapping实际是在其余定义好了path变量的文件中执行,而不是controller文件中执行。

  并且更有意思的是,将path变量改为其它变量dd,出错:The attribute dd is undefined for the annotation type。

 

给url增长参数

有时候网站url栏出现的网址为:127.0.0.1:8080/profile/2/1?key=12334x&type=12 这种形式。实现代码以下:

1  //{goupid},{userid}为路径变量,访问时能够自行修改。而profile则是固定的路径了。
2   @RequestMapping(path = {"/profile/{groupid}/{userid}"})
3 @ResponseBody
4   //PathVariable是路径中的一个变量。路径中的值类型在本程序中转成对应的gp,ui的String类型
5 public String profile(@PathVariable("groupid") String gp, 6 @PathVariable("userid") String ui,
7   //RequestParam不是路径中的变量,而是额外加上的变量。url中的值转化成本程序的int类型和String类型的type和key变量。
8 @RequestParam(value = "type", defaultValue = "1") int type, 9 @RequestParam(value = "key", defaultValue = "nowcoder") String key) { 10 //最后把url变量显示在网页中。
11     return String.format("GID{%s}, UID{%s}, TYPE{%d}, KEY{%s}", gp, ui, type, key);
12 }

   效果:

    访问http://127.0.0.1:8080/profile/2/1?key=12334x&type=1

    显示:

      GID{2}, UID{1}, TYPE{1}, KEY{12334x}