我想返回一个简单的纯文本字符串,如下所示:
@RestController
@RequestMapping("/test")
public class TestController {
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/my", method = RequestMethod.GET, produces="text/plain")
public String test() {
return "OK";
}
Run Code Online (Sandbox Code Playgroud)
问题:我也有一个全局的ContentNegotiation过滤器,如下所示:
@Configuration
public class ContentNegotiationAdapter extends WebMvcConfigurerAdapter {
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(false)
.favorParameter(true)
.ignoreAcceptHeader(true)
.useJaf(false)
.defaultContentType(MediaType.APPLICATION_XML);
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
super.configureMessageConverters(converters);
}
}
Run Code Online (Sandbox Code Playgroud)
结果:每当我访问spring控制器时,都会收到错误消息:
Could not find acceptable representation
问题:即使在内容协商中仅配置了XML(我必须保留),如何强制控制器返回纯文本?
我有一个 spring REST web 服务 URL http://localhost:8080/MySpringRestService/callSome
如何限制对 Web 服务的并发访问。
我的要求是一次只允许一个对 Web 服务的请求。
任何形式的帮助将不胜感激。
我正在尝试将protobuf参数传递给REST端点,但我得到了
org.springframework.web.client.HttpServerErrorException:500 null
每次我试试.我现在拥有的是这样的:
@RestController
public class TestTaskEndpoint {
@PostMapping(value = "/testTask", consumes = "application/x-protobuf", produces = "application/x-protobuf")
TestTaskComplete processTestTask(TestTask testTask) {
// TestTask is a generated protobuf class
return generateResult(testTask);
}
}
@Configuration
public class AppConfiguration {
@Bean
ProtobufHttpMessageConverter protobufHttpMessageConverter() {
return new ProtobufHttpMessageConverter();
}
}
@SpringBootApplication
public class JavaConnectorApplication {
public static void main(String[] args) {
SpringApplication.run(JavaConnectorApplication.class, args);
}
}
Run Code Online (Sandbox Code Playgroud)
我的测试看起来像这样:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@WebAppConfiguration
public class JavaConnectorApplicationTest {
@Configuration
public static class RestClientConfiguration {
@Bean
RestTemplate restTemplate(ProtobufHttpMessageConverter hmc) …Run Code Online (Sandbox Code Playgroud) 我正在使用MongoRepository为MongoDB数据库创建Rest API.我想创建一个使用"RequestMethod.PATCH"的端点并实现"PATCH"功能:使用@RequestBody中提供的字段进行增量更新.
通过在我的Repository类上使用"@RepositoryRestResource"注释,我想要的功能已存在于"Spring Data Rest"中,如此处所述https://spring.io/guides/gs/accessing-data-rest/
但我不想像那样公开我的Repository类.我喜欢经典的Controller-> Service-> Repository lineage.我的控制器看起来像这样:
@RestController
public class ActivitiesController {
@Autowired
ActivitiesService activitiesService;
@RequestMapping(value="activities", method=RequestMethod.PATCH)
public ActivityModel updateActivity(
@RequestBody ActivityModel activityModel
){
//Input ActivityModel will only have subset of fields that have been changed, aka the delta
return activitiesService.update(activityModel);
}
@RequestMapping(value="activities", method=RequestMethod.PUT)
public ActivityModel updateActivity(
@RequestBody ActivityModel activityModel
){
//Input ActivityModel will have all fields populated
return activitiesService.save(activityModel);
}
}
Run Code Online (Sandbox Code Playgroud)
我的存储库在这里:
@Repository
public interface ActivitiesRepo extends MongoRepository<ActivityModel, String> {
//out of the box implementation
} …Run Code Online (Sandbox Code Playgroud) 我在对聚合管道的结果进行分页时遇到了一些麻烦。在查看了In spring data mongodb 如何实现分页进行聚合后,我想出了一个感觉像 hacky 的解决方案。我首先执行匹配查询,然后按我搜索的字段分组,并对结果进行计数,将值映射到一个私有类:
private long getCount(String propertyName, String propertyValue) {
MatchOperation matchOperation = match(
Criteria.where(propertyName).is(propertyValue)
);
GroupOperation groupOperation = group(propertyName).count().as("count");
Aggregation aggregation = newAggregation(matchOperation, groupOperation);
return mongoTemplate.aggregate(aggregation, Athlete.class, NumberOfResults.class)
.getMappedResults().get(0).getCount();
}
private class NumberOfResults {
private int count;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
Run Code Online (Sandbox Code Playgroud)
这样,我就能够为我返回的页面对象提供一个“总”值:
public Page<Athlete> findAllByName(String name, Pageable pageable) {
long total = getCount("team.name", name);
Aggregation aggregation = getAggregation("team.name", name, pageable); …Run Code Online (Sandbox Code Playgroud) spring-data-mongodb spring-boot spring-restcontroller spring-rest
我正在尝试对我的控制器和特定情况进行单元测试:我的服务返回一个 Mono.Empty,我抛出一个 NotFoundException 并且我不想确保我收到 404 异常
这是我的控制器:
@GetMapping(path = "/{id}")
public Mono<MyObject<JsonNode>> getFragmentById(@PathVariable(value = "id") String id) throws NotFoundException {
return this.myService.getObject(id, JsonNode.class).switchIfEmpty(Mono.error(new NotFoundException()));
}
Run Code Online (Sandbox Code Playgroud)
这是我的控制器建议:
@ControllerAdvice
public class RestResponseEntityExceptionHandler {
@ExceptionHandler(value = { NotFoundException.class })
protected ResponseEntity<String> handleNotFound(SaveActionException ex, WebRequest request) {
String bodyOfResponse = "This should be application specific";
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Resource not found");
}
}
Run Code Online (Sandbox Code Playgroud)
和我的测试:
@Before
public void setup() {
client = WebTestClient.bindToController(new MyController()).controllerAdvice(new RestResponseEntityExceptionHandler()).build();
}
@Test
public void assert_404() throws Exception {
when(myService.getobject("id", JsonNode.class)).thenReturn(Mono.empty());
WebTestClient.ResponseSpec response …Run Code Online (Sandbox Code Playgroud) 我正在编写一个 spring rest 方法来从数据库中获取详细信息并将其设置在响应 POJO 中,然后返回它。目前,当使用 POSTMAN 或 RC(如带有数据的可下载 CSV 文件)命中 URL 时,我需要以 CSV 格式而不是默认 json 格式生成此响应。我用谷歌搜索了很多网站,但我不确定一些逻辑。
目前我还没有为 CSV 转换编写任何代码。
@GetMapping("/batch/export" , produces="text/csv")
public ResponseEntity<ApplicationResponse> getBatchDetails(
HttpServletRequest request) {
ApplicationRequest appRequest = ApplicationServiceMapper.mapRequestFromHttpRequest(request);
ApplicationResponse response = appService.getDBDetails(appRequest);
return new ResponseEntity<>(response, HttpStatus.OK);
}
Run Code Online (Sandbox Code Playgroud)
这里的响应是服务以 pojo 格式返回所有数据的响应,如果我们不在注释中给出产品,那么默认情况下 spring 将返回响应 json。有人可以指导我吗?提前致谢。
我在我的弹簧控制器中使用验证器。如果@RequestParam需要没有问题,我可以用@NotBlank. 但是如果@RequestParam是可选的,我不能将它与 一起使用@NotBlank,因为这个参数是可选的,有时可以为空。我想验证@NotBlankString 是否不为空。有什么限制可以帮助我吗?
@RequestParam @NotBlank String name
Run Code Online (Sandbox Code Playgroud)
完美运行。我有问题,required=false
如果客户端不发送可选的描述参数,验证失败。
@PatchMapping("/role/{id}")
public ResponseEntity<?> updateRole(HttpServletRequest request, @PathVariable @Positive Integer id,
@RequestParam @NotBlank String name,
@RequestParam(required = false) @NotBlank String description)
Run Code Online (Sandbox Code Playgroud)
我想验证@NotBlank描述是否不是null。
`@RequestParam(required = false) @NotBlank String description`
Run Code Online (Sandbox Code Playgroud)
如果我这样使用,我会收到“输入验证失败!”。
tldr:有没有办法在不上网的情况下发出内部请求(使用方法的路径)?
——
为什么我需要它?我有一个接收许多事件的项目。谁将处理每个事件的决定由控制器做出。所以我有类似的东西:
@RestController
@RequestMapping("/events")
public class EventHandlerAPI {
@Autowired
private EventAHandler eventAhandler;
@Autowired
private EventBHandler eventBhandler;
@PostMapping("/a")
public void handleEventA(@RequestBody EventA event) {
eventAhandler.handle(id, event);
}
@PostMapping("/b")
public void handleEventB(@RequestBody EventB event) {
eventBhandler.handle(id, event);
}
}
Run Code Online (Sandbox Code Playgroud)
我们最近添加了通过队列服务接收事件的支持。它向我们发送有效载荷和事件类。我们的决定是让两个接口都工作(休息和排队)。避免代码重复的解决方案是让控制器选择哪个处理程序来处理事件。现在的代码类似于:
@Configuration
public class EventHandlerQueueConsumer {
@Autowired
private EventHandlerAPI eventHandlerAPI;
private Map<Class, EventHandler> eventHandlers;
@PostConstruct
public void init() {
/* start listen queue */
declareEventHandlers();
}
private void declareEventHandlers() {
eventHandlers = new HashMap<>();
eventHandlers.put(EventAHandler.class, (EventHandler<EventAHandler>) eventHandlerAPI::handleEventA);
eventHandlers.put(EventBHandler.class, (EventHandler<EventBHandler>) eventHandlerAPI::handleEventB);
} …Run Code Online (Sandbox Code Playgroud) 我无法将我的 JSON 从帖子的方法体转换为我的 POJO,@RequestBody在我的控制器类中。
我调试了错误,我看到某些字段被映射而其他字段没有。像这样(POJO):
name: null, typeOfPlan: null, Email: example@gmail.com, PhoneNum: 123456789, Website: test.org, Username: null, password: 1234,这很奇怪。
JSON:
{
"confirmPassword": "1234",
"email": "example@gmail.com",
"password": "1234",
"phoneNum": "123456789",
"name": "Hello world",
"typeOfPlan": "Test",
"userName": "user",
"website": "test.org"
}
Run Code Online (Sandbox Code Playgroud)
控制器
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SomeController {
@Autowired
private Service foo;
@CrossOrigin
@PostMapping(value = "/create")
private void createAccount(@RequestBody BigFoo bigFoo) {
foo.createAccount(bigFoo);
}
}
Run Code Online (Sandbox Code Playgroud)
从这里,我调用我的服务,然后调用 DAO 类。 …
java ×5
spring ×5
spring-boot ×4
csv ×1
json ×1
junit ×1
mapping ×1
mongodb ×1
plaintext ×1
spring-mvc ×1
spring-rest ×1
spring-test ×1
validation ×1