springboot下使用Restful风格

87 阅读3分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第13天,点击查看活动详情

什么是RESTful

RESTFUL是一种网络应用程序的设计风格和开发方式,基于HTTP,可以使用XML格式定义或JSON格式定义。RESTFUL适用于移动互联网厂商作为业务接口的场景,实现第三方OTT调用移动网络资源的功能,动作类型为新增、变更、删除所调用资源。

而在Spring Boot中使用RESTful服务非常简单。接下来就让我们学习一下吧。

检查依赖

首先,需要在pom.xml文件中添加对Spring MVC的依赖

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>

这其实就是对Spring MVC的依赖。

一个小demo

然后,可以使用@RestController注解的类来创建RESTful控制器。控制器可以包含多个处理HTTP请求的方法,这些方法可以使用@RequestMapping注解来映射到特定的HTTP路径和方法。例如:

@RestController
public class MyController {

   @RequestMapping(value="/users", method=RequestMethod.GET)
   public List<User> getUsers() {
      // retrieve users from database
      return users;
   }

   @RequestMapping(value="/users", method=RequestMethod.POST)
   public void addUser(@RequestBody User user) {
      // add user to database
   }

   @RequestMapping(value="/users/{id}", method=RequestMethod.GET)
   public User getUser(@PathVariable Long id) {
      // retrieve user from database
      return user;
   }

   @RequestMapping(value="/users/{id}", method=RequestMethod.PUT)
   public void updateUser(@PathVariable Long id, @RequestBody User user) {
      // update user in database
   }

   @RequestMapping(value="/users/{id}", method=RequestMethod.DELETE)
   public void deleteUser(@PathVariable Long id) {
      // delete user from database
   }
}

在这个例子中,我们有一个控制器包含五个处理HTTP请求的方法。第一个方法处理GET请求,并返回所有用户的列表。第二个方法处理POST请求,用于新增用户。第三个方法处理GET请求,并返回指定ID的用户。第四个方法处理PUT请求,用于更新用户。最后一个方法处理DELETE请求,用于删除,当然,delete请求并不是安全的,实际项目开发我们可能不会这么去使用。

如何将项目中static中的html文件通过restful呈现

@RestController
public class MyController {

   @RequestMapping(value="/index.html", method=RequestMethod.GET)
   public String getIndexPage() {
      return "forward:/index.html";
   }
}

这个方法使用"forward"前缀来将请求转发到"/index.html",这样Tomcat就会返回你的HTML文件。

注意:这种方法只能用于返回静态HTML文件,如果你想要返回动态内容,你可能需要使用其他技术,例如使用Spring MVC的视图解析器或使用模板引擎。

当然,我们也可以使用servlet 提供的API,如下:

package com.example.lyyshop.control;

import org.springframework.stereotype.Controller;
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;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
public class RestForHtml {
    @RequestMapping(value="/login", method= RequestMethod.GET)
    public void getLoginPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/html/login.html").forward(request,response);
    }
}

可能出现的问题

访问了该接口,但是只在页面中返回了字符串,并没有转发到index.html页面上

如果在调用RESTful接口时仅返回字符串而没有转发到HTML页面,这可能是因为你的Spring Boot应用程序没有正确配置内置的Tomcat服务器来提供静态资源。

要解决这个问题,你需要在你的应用程序的配置类中添加以下代码:

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

   @Override
   public void addResourceHandlers(ResourceHandlerRegistry registry) {
      registry.addResourceHandler("/**")
            .addResourceLocations("classpath:/static/");
   }
}

这段代码告诉Spring Boot将"/static"文件夹中的所有文件映射到"/**" URL。这样,当你访问"/index.html"时,Tomcat就会返回"/static/index.html"文件。

注意:这段代码假设你的HTML文件位于"src/main/resources/static"文件夹中。如果你的文件位于其他位置,你需要修改"addResourceLocations"方法的参数以指向正确的文件夹。