简体   繁体   English

带有Spring Boot的RESTful Web服务

[英]A RESTful Web Service with Spring Boot

I have been working on my first Web Service application, and I need to earse/replace ModelAndView . 我一直在开发我的第一个Web Service应用程序,并且需要学习/替换ModelAndView

I want to keep the webpages separately from the application files, and suggestions? 我想将网页与应用程序文件分开保存,并且有何建议?

class ModelAndView ModelAndView类

Holder for both Model and View in the web MVC framework. Web MVC框架中的Model和View的持有人。 Note that these are entirely distinct. 请注意,这些完全不同。 This class merely holds both to make it possible for a controller to return both model and view in a single return value. 此类仅持有两者,以使控制器可以在单个返回值中返回模型和视图。

Represents a model and view returned by a handler, to be resolved by a DispatcherPortlet. 表示要由DispatcherPortlet解析的处理程序返回的模型和视图。 The view can take the form of a String view name which will need to be resolved by a ViewResolver object; 该视图可以采用String视图名称的形式,该名称需要由ViewResolver对象解析; alternatively a view object can be specified directly. 或者,可以直接指定视图对象。 The model is a Map, allowing the use of multiple objects keyed by name. 该模型是一个Map,允许使用按名称键控的多个对象。

1) First of all remove below code from controller layer: 1)首先从控制器层删除以下代码:

 @Bean
    public MultipartResolver multipartResolver() {
         CommonsMultipartResolver multipartResolver = new                    CommonsMultipartResolver();
        multipartResolver.setMaxUploadSize(10240000);
        return multipartResolver;
    }

Make a java file say ProductConfig annotate it with @Config and include all configuration method like multipartResolver() in it. 使一个Java文件说出ProductConfig,并用@Config对其进行注释,并在其中包含所有配置方法,例如multipartResolver()。

2) Coming to your question,you can sent the result as JSON response instead of using ModelAndView example: 2)谈到您的问题,您可以将结果作为JSON响应发送,而无需使用ModelAndView示例:

@RequestMapping("getProductById/{productId}")
    public @ResponseBody getProductById(@PathVariable(value = "productId") String productId) {
        Product product = productService.getProductById(productId);
        return product;
}

Now this API with return a json response. 现在,此API返回一个json响应。

On the front end ,you can use some framework like angular js. 在前端,您可以使用诸如angular js之类的框架。 Angular provides features such as routing which can help you to navigate. Angular提供了诸如路由之类的功能,可以帮助您导航。 Ideally all frontend navigation should not be handled at java layer 理想情况下,不应在Java层处理所有前端导航

If your plan is to run a separate server for the front end then make sure you enable CORS . 如果您打算为前端运行单独的服务器,请确保启用CORS

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:9000");
        }
    };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM