#POST Method REST - Status Code: 405 / Method Not Allowed
I am invoking a REST method from JSP which results in error Status Code: 405 / Method Not Allowed
What could be the reason and how can resolve the issue? Application server Weblogic 12.2.1.4
#POST
public Object saveProduct(#FormParam("productId") String productId,
#FormParam("productCategoryId") #Context HttpServletRequest request,
#Context HttpHeaders headers) {
String returnJSON = null;
List<ProductList> productPersistList = new ArrayList<ProductList>();
ProductPersist productPersist = new ProductPersist();
productPersistList.add(productPersist);
log.info("productId " + productId);
try {
for (ProductList persistItems: productPersistList) {
persistItems.setProductId(productId);
}
productPersistDAO.persistData(productPersistList);
log.info("persist data ");
map.put("success", "true");
map.put("msg", "Done");
returnJSON = JSONObject.fromObject(map).toString();
} catch (Exception e) {
log.error("error from persistData " + e);
e.printStackTrace();
} finally {
map.clear();
}
return returnJSON;
}
Update 1
The below is the code snippet where REST API is called wher it is defined in a .js file
function saveProduct(param){
$('#fmEdit').form('submit',{
method: 'POST',
contentType : "application/x-www-form-urlencoded",
url: url,
onSubmit: function(){
return $(this).form('validate');
},
success: function(result){
var result = eval('('+result+')');
if (result.errorMsg){
$.messager.show({
title: 'Error',
msg: result.errorMsg
});
} else {
successMessage();
$('#dg').datagrid('reload');
if(param=='saveclose' ){
$('#dlg').dialog('close');
}
else if(param == 'save'){
$('#fmEdit').form('clear');
}
}
}
});
}
have u tried to set Consumes(MediaType.APPLICATION_FORM_URLENCODED) in the REST service method?
Related
I have a Spring Boot application written in Java that is a REST API. This service (Svc A) calls a REST API service (Svc B) with is also a Spring Boot Application written in Java. Svc B returns a 404 status code when no data was found. I need to change this response to a 200 status code and return an empty response object. I am not sure if or how to do this.
I can catch the error and determine if the 404 is this no data found error. However, I don't know how to change the response to a 200 empty response.
I am using a FeignClient to call the service. This is the error code that catches the 404:
#Component
public class FeignErrorDecoder implements ErrorDecoder {
Logger logger = LoggerFactory.getLogger(this.getClass());
#Override
public Exception decode(String methodKey, Response response) {
Reader reader = null;
String messageText = null;
switch (response.status()){
case 400:
logger.error("Status code " + response.status() + ", methodKey = " + methodKey);
case 404:
{
logger.error("Error took place when using Feign client to send HTTP Request. Status code " + response.status() + ", methodKey = " + methodKey);
try {
reader = response.body().asReader();
//Easy way to read the stream and get a String object
String result = CharStreams.toString(reader);
logger.error("RESPONSE BODY: " + result);
ObjectMapper mapper = new ObjectMapper();
//just in case you missed an attribute in the Pojo
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
//init the Pojo
ExceptionMessage exceptionMessage = mapper.readValue(result,
ExceptionMessage.class);
messageText = exceptionMessage.getMessage();
logger.info("message: " + messageText);
} catch(IOException ex) {
logger.error(ex.getMessage());
}
finally {
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return new ResponseStatusException(HttpStatus.valueOf(200), messageText);
}
default:
return new Exception(response.reason());
}
}
}
I can change the status code to a 200 and it returns a 200 but I need to the response to have an empty response object.
The above code will return this response body of an error response object:
{
"statusCd" : "200",
"message" : "The Location not found for given Location Number and Facility Type Code",
"detailDesc" : "The Location not found for given Location Number and Facility Type Code. Error Timestamp : 2020-01-31 18:19:13"
}
I need it to return a response body like this:
200 - Empty Response
{
"facilityNumber": "923",
"facilityTimeZone": null,
"facilityAbbr": null,
"scheduledOperations": []
}
In case 404 just try
return new ResponseStatusException(HttpStatus.valueOf(200));
For anyone that has to do something this crazy...here is my solution:
Removed the FeignErrorCode file.
Added an exception to ControllerAdvice class like this:
#ExceptionHandler(FeignException.class)
public ResponseEntity<?> handleFeignException(FeignException fe, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), HttpStatus.valueOf(fe.status()), fe.getMessage(), request.getDescription(false));
String response = fe.contentUTF8();
if(response != null) {
ScheduledOperationsViewResponse scheduledOperationsViewResponse = new ScheduledOperationsViewResponse();
if (response.contains("Scheduled") || response.contains("Location")) {
HttpHeaders headers = new HttpHeaders();
scheduledOperationsViewResponse.setFacilityNumber(request.getParameter("facilityNumber"));
return new ResponseEntity<ScheduledOperationsViewResponse>(scheduledOperationsViewResponse, headers, HttpStatus.OK);
}
}
return new ResponseEntity<>(errorDetails, errorDetails.getStatus());
}
I was having some problem when trying to send RESTful API from Angular to EJB. Here is my component.ts:
this.opUserAdminWinService.retrievePegRoleList().subscribe(resf => {
console.log(resf);
});
And my service.ts:
serviceAPI = SERVER_API_URL;
mainAPI = '/api/securityactivity/securityactivity';
retrievePegRoleList() {
const url: string = this.serviceAPI + this.mainAPI + '/RetrievePegRoleList';
return this.http.post(url, this.httpOptions);
}
In my Controller.java:
#PostMapping("/RetrievePegRoleList")
public Vector RetrievePegRoleList()
throws JaMClientRemoteException, JaMException {
return getSecurityActivity().RetrievePegRoleList();
}
In my EjbBean class:
public Vector RetrievePegRoleList() throws JaMClientRemoteException, JaMException;
#TransactionAttribute(TransactionAttributeType.SUPPORTS)
public Vector RetrievePegRoleList() throws JaMClientRemoteException, JaMException
{
Vector pegRoleList;
try {
String dataSource = JaM.getProperties().ORD_DATA_SOURCE;
RetrievePegRoleListTask retrievePegRoleListTask = new RetrievePegRoleListTask(dataSource);
retrievePegRoleListTask.execute();
pegRoleList = retrievePegRoleListTask.getResult();
} catch (Exception e) {
throw new JaMClientRemoteException(this.ERR_EXCEPTION_JAM, e.toString());
}
return pegRoleList;
}
However, I am getting this error message:
Any ideas why is it so? Thanks!
try this in angular.
export const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
this.http.post(your-url,your-data, httpOptions);
I always send post like this in angular.
If it doesn't work. You should examine,is there an interceptor in Server.
I am trying to get the user list for a email Id using a post request , Sometimes the post request goes to pending status and it stays in the same status forever.If I restart the tomcat then the request works but after some times the same issue occurs.
Below is the post method calling in angular
loadBOEDetailsListByEmail(emailId, password) {
const url = `${environment.url}backofficeemployee/detailsByBoeEmailId/`;
const params = {
resetEmail: emailId
};
const myHeader = new HttpHeaders();
myHeader.append('Content-Type', 'application/x-www-form-urlencoded');
return Observable.create(observer => {
this.http.post(url, params, { headers: myHeader }).subscribe(
(response: any) => {
if (response && response.data && response.data[0] !== undefined) {
this.accountList = response.data;
const boe = response.data[0];
this.checkAccountValidity(boe, password, observer);
} else {
observer.error('No account found');
}
},
() => observer.error('Employee service call failed')
);
});
}
In the java side this is how I am receiving
// Backoffice employee - Details by BoeUserId
#PostMapping(value = "/detailsByBoeEmailId/")
public #ResponseBody Map<String, Object> getBackofficeemployeeDetailsByBoeEmailId(#RequestBody ResetpasswordRequestDto requestDto) {
log.info(" boeEmailId in getBackofficeemployeeDetails {}", requestDto.getResetEmail());
try {
List<BackofficeemployeeResponseDto> backofficeemployeeResponseDto = backofficeemployeeService
.getByBoeEmailId(requestDto.getResetEmail());
return JsonUtils.mapOK(backofficeemployeeResponseDto);
} catch (Exception e) {
log.error("Exception in getBackofficeemployeeDetailsByBoeEmailId", e);
return JsonUtils.mapError(ERROR_MSG + e.getMessage());
}
}
I have an ajax call like this
var userList = {
"active": activeUsersId,
"inactive": inactiveUsersId
}
$.ajax({
type: "POST",
data: userList,
url: "/ewaanmapbuilder/rest/user/status",
contentType: "application/json",
success: function (flag) {
if (flag == true) {
$("#messageContainer").text("Status Updated Successfully!");
}
else {
$("#messageContainer").text("Status Updation Failed!");
}
$('#messageContainer').css('display', 'block');
setTimeout(function () { $('#messageContainer').css('display', 'none'); $('.registration-container').css('margin-top', '10%') }, 3000);
}
});
In this ajax call i am sending the userlist as aobject and my spring controller is like this
#ResponseBody
#RequestMapping(value = EwaanMapBuilderConstant.UPDATE_USER_STATUS, method = RequestMethod.POST,consumes= MediaType.APPLICATION_JSON_VALUE)
public boolean updateUserStatus(#RequestBody ActiveUserList userList, HttpServletRequest request) {
try {
HttpSession session = request.getSession();
String adminUserId = session.getAttribute(EwaanMapBuilderConstant.USER_ID).toString();
userService.updateUserStatus(userList, adminUserId);
}
catch(Exception e) {
logger.error("update status failed" +e);
return false;
}
return true;
}
BUt my ajax call gives me "415 (Unsupported Media Type)" error. I have tried so many options but i am not getting where i am going wrong.
I have two web applications hosted on a server. From one I am trying to do $.post to the second application (spring mvc3). I am able to successfully hit the url of the second application but I do not get response back of the ajax call.
App1 JS Code (http://localhost:7777/app1/test.html) -
var serialisedFormData = $("form").serialize();
$.post("http://localhost:8080/app2/doSomething", serialisedFormData, function (data) {
alert("job done");
}, "json");
App2 Java Code -
#RequestMapping(value = "/doSomething")
public #ResponseBody String doSomething(HttpServletRequest request,
#RequestParam("d") String data) {
try {
... do something here ...
return "done";
}
catch (Exception e) {
logger.debug("Exception occured when doing something", e);
return "failure";
}
}
I achieved it by removing "json" type from my jquery post call.
$.post("http://localhost:8080/app2/doSomething", serialisedFormData, function (data) {
alert("job done");
});
and adding a header to my response
#RequestMapping(value = "/doSomething")
public #ResponseBody String doSomething(HttpServletRequest request, HttpServletResponse response, #RequestParam("d") String data)
{
try {
... do something here ...
response.setHeader("Access-Control-Allow-Origin", "*");
return "done";
}
catch (Exception e) {
logger.debug("Exception occured when doing something", e);
return "failure";
}
}