天天看點

spring integration之http rest

spring integration例子代碼下載下傳位址,以及如何導入eclipse并使用maven建構等請參看上一篇:

Spring Integration執行個體代碼分析之basic--http

先看一下http-rest例子的readme

This sample demonstrates how you can send an HTTP request to a Spring Integration's HTTP service while utilizing Spring Integration's new HTTP Path usage;

This sample also uses Spring Security for HTTP Basic authentication. With HTTP Path facility, the client program can send requests with URL Variables.

It consists of two parts - Client and Server.

The following client program can be used to test the HTTP Path usage.

1. RestHttpClientTest. It uses Spring's RestTemplate to assemble and send HTTP request

Server is Spring Integration's HTTP endpoint configuration.

此示例示範了如何發送一個HTTP請求到一個Spring內建的HTTP服務,同時利用Spring Integration的新的HTTP Path;

此示例還使用了Spring HTTP基本身份驗證安全性。 HTTP Path,用戶端程式可以發送請求的URL變量。

它由兩部分組成 - 用戶端和伺服器。

用戶端程式,可以用來測試使用HTTP path。RestHttpClientTest。它使用Spring的RestTemplate的組裝和發送HTTP請求

服務端是Spring內建的HTTP端點配置。

代碼結構

spring integration之http rest

仍然先看web.xml

先是配置幾個變量,指定spring配置路徑和log4j的配置路徑

[html]

      <context-param> 

       <param-name>contextConfigLocation</param-name> 

       <param-value> 

            <!-- Spring application context declaration --> 

             /WEB-INF/config/web-application-config.xml                

       </param-value> 

    </context-param> 

    <!-- 

Key of the system property that should specify the root directory of this 

web app. Applied by WebAppRootListener or Log4jConfigListener. 

--> 

<context-param> 

    <param-name>webAppRootKey</param-name> 

    <param-value>rest-http.root</param-value> 

</context-param> 

    <!-- 

Location of the Log4J config file, for initialization and refresh checks. 

Applied by Log4jConfigListener. 

--> 

<context-param> 

    <param-name>log4jConfigLocation</param-name> 

    <param-value>/WEB-INF/classes/log4j.properties</param-value> 

</context-param> 

然後配置spring的listener,用于啟動WebApplicationContext

[html] 

<listener> 

    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> 

</listener> 

   <!-- 

    - Loads the root application context of this web app at startup, 

    - by default from "/WEB-INF/applicationContext.xml". 

    - Note that you need to fall back to Spring's ContextLoaderServlet for 

    - J2EE servers that do not follow the Servlet 2.4 initialization order. 

    - 

    - Use WebApplicationContextUtils.getWebApplicationContext(servletContext) 

    - to access it anywhere in the web application, outside of the framework. 

    - 

    - The root context is the parent of all servlet-specific contexts. 

    - This means that its beans are automatically available in these child contexts, 

    - both for getBean(name) calls and (external) bean references. 

--> 

    <listener> 

        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 

</listener> 

接着是filter,包含指定字元的,和security的,用于認證。

[html] 

<filter> 

            <filter-name>charEncodingFilter</filter-name> 

            <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 

            <init-param> 

              <param-name>encoding</param-name> 

              <param-value>UTF-8</param-value> 

            </init-param> 

            <init-param> 

              <param-name>forceEncoding</param-name> 

              <param-value>true</param-value> 

            </init-param> 

        </filter> 

        <filter-mapping> 

            <filter-name>charEncodingFilter</filter-name> 

            <url-pattern> 

    public List<Employee> getEmployee() { 

        if (employee == null){ 

            employee = new ArrayList<Employee>(); 

        } 

        return employee; 

    } 

EmployeeSearchService

[java]

@Service("employeeSearchService") 

public class EmployeeSearchService { 

    private static Logger logger = Logger.getLogger(EmployeeSearchService.class); 

    @Secured("ROLE_REST_HTTP_USER") 

    public Message<EmployeeList> getEmployee(Message<?> inMessage){ 

        EmployeeList employeeList = new EmployeeList(); 

        Map<String, Object> responseHeaderMap = new HashMap<String, Object>(); 

        try{ 

            MessageHeaders headers = inMessage.getHeaders(); 

            String id = (String)headers.get("employeeId"); 

            boolean isFound; 

            if (id.equals("1")){ 

                employeeList.getEmployee().add(new Employee(1, "John", "Doe")); 

                isFound = true; 

            }else if (id.equals("2")){ 

                employeeList.getEmployee().add(new Employee(2, "Jane", "Doe")); 

                isFound = true; 

            }else if (id.equals("0")){ 

                employeeList.getEmployee().add(new Employee(1, "John", "Doe")); 

                employeeList.getEmployee().add(new Employee(2, "Jane", "Doe"));              

                isFound = true; 

            }else{               

                isFound = false; 

            }            

            if (isFound){ 

                setReturnStatusAndMessage("0", "Success", employeeList, responseHeaderMap); 

            }else{ 

                setReturnStatusAndMessage("2", "Employee Not Found", employeeList, responseHeaderMap);                               

            } 

        }catch (Throwable e){ 

            setReturnStatusAndMessage("1", "System Error", employeeList, responseHeaderMap); 

            logger.error("System error occured :"+e); 

        } 

        Message<EmployeeList> message = new GenericMessage<EmployeeList>(employeeList, responseHeaderMap); 

        return message;      

    } 

    private void setReturnStatusAndMessage(String status,  

                        String message,  

                        EmployeeList employeeList,  

                        Map<String, Object> responseHeaderMap){ 

        employeeList.setReturnStatus(status); 

        employeeList.setReturnStatusMsg(message); 

        responseHeaderMap.put("Return-Status", status); 

        responseHeaderMap.put("Return-Status-Msg", message); 

    } 

這些代碼就都很簡單,一目了然,不用怎麼解釋了。

其中幾個元件關系如下圖所示:

運作

run as --> run on server -->選擇tomcat運作

用junit運作RestHttpClientTest,就可以得到資料。

[java

final String fullUrl = "http://localhost:8080/rest-http/services/employee/{id}/search"; 

    EmployeeList employeeList = restTemplate.execute(fullUrl, HttpMethod.GET, 

            new RequestCallback() { 

                @Override 

                public void doWithRequest(ClientHttpRequest request) throws IOException { 

                    HttpHeaders headers = getHttpHeadersWithUserCredentials(request); 

                    headers.add("Accept", "application/xml"); 

                } 

    }, responseExtractor, employeeSearchMap); 

[java] view plaincopy

@Test 

    public void testGetEmployeeAsJson() throws Exception{ 

        Map<String, Object> employeeSearchMap = getEmployeeSearchMap("0"); 

        final String fullUrl = "http://localhost:8080/rest-http/services/employee/{id}/search?format=json"; 

        HttpHeaders headers = getHttpHeadersWithUserCredentials(new HttpHeaders()); 

        headers.add("Accept", "application/json"); 

        HttpEntity<Object> request = new HttpEntity<Object>(headers); 

        ResponseEntity<?> httpResponse = restTemplate.exchange(fullUrl, HttpMethod.GET, request, EmployeeList.class, employeeSearchMap); 

        logger.info("Return Status :"+httpResponse.getHeaders().get("X-Return-Status")); 

        logger.info("Return Status Message :"+httpResponse.getHeaders().get("X-Return-Status-Msg")); 

        assertTrue(httpResponse.getStatusCode().equals(HttpStatus.OK)); 

        jaxbJacksonObjectMapper.writeValue(System.out, httpResponse.getBody()); 

    }