1、在Spring-MVC中使用REST时,首先我们需要导入相应的依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.6.RELEASE</version>
</dependency>
<!--添加这个 依赖 后可以可以保证将所有的对象数据转换为 JSON 格式-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.10</version>
</dependency>
</dependencies>
2、然后在controller控制器前添加 @RestController 注解 ,这是一种方法;另一种方法是 添加 @Controller 注解,但是在调用不同的路径时,需要在下面 添加上 @ResponseBody 注解,也就是(@Controller + @ResponseBody )一起使用。同时不同的方法我们可以根据不同的注解进行调用,例 @GetMapping 、@PostMaping 、@PutMapping、 @DeleteMapping 这些注解。举例如下:
package com.qfedu.controller;
import com.qfedu.bean.User;
import com.qfedu.service.Impe.UserServiceImpe;
import com.qfedu.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/** 使用 REST 时,有两种方法,
* 第一种是直接添加 @RestController 注解 ( 注意添加 pom 文件中的 依赖)
* 第二种是使用 @Controller注解, 然后 在要调用的路径下 添加 @ResponseBody 注解 。
* Created by asus on 2020/3/6.
*/
/* @RestController 第一种方法直接使用 RestController 注解 */
@Controller
public class UserController {
private UserService us=new UserServiceImpe();
@GetMapping("/users")
@ResponseBody
public List<User> getAllUsers(){
return us.getAllUsers();
}
@GetMapping("/users/{uid}")
public User getUserById(@PathVariable int uid){
return us.getUserById(uid);
}
@DeleteMapping("/delete/{uid}")
/*@ResponseBody 第二种方法,可以直接使用Controller 注解 + ResponseBody 注解 */
public boolean deleteUser(@PathVariable int uid){
System.out.println("删除成功!");
return us.deleteUser(uid);
}
@PostMapping("/save/{uid}/{name}/{password}/{age}")
public boolean saveUser(@PathVariable int uid,@PathVariable String name,@PathVariable String password,@PathVariable int age){
User user=new User(uid,name,password,age);
System.out.println("添加成功!");
return us.saveUser(user);
}
@PutMapping("/update/{uid}/{name}/{password}/{age}/{uids}")
public boolean updateUser(@PathVariable int uid,@PathVariable String name,@PathVariable String password,@PathVariable int age,@PathVariable int uids){
User user=new User(uid,name,password,age);
System.out.println("更新成功!");
return us.updateUser(user,uids);
}
}
3、关于出现错误的提示页面
首先在web.xml中配置 ,我们可以根据不同的错误,来展示不同的页面,例
<!--表示 一旦 出现 404 错误, 就会自动跳转到 404 .jsp 这个界面中 -->
<error-page>
<error-code>404</error-code>
<location>/404.jsp</location>
</error-page>