<3>SpringBoot Controller
(示例项目:demo。项目路径:C:\somethingfromeF\25SummerVacation\demo)
1.控制器(@Controller和@RestController)
a.@Controller往往用于前后端不分离的情况,传回页面和数据,一般和Thymeleaf模板引擎结合使用。
b.@RestController往往用于前后端分离的情况,只传回数据。
2.路由映射(@RequestMapping)

a.
@GetMapping("/hello")
和
@RequestMapping(value = "/hello",method = RequestMethod.GET)
是一样的,只不过完整和简写的区别。
b.一些功能应用
代码:
@RestController
public class HelloController {
// 访问路径:http://localhost:8080/hello
// 访问路径:http://localhost:8080/hello?nickname=zhangsan&phpne=123
@RequestMapping(value = "/hello",method = RequestMethod.GET)
public String hello(String nickname,String phone) {
return "hello world "+nickname;
}
}
结果如下图:

3.两个post工具
apipost和postman
4.以apipost为例
a.Hellocontroller.java下面:
@RequestMapping(value = "/postTest1", method = RequestMethod.POST)
public String postTest2(User user) {
System.out.println(user);
return "Post 请求";
}
b.(string 很多)--->专门设立一个实体类封装在里面

c.apipost执行

d.编译器输出:(user实体类里面了相当于)

5.常见错误
a.404
b.405
.......
6.附录
package com.example.demo.controller;
import com.example.demo.entity.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ParamsController {
@RequestMapping(value="/getTest1",method= RequestMethod.GET)
public String getTest1(){
return "GET请求";
}
@RequestMapping(value="/getTest2",method = RequestMethod.GET)
// http://localhost:8080/getTest2?nickname=xxx&phone=xxx
public String getTest2(String nickname,String phone){
System.out.println("nickname:"+nickname);
System.out.println("phone:"+phone);
return"GET请求";
}
@RequestMapping(value="/postTest1",method=RequestMethod.POST)
public String postTest1 (){
return "POST请求";
}
@RequestMapping(value="/postTest2",method=RequestMethod.POST)
public String postTest2 (String username ,String password ){
System.out.println("username:"+username);
System.out.println("password:"+password);
return "POST请求";
}
@RequestMapping(value="/postTest3",method=RequestMethod.POST)
public String postTest3 (User user){
System.out.println(user);
return "POST请求";
}
//"/test/*"代表http://localhost8080/test/xxx(一个)
@GetMapping("/test/**")//http://localhost8080/test/xxx/xxx(任意)
public String test ( ){
return "POST请求";
}
}
posted on 2025-08-08 18:23 Adda...nina 阅读(13) 评论(1) 收藏 举报
浙公网安备 33010602011771号