我需要在Spring控制器中返回图像.我在这个Spring MVC中尝试回答:如何在@ResponseBody中返回图像?但它不起作用
我的代码是这样的
@RequestMapping(value = "cabang/photo", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<byte[]> getPhoto() throws IOException {
File imgPath = new File("D:\\test.jpg");
byte[] image = Files.readAllBytes(imgPath.toPath());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_JPEG);
headers.setContentLength(image.length);
return new ResponseEntity<>(image, headers, HttpStatus.OK);
}
Run Code Online (Sandbox Code Playgroud)
但是当我在浏览器中访问它时,它没有显示任何内容(只是没有图片图标).但是如果我读取图像字节数组,它就不是空的.我的代码中是否有任何遗漏?
我只是在想,为休息服务创建PATH映射的最佳做法是什么.假设我们有以下路径:
/users POST
/users/1 PATCH, GET
/users/1/contacts GET, POST
/users/1/contacts/1 GET, PATCH
Run Code Online (Sandbox Code Playgroud)
问题是 - 创建控制器的最佳实践是什么.例如,我们有UserController,我们在技术上可以放置所有这些映射.或者 - 我们应该创建单独的控制器(UserController,ContactsController).如果我们把所有东西放在下面,请在下面的UserController中.
@RequestMapping("users")
@RestController
public class UserController {
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<Void> createUser() {}
@RequestMapping(method = RequestMethod.GET)
public User getUser() {}
@RequestMapping(value = "{id}/contacts", method = RequestMethod.GET)
public List<Contact> getContacts() {}
@RequestMapping(value = "{id}/contacts", method = RequestMethod.POST)
public ResponseEntity<Void> createContact() {}
.....
}
Run Code Online (Sandbox Code Playgroud)
如果我们创建单独的控制器,那么应该如何组织路径呢?可能这是一个愚蠢的问题,但如果有人可以分享经验,我会很高兴.
我无法直接获取JSONObject,此代码有效:
RestTemplate restTemplate = new RestTemplate();
String str = restTemplate.getForObject("http://127.0.0.1:8888/books", String.class);
JSONObject bookList = new JSONObject(str);
Run Code Online (Sandbox Code Playgroud)
但是这段代码没有:
JSONObject bookList = restTemplate.getForObject("http://127.0.0.1:8888/books", JSONObject.class);
Run Code Online (Sandbox Code Playgroud)
可能是什么问题呢?它没有给出错误,但最后我有一个空的JSONObject.
我的pom.xml:
<?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>
<groupId>com.example</groupId>
<artifactId>library-client</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>LibraryClient</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<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>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
</dependency>
</dependencies>
<build> …Run Code Online (Sandbox Code Playgroud) 我正在尝试理解restTemplate上可用的readTimeout,它究竟是什么?
它是在我们获得超时异常之前请求可以花费的总时间吗?
我想创建一个生成text/csv内容的简单网络服务。但我不能要求它:
@RestController
public class MyServlet {
@PostMapping(produces = {"text/csv", "application/json"})
public Object post() {
//...
}
}
spring.mvc.contentnegotiation.media-types.csv=text/csv
Run Code Online (Sandbox Code Playgroud)
当我发送带有 http 标头的 post 请求时Content-Type: text/csv,出现以下错误:
415:Content type 'text/csv' not supported
这是我的配置:
@Configuration
public class ContentNegotiationConfiguration implements WebMvcConfigurer {
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer
.favorParameter(true) //favor &format=csv
.defaultContentType(MediaType.APPLICATION_JSON)
.parameterName(format);
//.mediaType("csv", new MediaType("text", "csv")) //also tried without success
}
}
Run Code Online (Sandbox Code Playgroud) 我有一个休息控制器类,如下所示,当用户对象无效时,它会抛出自定义异常。但是这些异常被 spring 框架包装,而不是由控制器建议中定义的特定异常处理程序处理。
@PostMapping
public ResponseEntity<String> process(
@PathVariable(User_id) String id,
@Valid @RequestBody(required = false) User user) {
}
Run Code Online (Sandbox Code Playgroud)
例如,Json 映射异常被包装为 org.springframework.http.converter.HttpMessageNotReadableException,并且不会通过控制器建议中的以下异常处理程序进行处理。
@ExceptionHandler(JsonMappingException.class)
public ResponseEntity<ErrorMessage> handleJsonMappingException(JsonMappingException e){
//process to return error message
}
Run Code Online (Sandbox Code Playgroud)
如何处理构建请求主体对象时抛出的这些特定异常?
实际收到的异常:
2018-09-16 23:14:07,671 ERROR [qtp1824013753-23] c.m.a.c.e.m.MyExceptionHandler [MyExceptionHandler.java:111] Unhandled exception : Type definition error: [simple type, class com.common.model.User]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.common.model.User`, problem: '123ghijk' is not a valid DeptName
at [Source: UNKNOWN; line: -1, column: -1] (through reference chain: com.common.model.Employee["DeptName"])
org.springframework.http.converter.HttpMessageConversionException: Type definition …Run Code Online (Sandbox Code Playgroud) exception spring-mvc spring-boot spring-restcontroller spring-rest
我使用以下代码从 HTTP 请求获取值:
@PostMapping(consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, value = "/v1/notification")
public ResponseEntity<String> handleNotifications(@RequestBody MultiValueMap<String, Object> keyValuePairs) {
LOGGER.debug("handleFormMessage");
LOGGER.debug("keyValuePairs: {}", keyValuePairs);
String unique_id = String.valueOf(keyValuePairs.get("unique_id"));
System.out.println("!!!!!!!!!!!!!! ! unique_id " + unique_id);
}
Run Code Online (Sandbox Code Playgroud)
但我得到这个值:!!!!!!!!!!!!!! ! unique_id [24q376c3ts2kh3o3220rry322dfe2k7y]。
[]有没有办法在没有经典的情况下从字符串中删除String result = str.substring(0, index) + str.substring(index+1);?
有没有办法获取值?
我用它来发布值:
是否可以在Spring批处理项目中使用RestAPI(REST TEMPLATE)从DB读取数据,处理它并在ItemWriter中发送到另一个系统?我所能看到的就是获取数据并将其写入 csv 文件。
spring-batch spring-boot spring-rest itemwriter spring-resttemplate
我有两个项目,projectA(spring boot),projectB(spring)
在这两个项目中,我有类似的返回字符串的 API。但是来自projectB API的响应有双引号,而projectA的响应中没有双引号
ProjectA [这是 Spring Boot 项目]
@PostMapping(path = "/tenants/{tenantId}/script/getNormalString")
public String getNormalString(@PathVariable("tenantId") String tenantId,HttpServletRequest httpRequest) {
try {
String uuid = "normalString";
return uuid;
} catch(Exception e) {
logger.error("Error in getNormalString-> {}",e.getMessage(),e);
throw new RestApiException(FAILED_GET,e.getMessage(),e);
}
}
Run Code Online (Sandbox Code Playgroud)
回复
normalString
Run Code Online (Sandbox Code Playgroud)
项目B
@PostMapping(path = "/tenants/{tenantId}/script/getNormalString")
public String getNormalString(@PathVariable("tenantId") String tenantId,HttpServletRequest httpRequest) {
try {
String uuid = "normalString";
return uuid;
} catch(Exception e) {
logger.error("Error in getNormalString-> {}",e.getMessage(),e);
throw new RestApiException(FAILED_GET,e.getMessage(),e);
}
}
Run Code Online (Sandbox Code Playgroud)
回复
"normalString"
Run Code Online (Sandbox Code Playgroud)
有人可以帮我解决为什么反应有差异吗?有没有办法发送不带双引号的响应?我尝试使用@Produces("text/plain")但响应仍然没有变化
我有 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) spring-rest ×10
spring ×7
spring-boot ×6
java ×4
rest ×3
controller ×1
exception ×1
image ×1
itemwriter ×1
resttemplate ×1
spring-batch ×1
spring-mvc ×1
spring-web ×1