2017-07-03 47 views
0

我正在創建一個基於Spring的Web應用程序(Spring,jackson和hibernate),它將接受XML/BASE64輸入作爲請求消息並處理響應將是XML消息。應用程序將有不同的控制器接受BASE64/XML消息。將接受(XML/BASE64)並返回支持傑克遜的XML的Spring控制器

客戶---(BASE64/XML) - >服務器----> XML --->客戶端

我需要知道如何實現兩個不同的控制器,可以從客戶端讀取XML 。由於它是一個Web應用程序,它將根據客戶端請求獲取輸入消息。請求XML消息包含可能/可能不存在的可選標籤。我需要知道創建應用程序作爲Spring Web服務是否好(請引導我使用正確的示例鏈接),或者像正常的Web應用程序那樣從輸入流中讀取數據。

我的客戶端程序將打開一個URL連接,打開流寫入數據並等待服務器將響應寫回流。

@Controller 
@RequestMapping("/employee") 
public class EmployeeController { 

    //Function to take request and response as XML 
    @RequestMapping(value = "/allEmployyes", method = RequestMethod.POST) 
    public @ResponseBody EmployeesStatus readAllEmployeeDetails() { 
    } 

    //Function to take request as BASE64 and reply as XML 
    @RequestMapping(value = "/empProfile", method = RequestMethod.POST) 
    public @ResponseBody ProfileStatus updateEmployeeProfilePic() { 
    } 
} 

請幫助我創建一個更好的解決方案(需要有經驗的Spring專業人員的實用解決方案)。

回答

0

以下是使用@RestController的一種可能的解決方案,可以滿足您的要求。注意:我正在使用Project Lombok註釋處理來減少樣板吸氣劑和吸附劑,但您絕不會有義務使用它。

import lombok.AllArgsConstructor; 
import lombok.Data; 
import lombok.extern.slf4j.Slf4j; 
import org.hibernate.validator.constraints.NotEmpty; 
import org.springframework.validation.annotation.Validated; 
import org.springframework.web.bind.annotation.ExceptionHandler; 
import org.springframework.web.bind.annotation.RequestBody; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RestController; 

import javax.servlet.http.HttpServletResponse; 
import javax.validation.ConstraintViolation; 
import javax.validation.ConstraintViolationException; 
import javax.validation.Valid; 
import javax.validation.constraints.Pattern; 
import java.io.IOException; 
import java.util.Base64; 
import java.util.stream.Collectors; 

import static org.springframework.http.HttpStatus.BAD_REQUEST; 
import static org.springframework.http.MediaType.APPLICATION_XML_VALUE; 
import static org.springframework.http.MediaType.TEXT_PLAIN_VALUE; 
import static org.springframework.web.bind.annotation.RequestMethod.POST; 

@RestController 
@RequestMapping("/employee") 
@Validated 
@Slf4j 
public class EmployeeController { 
    /** 
    * Reads employee details and returns status. 
    * 
    * @param employeeDetails the employee details 
    * @return a status object 
    */ 
    @RequestMapping(value = "/allEmployees", method = POST, consumes = APPLICATION_XML_VALUE, produces = APPLICATION_XML_VALUE) 
    public EmployeeStatus readAllEmployeeDetails(@Valid @RequestBody EmployeeDetails employeeDetails) { 
     log.info("Got employee details: {}", employeeDetails); 
     return new EmployeeStatus("Employee details updated"); 
    } 

    /** 
    * Reads a Base64 encoded picture and returns status. 
    * 
    * @param picture the Base64 encoded picture 
    * @return a status object 
    */ 
    @RequestMapping(value = "/empProfile", method = POST, consumes = TEXT_PLAIN_VALUE, produces = APPLICATION_XML_VALUE) 
    public ProfileStatus updateEmployeeProfilePic(
      @Valid 
      // Regular expression for validating Base64 encoded text. 
      @Pattern(message = "Not Base64 encoded", regexp = "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$") 
      @RequestBody String picture) { 
     byte[] bytes = Base64.getDecoder().decode(picture); 
     log.info("Received {} bytes", bytes.length); 
     // Process bytes... 
     return new ProfileStatus("Picture updated"); 
    } 

    /** 
    * Handles validation constraint violations by returning a 400 Bad Request, and outputs the violation messages. 
    * 
    * @param e  the {@link ConstraintViolationException} 
    * @param response the {@link HttpServletResponse} 
    * @throws IOException on unexpected I/O error 
    */ 
    @ExceptionHandler 
    public void handleConstraintViolation(ConstraintViolationException e, HttpServletResponse response) throws IOException { 
     String message = e.getConstraintViolations().stream() 
       .map(ConstraintViolation::getMessage) 
       .collect(Collectors.joining(", ")); 
     response.sendError(BAD_REQUEST.value(), message); 
    } 

    @Data 
    public static class EmployeeDetails { 
     @NotEmpty 
     private String firstName; 
     @NotEmpty 
     private String lastName; 
    } 

    @Data 
    @AllArgsConstructor 
    public static class EmployeeStatus { 
     private String status; 
    } 

    @Data 
    @AllArgsConstructor 
    public static class ProfileStatus { 
     private String status; 
    } 
} 

這是我用於控制器的Maven POM。關鍵是要包括jackson-dataformat-xml作爲XML序列化支持的依賴:

<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/maven-v4_0_0.xsd"> 
    <modelVersion>4.0.0</modelVersion> 

    <groupId>com.anoop</groupId> 
    <artifactId>stack-44893803-rest</artifactId> 
    <packaging>jar</packaging> 
    <version>1.0-SNAPSHOT</version> 

    <parent> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-parent</artifactId> 
     <version>1.5.4.RELEASE</version> 
     <relativePath/> 
    </parent> 

    <properties> 
     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
     <maven.compiler.source>1.8</maven.compiler.source> 
     <maven.compiler.target>1.8</maven.compiler.target> 
    </properties> 

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

     <dependency> 
      <groupId>com.fasterxml.jackson.dataformat</groupId> 
      <artifactId>jackson-dataformat-xml</artifactId> 
      <version>2.8.8</version> 
     </dependency> 

     <dependency> 
      <groupId>org.projectlombok</groupId> 
      <artifactId>lombok</artifactId> 
      <version>1.16.16</version> 
      <scope>provided</scope> 
     </dependency> 

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

    <build> 
     <plugins> 
      <plugin> 
       <groupId>org.springframework.boot</groupId> 
       <artifactId>spring-boot-maven-plugin</artifactId> 
      </plugin> 
     </plugins> 
    </build> 
</project> 

這使您可以將XML和序列化/使用反序列化傑克遜:

curl -X POST \ 
    http://localhost:8080/employee/allEmployees \ 
    -H 'content-type: application/xml' \ 
    -d '<employee> 
    <firstName>John</firstName> 
    <lastName>Doe</lastName> 
</employee>' 
0

我認爲解決這個可以使用的方法如下面 ```

```

並且所述控制器改變 `` `

//Function to take request and response as XML 
@RequestMapping(value = "/allEmployyes", method = RequestMethod.POST) 
public void EmployeesStatus readAllEmployeeDetails(HttpServletResponse response) { 
     ... 
    ObjectMapper mapper = new XmlMapper(); 
    String xmlStr = xmlMapper.writeValueAsString(someresult); 
    try { 
     response.getWriter().write(xmlStr); 
     } catch (IOException e) { 
     log.error("Io Exception!",e); 
     } 
} 

```