I have a spring mvc controller which is serving web service requests with multiple request parameters. All the parameters are marked required = false. Still if in the request a parameter is not available,
@RequestMapping(value = "/service/deployNew", method = RequestMethod.POST)
@ResponseBody public ResponseEntity<DeploymentId> deploy(HttpServletRequest request, HttpServletResponse response, @RequestParam(required = false, value = "abc") String abc, @RequestParam(required = false, value = "xyz") String xyz, @RequestParam(required = false, value = "uvw") String uvw,) throws Exception;
Run Code Online (Sandbox Code Playgroud)
I see the error
required string …Run Code Online (Sandbox Code Playgroud) 当 REST API 映射到 Java 对象时,它采用输入内容类型:application/x-www-form-urlencoded,例如
public class MyRequest {
@JsonProperty("my_name")
private String myName;
@JsonProperty("my_phone")
private String myPhone;
//Getters and Setters of myName and myPhone.
}
Run Code Online (Sandbox Code Playgroud)
在表单输入请求中,我设置了 my_name 和 my_phone 的值,但 MyRequest 对象的 myName 和 myPhone 为 null。
我正在使用 Jackson-annotations 2.3 jar
有什么建议可能有什么问题吗?
我在 Spring-RS 中得到了一些 REST 端点,它使用实体 id 作为路径变量。大多数时候,该方法所做的第一件事是使用 id 检索实体。有没有办法自动将 id 映射到实体,仅将实体作为方法参数?
现在的情况 :
@RequestMapping(path="/{entityId})
public void method(@PathVariable String entityId) {
Entity entity = entityRepository.findOne(entityId);
//Do some work
}
Run Code Online (Sandbox Code Playgroud)
我想要什么:
@RequestMapping(path="/{entityId})
public void method(@PathVariable Entity entityId) {
//Do some work
}
Run Code Online (Sandbox Code Playgroud) 我在使用由 Spring Boot 1.5 组成的 REST 服务时遇到问题。我正在开发一个充当代理的 REST 服务,将请求转发到另一个公开相同 API 的 REST 服务。
@RestController
@RequestMapping("/user")
public class ProxyUserController {
// Some initialization code
@PostMapping
public ResponseEntity<?> add(@Valid @RequestBody User user) {
return restTemplate.postForEntity(userUrl, user, String.class);
}
@Configuration
public static class RestConfiguration {
@Bean
public RestTemplate restTemplate(UserErrorHandler errorHandler) {
return new RestTemplateBuilder().errorHandler(errorHandler).build();
}
}
@Component
public static class UserErrorHandler implements ResponseErrorHandler {
@Override
public boolean hasError(ClientHttpResponse response) {
return false;
}
@Override
public void handleError(ClientHttpResponse response) {
// Empty body
} …Run Code Online (Sandbox Code Playgroud) 我有 Spring Rest API 的端点:
@PostMapping(value = "/v1/", consumes = { MediaType.APPLICATION_XML_VALUE,
MediaType.APPLICATION_JSON_VALUE }, produces = { MediaType.APPLICATION_XML_VALUE,
MediaType.APPLICATION_JSON_VALUE })
public PaymentResponse handleMessage(@RequestBody PaymentTransaction transaction, HttpServletRequest request) throws Exception {
// get here plain XML
}
Run Code Online (Sandbox Code Playgroud)
XML 模型。
@XmlRootElement(name = "payment_transaction")
@XmlAccessorType(XmlAccessType.FIELD)
public class PaymentTransaction {
public enum Response {
failed_response, successful_response
}
@XmlElement(name = "transaction_type")
public String transactionType;
.........
}
Run Code Online (Sandbox Code Playgroud)
如何获取纯 XML 文本格式的 XML 请求?
我也尝试过使用 Spring 拦截器:我尝试了这段代码:
@SpringBootApplication
@EntityScan("org.plugin.entity")
public class Application extends SpringBootServletInitializer implements WebMvcConfigurer {
@Override …Run Code Online (Sandbox Code Playgroud) 我有一个用于CRUD的RestController注释如下:
@RestController
@RequestMapping("/rest/v1/area")
public class AreaController
Run Code Online (Sandbox Code Playgroud)
我的方法注释如下:
@RequestMapping(value = "/{uuid}", method = RequestMethod.PUT)
public ResponseEntity<Area> save(@Valid @RequestBody Area area) {
Run Code Online (Sandbox Code Playgroud)
有没有办法使用方法的值来获得绝对路径?我想添加一个上传文件的方法,并且不想为此创建一个新的Controller.我想要一个像这样的方法:
@RequestMapping(value = "/rest/v1/area-upload", method = RequestMethod.PUT
public String handleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
Run Code Online (Sandbox Code Playgroud)
谢谢!
我已经为我的REST API配置了Spring Security(使用HeaderHttpSessionStrategy).
我的'WebSecurityConfigurerAdapter'实现如下所示.
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/user/**").authenticated()
.antMatchers("/**").permitAll()
.and()
.requestCache()
.requestCache(new NullRequestCache())
.and()
.httpBasic()
;
}
Run Code Online (Sandbox Code Playgroud)
现在,我如何配置'HttpSecurity'对象,以便只有特定端点才能进行基本身份验证.
例如:
/ user/login:只能在此端点进行基本身份验证.在进行成功身份验证后,将返回x-auth-token标头.
/ user/create:客户端不应该能够在此端点上进行身份验证.只能返回401.Can只能使用/ user/login端口创建的"x-auth-token"访问.
java spring spring-mvc spring-security spring-restcontroller
对端点的请求失败,并显示以下错误:
400错误请求org.springframework.http.converter.HttpMessageNotReadableException:缺少必需的请求正文
@GetMapping
public List<SomeObject> list(@RequestParam(required = false) String parameter, @RequestBody String body, @RequestHeader("Authorization") String token) {
.....
}
Run Code Online (Sandbox Code Playgroud)
如果@GetMapping会改变@PostMapping一切就像魅力一样.有什么想法到底是怎么回事?
注意: Swagger用于请求发送,因此错误不太可能在Curl中
更新:
所以,它看起来像春天不支持@RequestBody 的@GetMapping.我还是想不通为什么?@DeleteMapping与@RequestBody工作正常,并根据HTTP/1.1 GET请求可能包含体- stackoverflow.com/questions/978061/http-get-with-request-body
IMO看起来有点不一致允许身体进入DELETE但禁止进入GET
无法将json字符串映射到java对象,得到错误JSON解析错误:无法构造com.test.CPInput的实例$ Evc $ Uni
错误:
{
"timestamp": 1502270576300,
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.http.converter.HttpMessageNotReadableException",
"message": "**JSON parse error: Can not construct instance of com.test.CPInput$Evc$Uni: can only instantiate non-static inner class by using default, no-argument constructor; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of com.test.CPInput$Evc$Uni: can only instantiate non-static inner class by using default, no-argument constructor at [Source: java.io.PushbackInputStream@edc246; line: 20, column: 9] (through reference chain: com.test.CPInput["evc"]->com.test.CPInput$Evc["uni"]->java.util.ArrayList[0]**)",
"path": "/demo/addCustomer"
}
Run Code Online (Sandbox Code Playgroud)
JSON
{
"customerId": "abcdef",
"customerSegment": {
"customerType": "customer type", …Run Code Online (Sandbox Code Playgroud) 我有一个带有@Controllers和@RestControllers 的Spring MVC应用程序。我当时在想:当我遇到异常时@Controller,它将由我处理;@ControllerAdvice当我遇到异常时@RestController,将由我处理@RestControllerAdvice...但是现在,我认为这不是事情的工作方式,因为我@ControllerAdvice正在捕获所有内容,甚至是由@RestController... 引发的任何异常,我不知道是否应该发生这种情况。这是我的代码:
@ControllerAdvice
public class ExceptionHandlerController {
private final String DEFAULT_ERROR_VIEW = "error/default";
@ExceptionHandler(Exception.class)
public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e)
{
ModelAndView mav = new ModelAndView();
mav.addObject("exception", e);
mav.addObject("danger", e.getMessage());
mav.addObject("url", req.getRequestURL());
mav.setViewName(DEFAULT_ERROR_VIEW);
return mav;
}
}
@RestControllerAdvice
public class ExceptionHandlerRestController {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
return new ResponseEntity<>(" test "+e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Run Code Online (Sandbox Code Playgroud) java ×8
spring ×6
rest ×2
spring-boot ×2
spring-mvc ×2
spring-rest ×2
controller ×1
http ×1
jackson ×1
json ×1
post ×1
swagger ×1