标签: spring-restcontroller

Spring @RestController 获取请求内容类型以响应 json 或 html

如何获取请求 Content-Type 值?我们需要它来打印 json 响应或 Html 响应。我的代码是这样的:

 @RestController
public class GestorController {
    @RequestMapping(value="/gestores", method = RequestMethod.GET)  
    public Object gestoresHtml(@RequestParam(value="name", required=false, defaultValue="sh14") String name) throws Exception {
        String json = "prueba json";

        String contentType = ?????

        if(contentType.equals("application/json")){
            return json;
        }else{
            ModelAndView mav = new ModelAndView();
            mav.setViewName("gestores");
            mav.addObject("name", name);
            return mav;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢大家。

spring-mvc spring-restcontroller

2
推荐指数
1
解决办法
9970
查看次数

无法使用 spring 框架在请求映射中获取不同的内容类型?

这是我的控制器类:

@Controller
@RequestMapping("/actuator")
public class HealthController {

    @RequestMapping(value = "/metrics", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON)
    @ResponseBody
    public HealthModel getDump() throws JsonProcessingException {
        return new HealthModel();
        //return mapper.writeValueAsString(metrics.invoke());
    }

    @RequestMapping(value = "/metrics", method = RequestMethod.GET, produces = MediaType.TEXT_PLAIN)
    @ResponseBody
    public String getHealth() {
        return "HEALTHY";
    }
}
Run Code Online (Sandbox Code Playgroud)

模型

public class HealthModel {

    @JsonProperty
    private String status;
    @JsonProperty
    private int id;

    public HealthModel(){
        this.status="WARN";
        this.id=2;
    }

}
Run Code Online (Sandbox Code Playgroud)

注意我已经映射/metrics到返回jsonplain-text取决于Accept Header请求中的

当我提出请求时

curl -v -H …

spring spring-mvc spring-restcontroller spring-rest

2
推荐指数
1
解决办法
1万
查看次数

Spring - RestController 注释不捕获请求

我不明白为什么如果我使用 RestController 注释将类声明为服务,如下所示:

@RestController("/registration")
public class RegistrationService {

    @RequestMapping(value="/", 
                produces="application/json")
    public String initializeSession(Model model){

        return "{\"success\":1}";
    }
}
Run Code Online (Sandbox Code Playgroud)

当我做一个请求时

http://localhost:8080/SpringRest/registration/

我得到 404 状态并在控制台中:

No mapping found for HTTP request with URI [/SpringRest/registration/] in DispatcherServlet with name 'dispatcherServlet'
Run Code Online (Sandbox Code Playgroud)

一切正常,如果我改变@RestController("/registration")

@Controller @RequestMapping("/registration")

并在方法声明上方添加@ResponseBody。

这是我的配置:

网页.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns="http://java.sun.com/xml/ns/javaee"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
     id="WebApp_ID" version="2.5">

<display-name>SpringRest</display-name>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/application-config.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>


<!--
    - Servlet that dispatches request to registered handlers (Controller implementations).
-->
<servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name> …
Run Code Online (Sandbox Code Playgroud)

java spring annotations spring-restcontroller

2
推荐指数
2
解决办法
3315
查看次数

使用 Spring RestTemplate 时未设置“X-Appengine-Inbound-Appid”标头

我有两个在 Google App Engine 上运行的服务(MS1 和 MS2)。MS1 部署在标准环境中,MS2 部署在灵活环境中。我正在从标准环境调用 API 到灵活环境。我想确保 MS2 只接受来自 MS1 的请求。所以,我决定使用App Engine 的这个功能。我正在MS1 中设置X-Appengine-Inbound-Appid标头和setInstanceFollowRedirectsto false,但看起来 App Engine 正在删除此标头。我在 MS2 中找不到这个标题。

HttpHeaders headers = new HttpHeaders();
headers.add("X-Appengine-Inbound-Appid", ApiProxy.getCurrentEnvironment().getAppId());
HttpEntity<MergePdfsResource> entity = new HttpEntity<MergePdfsResource>(mergePdfsResource, headers);

restTemplate.setRequestFactory(new SimpleClientHttpRequestFactory() {
        protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
        super.prepareConnection(connection, httpMethod);
        connection.setInstanceFollowRedirects(false);
    }
});

ResponseEntity<SomeClass> response = restTemplate.postForEntity(apiUrl, entity, SomeClass.class);
Run Code Online (Sandbox Code Playgroud)

google-app-engine spring spring-restcontroller spring-rest google-flexible

2
推荐指数
1
解决办法
725
查看次数

Spring - 是否可以在 post 方法的请求映射中提供相同的 url?

是否可以在两种不同的 post 方法的请求映射中使用相同的 url,只有请求正文不同。

java spring spring-restcontroller

2
推荐指数
2
解决办法
9350
查看次数

如何在 Spring Boot RestController 中映射动态查询参数

是否可以使用 Spring Boot 使用动态名称映射查询参数?我想映射如下参数:

/products?filter[name]=foo
/products?filter[length]=10
/products?filter[width]=5
Run Code Online (Sandbox Code Playgroud)

我可以做这样的事情,但这需要知道每个可能的过滤器,我希望它是动态的:

@RestController
public class ProductsController {
    @GetMapping("/products")
    public String products(
            @RequestParam(name = "filter[name]") String name,
            @RequestParam(name = "filter[length]") String length,
            @RequestParam(name = "filter[width]") String width
    ) {
        //
    }
}
Run Code Online (Sandbox Code Playgroud)

如果可能,我正在寻找允许用户定义任意数量可能的过滤器值的东西,以及那些HashMap被 Spring Boot映射为 a的东西。

@RestController
public class ProductsController {
    @GetMapping("/products")
    public String products(
            @RequestParam(name = "filter[*]") HashMap<String, String> filters
    ) {
        filters.get("name");
        filters.get("length");
        filters.get("width");
    }
}
Run Code Online (Sandbox Code Playgroud)

发布在此问题上的答案建议使用@RequestParam Map<String, String> parameters,但是这将捕获所有查询参数,而不仅仅是那些匹配的filter[*].

java query-parameters spring-boot spring-restcontroller

2
推荐指数
1
解决办法
1万
查看次数

Spring MVC RequestMapping 不适用于 RestController

我想要一个带有基本映射“/user”的 RestController 类(因此不同的函数将具有“/user/add”、“/user/remove”等路径或使用 POST/GET 等)

这是我不明白并且无法开始工作的部分:

@RestController
public class UserController {

  @GetMapping("/user")
  public Response login(Principal principal){
    //some output
  }
}
Run Code Online (Sandbox Code Playgroud)

这种情况下的预期行为是我可以在“/user”下访问我的输出。这按预期工作。现在,如果我将其修改为以下内容(因为此控制器中的所有功能都应该有一个以“/user”开头的路径,这会更清晰)

@RestController
@RequestMapping("/user")
public class UserController {

  @GetMapping("/")
  public Response login(Principal principal){
    //some output
  }
}
Run Code Online (Sandbox Code Playgroud)

我得到一个 404-Error 页面并且无法再访问“/user”我发现的所有示例都使用相同的语法(或者有时@RequestMapping(path="/user") 但它不起作用)并且我不知道为什么它不起作用。有人能告诉我我的错误在哪里吗?

java spring-mvc spring-restcontroller request-mapping

2
推荐指数
1
解决办法
1322
查看次数

如何修复 spring 框架上的“白标错误页面” - GET 请求不起作用

我正在尝试使用 spring boot 制作“Hello World”控制器,但 GET 请求不起作用。我能做些什么来解决这个问题?

我在https://start.spring.io/和我选择 web 的依赖项中使用了 spring 初始值设定项

我尝试使用不同的注释,如@GetMapping

package com.example.hello;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @RequestMapping("/")
    public String helloWorld() {
        return "Hello World";
    }
}

Run Code Online (Sandbox Code Playgroud)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies> …
Run Code Online (Sandbox Code Playgroud)

java get spring-mvc spring-boot spring-restcontroller

2
推荐指数
1
解决办法
6224
查看次数

Angular 8 NgFor 仅支持绑定到 Iterables,例如 Arrays error 和 Access Control Allow origin

我有一个模型:

export class Employe {    
    constructor(public id?: any,
        public nom?: String,
        public prenom?: String,
        public cin?: String){}    
}
Run Code Online (Sandbox Code Playgroud)

员工.component.ts

ngOnInit(){
    this.loadEmployes();
}    

