Spring Controller入门
Spring MVC是java web的一种实现方案
web服务做的事情
Spring Controller技术有三个核心点
- Bean的配置:Controller注解的运用
- 网络资源的加载:加载网页
- 网络路由的配置:RequestMapping注解运用
Controller注解
Sprng Controller本身也是一个Spring Bean,只是它多提供了web服务,只要在类上面添加一个@Controller注解就可以了
import org.springframework.stereotype.Controller;
@Controller
public class HelloControl {
}
RequestMapping注解
对于web服务器来说,必须要实现的一个能力是解析URL,并提供资源内容给调用者,这个过程一般称为路由。
只需要在提供需要web访问的方法上添加一个@RequestMapping
注解就可以完成配置了
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloControl {
@RequestMapping("/hello")
public String say(){
return "html/hello.html";
}
}
@GetMapping
可以使用@GetMapping
来替换注解@RequestMapping
,他们的包路径是一样的。
import org.springframework.web.bind.annotation.*;
@GetMapping("/songlist")
public String index(@RequestParam("id") String id,@RequestParam("pageNum") int pageNum){
return "html/songList.html";
}
输出JSON数据
在Spring当中配置JSON数据非常简单,如下
@GetMapping("/api/foos")
@ResponseBody
public String getFoos(@RequestParam("id") String id) {
return "ID: " + id;
}
如上,只要在方法上增加@ResponseBody
注解,
一般把输出JSON数据的方法称为API