【问题标题】:Can you use jsp for your front end while your backend routes are restful in Spring Boot?你可以在 Spring Boot 中使用 jsp 作为前端,而后端路由是安静的吗?
【发布时间】:2020-06-23 19:25:43
【问题描述】:
@RestController

公共类 IndexController {

@RequestMapping("/")
public String indexRoute() {
    return JSON HERE;
}

假设以上是我的后端路由,有什么办法可以用 jsp 显示它吗? 我真的不想用 React 来嵌入它。

【问题讨论】:

    标签: spring spring-boot spring-mvc


    【解决方案1】:

    控制器:

    @Controller
    public class MyController {
    
        @GetMapping("/json")
        @ResponseBody
        public MyResource idexJson() {
            ...
            return res;
        }
    
        @GetMapping("/jsp")
        public String input(final Model model) {
            ...
            model.addAttribute(res);
            return "index";
        }
    
    }
    

    此外,您可能还需要额外的配置。例如:

    属性:

    spring.mvc.view.prefix= /WEB-INF/view/
    spring.mvc.view.suffix= .jsp
    

    依赖:

        <dependency>
          <groupId>org.apache.tomcat.embed</groupId>
          <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
    

    Example code

    【讨论】:

    • 是的,我明白了,但是 /jsp 中的 res 是如何提供的?
    • that sample code 会不会有帮助?/参考:1.3.4. Model
    • 在您发送的 Github 链接中见,/jsp 正在调用 createResource(),这就是它获取 res 数据的方式。它没有调用 /json 路由来获取 json 数据。我希望发生这种情况
    【解决方案2】:

    是的,您可以使用 @RestController 注释您的类,以告诉 Spring 它的方法将返回 HTTP 响应正文(例如 JSON 格式)

    你可以用@Controller注解另一个类,告诉Spring它的方法会返回一个视图名(比如JSP文件名)

    【讨论】:

    • 我将如何调用 Rest api 在我的 jsps 中显示数据?
    • 你的 Controller 的方法必须调用 RestController 的方法,并使用它的 addAttribute 方法将结果放入 org.springframework.ui.Model。请注意,这是一个非常奇怪的设计
    • 我将如何从我的 Controller 方法中调用 restController 方法?
    猜你喜欢
    • 1970-01-01
    • 2018-07-21
    • 1970-01-01
    • 2013-11-14
    • 1970-01-01
    • 2018-09-28
    • 2020-06-18
    • 1970-01-01
    • 2017-10-25
    相关资源
    最近更新 更多