I am facing a issue on calling REST API in following scenarios
str = < html>.....< /htm>
) Rest client code (webappA) :
RestTemplate restTemplate = new RestTemplate().getForObject(serverUrl, String.class);
Server code(webappB) : Note that this code will not existin in old build/war/version of webappB
@RequestMapping(value = "/xyz.htm")
public ResponseEntity<String> apiMethod(HttpServletRequest request, HttpServletResponse response) {
return (new ResponseEntity<String>(responseBody, HttpStatus.OK));
}
How I can solve this issue, instead of getting response string as login page (eg str = "< html>.........< /htm>"
). I need something from spring where rest client webappA can identify.
Thanks in advance.
Follow below steps to get a JSON response from webappB if no handler found for a particular URL requested by webappA:
Edit your web.xml as follows:
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/location/of/servlet_context.xml</param-value>
</init-param>
<init-param>
<param-name>throwExceptionIfNoHandlerFound</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
Now write a ExceptionHanler in your Controller or GlobalExceptionHandler class
@ExceptionHandler
public ResponseEntity<JSONReturned> exception(NoHandlerFoundException exception){
ResponseEntity<JSONReturned> responseEntity = null;
JSONReturned jsonReturned = new JSONReturned();
jsonReturned.setMsg("Sorry your request cannot be completed.");
jsonReturned.setResponse("Requested URL is not present.");
responseEntity = new ResponseEntity<JSONReturned>(jsonReturned, HttpStatus.BAD_REQUEST);
return responseEntity;
}
JSONReturned is a simple POJO class for carrying the message:
public class JSONReturned {
private String msg;
private String response;
//getters and setters
}
You are getting a 404 from the REST API since the path is not existing yet. You can change your default 404 response in your server (webappB) to what ever you prefer. https://spring.io/guides/tutorials/bookmarks/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.