 pageEmployes:any={};

  loadEmployes():Observable<any>{    
     this.http.get("http://localhost:8080/api/employe").subscribe(
      data=>{
        console.log(data);
        this.pageEmployes = data;

      }, err=>{
        console.log(err);
      }
    );
    return this.pageEmployes;
  }
Run Code Online (Sandbox Code Playgroud)

员工.component.html

 <tr *ngFor="let item of pageEmployes">         
      <td>{{item.nom}}</td>
      <td>{{item.prenom}}</td>    
    </tr>
Run Code Online (Sandbox Code Playgroud)

协作控制器.java

@RestController

@RequestMapping("/api/employe")

@CrossOrigin("*")

public class CollaborateurController {

    @Autowired
    private CollaborateurRepository collaborateurRepository;

    @RequestMapping(value="", method=RequestMethod.GET)
    public List<Collaborateur> getEmp() {
        return (List<Collaborateur>) collaborateurRepository.findAll();
    }
Run Code Online (Sandbox Code Playgroud)

这引发了我的错误:

ERROR 错误:找不到类型为“object”的不同支持对象“[object Object]”。NgFor 仅支持绑定到可迭代对象,例如数组。

从源“ http://localhost:4200 ”访问“ http://localhost:8080/api/employe ”的XMLHttpRequest已被 CORS …

spring-restcontroller angular cross-origin-read-blocking

2
推荐指数
1
解决办法
2万
查看次数

如何在 Spring Boot 中读取未映射到 @RequestBody 模型对象的其他 JSON 属性

我有一个看起来像这样的 RestController

@RequestMapping(value = "/post", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> test(@RequestBody User user) {

    System.out.println(user);
    return ResponseEntity.ok(user);
}     
Run Code Online (Sandbox Code Playgroud)

和看起来像这样的用户模型

class User {

    @NotBlank
    private String name;
    private String city;
    private String state;

}
Run Code Online (Sandbox Code Playgroud)

我有一个要求,用户可以在输入 JSON 中传递一些额外的附加属性,就像这样

{
"name": "abc",
"city": "xyz",
"state": "pqr",
"zip":"765234",
"country": "india"
}
Run Code Online (Sandbox Code Playgroud)

'zip' 和 'country' 是输入 JSON 中的附加属性。

在 Spring Boot 中有什么方法可以在 Request Body 中获得这些附加属性吗?

我知道一种方法,我可以使用“Map”或“JsonNode”或“HttpEntity”作为 Requestbody 参数。但是我不想使用这些类,因为我会丢失可以在“用户”模型对象中使用的 javax.validation。

java spring-boot spring-restcontroller

2
推荐指数
1
解决办法
320
查看次数