我正在使用带有@PreAuthorize 的自定义访问检查器:
@RestController
@RequestMapping("/users")
public class Users {
@PreAuthorize("@customAccessChecker.hasAccessToMethod('USERS', 'GET')")
@RequestMapping(method = RequestMethod.GET)
User getUsers() {
...
}
@PreAuthorize("@customAccessChecker.hasAccessToMethod('USERS', 'POST')")
@RequestMapping(method = RequestMethod.POST)
User addUser() {
...
}
}
Run Code Online (Sandbox Code Playgroud)
我想去掉@PreAuthorize 注释中的字符串“GET”和“POST”。是否可以将@RequestMapping 中使用的 RequestMethod 以某种方式作为 hasAccessToMethod 的变量输入?
java spring spring-annotations spring-restcontroller request-mapping
我正在尝试使用 Spring Data JPA 实现双向一对多关系。我已经创建了用于保存和获取数据的测试用例,并且映射中没有问题,并且数据都保存在两个表中。但是当我尝试通过点击 Post 请求来创建数据时,外键没有被保存。客户和电话之间的映射是双向的一对多。
一对多1应用程序
package com.jwt.onetomany;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class OneToMany1Application {
public static void main(String[] args) {
SpringApplication.run(OneToMany1Application.class, args);
}
}
Run Code Online (Sandbox Code Playgroud)
演示控制器
package com.jwt.onetomany.controller;
import java.net.URI;
import java.util.List;
import org.apache.tomcat.jni.Poll;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import com.jwt.onetomany.entity.Customer;
import com.jwt.onetomany.repo.CustomerRepository;
@RestController
public class DemoController {
@Autowired
CustomerRepository customerRepository;
@GetMapping("/getall")
ResponseEntity<List<Customer>> getAllCustomers() {
Iterable<Customer> findAll = customerRepository.findAll();
List<Customer> customers …Run Code Online (Sandbox Code Playgroud) rest hibernate spring-data-jpa spring-restcontroller spring-rest
考虑以下代码:
@RestController
@RequestMapping("/timeout")
public class TestController {
@Autowired
private TestService service;
@GetMapping("/max10secs")
public String max10secs() {
//In some cases it can take more than 10 seconds
return service.call();
}
}
@Service
public class TestService {
public String call() {
//some business logic here
return response;
}
}
Run Code Online (Sandbox Code Playgroud)
我想要完成的是,如果call来自的方法TestService需要超过 10 秒,我想取消它并使用HttpStatus.REQUEST_TIMEOUT代码生成响应。
spring request-timed-out spring-boot spring-restcontroller spring-async
我正在使用 Spring boot 和 Rest Controller。我有一个@PostMappingid@RequestBody类型为 的对象UUID。当我尝试测试来自邮递员的发布请求时,出现以下错误。
JSON 解析错误:
无法从字符串“4be4bd08cfdf407484f6a04131790949”反序列化类型的值
java.util.UUID:UUID 必须由标准 36 字符表示形式表示;嵌套异常是 com.fasterxml.jackson.databind.exc.InvalidFormatException:无法从字符串“4be4bd08cfdf407484f6a04131790949”反序列化类型的值java.util.UUID:UUID 必须由标准 36 字符表示形式表示
我在一些文章中读到,讨论了 invalidFormatException 但具有不同的数据类型,需要编写某种适配器。我该如何解决 UUID 的问题?预先感谢您的意见。
@PostMapping(value = "/save_order")
@ResponseStatus(HttpStatus.CREATED)
public void postOrder(@RequestBody Order order) {
...
public class Order {
@Id
private UUID dstId;
....
Run Code Online (Sandbox Code Playgroud) 我开发了Spring Boot + Spring Data Jpa Rest示例。我开发了下面的代码并给了我下面的错误,即使我无法启动 Swagger 给我错误的代码。
{
"timestamp": "2019-07-22T15:29:04.487+0000",
"status": 500,
"error": "Internal Server Error",
"message": "Could not write JSON: Infinite recursion (StackOverflowError); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: java.util.ArrayList[0]->com.example.demo.entity.Employee[\"department\"]->com.example.demo.entity.Department$HibernateProxy$muKgohop[\"employees\"])",
"path": "/employees/findEmployees/john"
}
Run Code Online (Sandbox Code Playgroud)
RangeError: 在 Mt.map (immutable.js:4401) at e (utils.js:64) at immutable.js:3016 at immutable.js:2699 at ft.__iterate (immutable.js:2206) 超出最大调用堆栈大小在 Mt.__iterate (immutable.js:2698) at r.Lt.r.__iterateUncached (immutable.js:3015) at le (immutable.js:604) at rJ__iterate (immutable.js:274) at r.forEach (immutable .js:4381)
日志:我可以看到很多像下面这样的日志进入递归。
2019-07-22 20:59:04.484 WARN 21016 --- [io-8080-exec-10] …Run Code Online (Sandbox Code Playgroud) Spring Boot 提供了 ResponseEntity 来表示 REST API 的 HTTP 响应,包括 headers、body 和 status。
我的 RestController 包含 getTodoById 方法,如下所示-
@GetMapping("/todo/{id}")
public Todo getTodoById(@PathVariable String id) {
int todoId = Integer.parseInt(id);
Todo todoItem = todoRepository.findById(todoId);
ResponseEntity.ok(todoItem);
}
Run Code Online (Sandbox Code Playgroud)
它在 api hit(api/v1/todo/13) 上给出以下 api 响应。
{
"id": 13,
"title": "title13",
"status": "not started"
}
Run Code Online (Sandbox Code Playgroud)
应用程序中的所有 api 都需要有一个通用的自定义响应结构,如下所示:
{
"status": "success",
"data": {
"id": 13,
"title": "title13",
"status": "not started"
},
"error": null,
"statusCode": 200
}
{
"status": "failure",
"data": {},
"error": "bad request",
"statusCode": …Run Code Online (Sandbox Code Playgroud) 我正在使用Spring 4.x并且我有以下RestController方法,它应该返回所有航班的列表
@RequestMapping(produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}, method = RequestMethod.GET)
public FlightWrapper returnAllFlights() {
List<FlightDto> flights = data.findAll();
return new FlightWrapper(flights);
}
Run Code Online (Sandbox Code Playgroud)
FlightWrapper类看起来像这样(rootElement = flight s element = flight):
@XmlRootElement(name = "flights")
public class FlightWrapper {
private List<FlightDto> flights;
public FlightWrapper() {}
public FlightWrapper(List<FlightDto> flights) {
this.flights = flights;
}
@XmlElement(name = "flight")
public List<FlightDto> getFlights() {
return flights;
}
public void setFlights(List<FlightDto> flights) {
this.flights = flights;
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,当我调用returnAllFlights()时,它将以这种格式返回xml:
<FlightWrapper>
<flights>
<flights>
....
</flights>
<flights>
....
</flights>
</flights>
</FlightWrapper> …Run Code Online (Sandbox Code Playgroud) 我正在编写一个Rest服务(HTTP Get端点),在下面的uri中执行以下操作
http://localhost:8080/customers/{customer_id}
Run Code Online (Sandbox Code Playgroud)
码:
@RequestMapping(method = RequestMethod.GET, value = "customers/{customer_id}")
public List<Customer> getCustomers(
@PathVariable(name = "customer_id", required = false) final String customerId) {
LOGGER.debug("customer_id {} received for getCustomers request", customerId);
}
Run Code Online (Sandbox Code Playgroud)
但是,使用上面的代码,第二种情况下,控件流向getCustomers()。
注意:我使用的是Java8和spring-web 4.3.10版本
非常感谢对此的任何帮助。
我想从Spring Boot控制器读取POST数据.
我已经尝试了这里给出的所有解决方案:HttpServletRequest获取JSON POST数据,但我仍然无法读取Spring Boot servlet中的post数据.
我的代码在这里:
package com.testmockmvc.testrequest.controller;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@Controller
public class TestRequestController {
@RequestMapping(path = "/testrequest")
@ResponseBody
public String testGetRequest(HttpServletRequest request) throws IOException {
final byte[] requestContent;
requestContent = IOUtils.toByteArray(request.getReader());
return new String(requestContent, StandardCharsets.UTF_8);
}
}
Run Code Online (Sandbox Code Playgroud)
我曾尝试使用收集器作为替代方案,但这也不起作用.我究竟做错了什么?
我将已经存在的应用程序从Spring Boot 1.3更新到2.0.1.该应用程序使用Actuator并公开REST风格的API.
在Boot 1.3中,无需身份验证即可使用API,并且执行器端点配置为受密码保护:
security.user.name=foo
security.user.password=bar
security-user.role=ADMIN
Run Code Online (Sandbox Code Playgroud)
我更新了这个,如配置更改日志中记录的那样,并将条目重命名为security.user.nameto spring.security.user.name和like .
但是当我尝试使用curl我的API时,我被拒绝了,因为我没有提供凭据:

在Spring博客中,我找到了一个可能的解决方案,如何在详细级别配置Spring Security:
http
.authorizeRequests()
// 1
.requestMatchers(EndpointRequest.to("status", "info"))
.permitAll()
// 2
.requestMatchers(EndpointRequest.toAnyEndpoint())
.hasRole("ACTUATOR")
// 3
.requestMatchers(StaticResourceRequest.toCommonLocations())
.permitAll()
// 4
.antMatchers("/**")
.hasRole("USER")
.and()
...
Run Code Online (Sandbox Code Playgroud)
但这比我需要的更细粒度,我正在寻找一个application.properties基础的解决方案.
有没有办法解决这个没有额外的代码?
spring-security spring-boot spring-restcontroller spring-boot-actuator
spring ×4
spring-boot ×4
java ×3
rest ×3
spring-rest ×2
hibernate ×1
httpresponse ×1
jackson ×1
java-8 ×1
spring-async ×1
spring-mvc ×1
uuid ×1