在《Spring Boot快速入门》基础上编写服务。
编写controller服务
新建controller包,包下新建HelloController:
package com.wong.ok.controller;
import com.alibaba.fastjson.JSON;
import com.wong.ok.bean.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@RestController
public class HelloController {
@ResponseBody
@RequestMapping("/hi")
public String hello(){
return "Hello";
}
/*default value*/
/*带默认值的*/
@ResponseBody
@RequestMapping("/goods")
public String showGoods(@RequestParam(defaultValue = "Potato") String productName){
return "product name:"+productName;
}
@ResponseBody
@RequestMapping("/user")
public User getUser(){
return new User("Tom1","boy","student");
}
@ResponseBody
@RequestMapping("/login")
public User login(User user){
user.setName(user.getName()+" Wong");
return user;
}
@ResponseBody
@RequestMapping("/login2")
public void login2(User user, HttpServletResponse response){
try {
user.setName(user.getName()+" Wong");
response.getWriter().write(JSON.toJSONString(user));
} catch (IOException e) {
e.printStackTrace();
}
}
}
-
@RestController 标志这是一个控制器
-
@ResponseBody 会包装返回结果,@responseBody注解的作用是将controller的方法返回的对象通过适当的转换器转换为指定的格式之后,写入到response对象的body区,通常用来返回JSON数据或者是XML
-
@RequestMapping 是匹配前台请求路径的
运行
- 启动服务:Run ‘OkApplication’
- 在浏览器访问此服务:
- http://localhost:8080/hi
- http://localhost:8080/goods
- http://localhost:8080/goods?productName=tomato
- http://localhost:8080/user
- http://localhost:8080/login
- http://localhost:8080/login2
/login与/login2的请求是等价的。
谢谢阅读