HTTP Status 404 Spring rest The requested resource is not available - spring

I am using spring 3.2.2.RELEASE and have a problem on sending request to server :
http://asdsda:8080/spr-mvc-hib/user/userHizmet.html?userId=19
HTTP Status 404 The requested resource is not available.
#RequestMapping(value = "/userHizmet/{userId}", method = RequestMethod.GET)
public ModelAndView userHizmet(#PathVariable String userId)
{
ModelAndView mav = new ModelAndView("userte");
where i called :
success: function (data) {
alert(data);
window.location.href="${pageContext. request. contextPath}/user/userHizmet.html?userId="+data;
},
dispatcher :
Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.addMapping("/");

localhost:8080/spr-mvc-hib/user/userHizmet.html?userId=19
removing .html and using requestparam solved my problem

Related

MethodArgumentTypeMismatchException in Spring

I have this method to retrieve data from my database :
#GetMapping(path="/login/in", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
User loginA(#RequestBody LoginCredential newLogin)
{
logger.debug(newLogin);
return repository.findByEmailAddress(newLogin.getEMail()).get(0).getUser();
}
And I'm trying to use this method like this :
var request = new XMLHttpRequest();
let url='http://localhost:8080/login/in';
let data=JSON.stringify({ email:this.state.email,passwordHash:this.state.passwordHash});
request.open('GET', url, true);
request.setRequestHeader("Content-Type", "application/json");
request.send(data);
It gives me error - 400
And Spring says :
Resolved [org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: com.mua.cse616.Model.User com.mua.cse616.Controller.LoginCredentialController.loginA(com.mua.cse616.Model.LoginCredential)]
How to resolve this?
I think the main problem is that you're using #GetMapping and sending body #RequestBody LoginCredential newLogin at the same time. You should user #RequestBody with #PostMapping or #PutMapping but not #Getmapping.
So, try to change your request to POST. That would solve the exception.
#PostMapping(path="/login/in", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
User loginA(#RequestBody LoginCredential newLogin)
{
logger.debug(newLogin);
return repository.findByEmailAddress(newLogin.getEMail()).get(0).getUser();
}
var request = new XMLHttpRequest();
let url='http://localhost:8080/login/in';
let data=JSON.stringify({ email:this.state.email,passwordHash:this.state.passwordHash});
request.open('POST', url, true);
request.setRequestHeader("Content-Type", "application/json");
request.send(data);

Spring MVC - Stop redirect in Controller function

I have a Spring MVC Controller and a PUT mapping that consumes JSON. I receive the JSON and everything just fine, the problem is whenever I fire off the JSON the mapper wants to redirect to the URL, giving me error 500 because the server can't find any template for the URL. How can I stop Spring MVC from trying to redirect to the URL and just receive the JSON?
My relevant Controller code :
#RequestMapping(value = "admin/users/VMs", method = RequestMethod.PUT, consumes = "application/json")
public void removeVM(#RequestBody ManageVMRequest packet, Authentication authentication) {
System.out.println(packet.getVm());
System.out.println(packet.getUser_id());
}
You can try to return ResponseEntity<Void>
#RequestMapping(value = "admin/users/VMs", method = RequestMethod.PUT, consumes = "application/json")
public #ResponseBody ResponseEntity<Void> removeVM(#RequestBody ManageVMRequest packet, Authentication authentication) {
System.out.println(packet.getVm());
System.out.println(packet.getUser_id());
return new ResponseEntity<Void>(HttpStatus.NO_CONTENT);
}

Error handling on controller SpringMVC

I am developing an application in jax-rs and spring mvc.
I want to notify my client each time when an default error is occured like
400, 403, 404, 405 and 415.
Controller
#Controller
#RequestMapping("/customer")
public class CustomerController {
#Autowired
CustomerService customerService;
// ........xxxxxx..............xxxxxxx................xxxxxxx.............//
#CrossOrigin
#RequestMapping(value = "/",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody String fetchCustomer() throws JsonProcessingException {
return new ObjectMapper().writeValueAsString(customerService.fetchAllCustomer());
}
// ........xxxxxx..............xxxxxxx................xxxxxxx.............//
}
Client
$http({
method: "GET",
contentType: "application/json",
url: baseUrl + '/customer'
}).success(function (response) {
console.log(response);
// you can also use
console.log(JSON.stringify(response);
}).error(function (response) {
console.log(response);
});
When i request a service from client i want to send response back with status code and custom message.
Example
When i defind method = post on controller and from client i send request as get service should return message like
error:{
Status Code: 405,
Message: Invalid Method
url: error/405
}
Check this out for reference.
Define a method for handling the specific error scenario and annotate it as #ExceptionHandler. The exception in your scenario (request method not supported) is HttpRequestMethodNotSupportedException.class. You can create more generic handler methods using Throwable, Exception etc.
In order to prevent duplication of error handling across controllers, one convenient way is to define all handlers in single class and use #ControllerAdvice on that. This way, all handlers will be applied to all controllers.
Do not return a String but return a org.springframework.http.ResponseEntity.
You can add status codes to this object
ResponseEntity<String> responseEntity = new ResponseEntity<String>("This is a response", HttpStatus.INTERNAL_SERVER_ERROR);
return responseEntity;
So your method signature will also change as below
#RequestMapping(value = "/", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody ResponseEntity<String> fetchCustomer() throws JsonProcessingException {
try {
String str = new ObjectMapper().writeValueAsString(customerService.fetchAllCustomer());
return new ResponseEntity<String>(str, HttpStatus.OK);
}
catch (Exception e) {
return new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
If there is an error, you can either use controller advice or catch the exception and update the ResponseEntity appropriately

Spring MVC - #RequestMapping GET and POST #RequestMethod

I understand this question has been asked previously, I am learning Spring following along Spring Petclinic Sample project. There is no problem with processCreationForm, when a redirect is done to showOwner using GET it works as expected, but when I experiment it by using POST it throws HTTP Status 405 - Request method 'GET' not supported. Is it because processCreationForm is doing a redirect to showOwner I am unable to grab it as POST request?
#RequestMapping(value = "/owners/new", method = RequestMethod.POST)
public String processCreationForm(#Valid Owner owner,
BindingResult result) {
if(result.hasErrors()) {
return "owners/ownerForm";
} else {
this.clinicService.saveOwner(owner);
return "redirect:/owners/" + owner.getId();
}
}
#RequestMapping(value = "/owners/{ownerId}", method = RequestMethod.POST)
public ModelAndView showOwner(#PathVariable("ownerId") int ownerId) {
ModelAndView mav = new ModelAndView("owners/ownerDetails");
mav.addObject(this.clinicService.findOwnerById(ownerId));
return mav;
}
Any helpful comments are appreciated.
You're redirecting to /owners/{ownerId} url, but you didn't define a GET handler for that endpoint, hence Spring MVC complains with:
HTTP Status 405 - Request method 'GET' not supported.
Using RequestMethod.GET will solve your problem:
#RequestMapping(value = "/owners/{ownerId}", method = RequestMethod.GET)
public ModelAndView showOwner(#PathVariable("ownerId") int ownerId) { ... }
Is it because processCreationForm is doing a redirect to showOwner I
am unable to grab it as POST request?
Since your POST handler on /owners/new is redirecting to /owners/{ownerId}, does not mean that redirection will be a POST request. Redirections are always GET requests.

"org.springframework.web.servlet.PageNotFound handleHttpRequestMethodNotSupported" Request method 'POST' not supported

I am using angular JS and Spring MVC+Spring Security in my application. When using $http like below:
$http.post('/abc/xyz/'+catalogId);
it is giving below error:
org.springframework.web.servlet.PageNotFound handleHttpRequestMethodNotSupported
WARNING: Request method 'POST' not supported.
Moreover I've put POST in my controller as well:
#RequestMapping(value = "/xyz/{catalogId}", method = RequestMethod.POST)
public #ResponseBody List<Category> getCategorybyCatalogId(#PathVariable(value = "catalogId") long catalogId, ModelMap modelMap,
HttpSession session) throws IOException {
if (catalogId != 0) {
return menuService.getCategorybyCatalogId(catalogId);
} else {
return null;
}
}
this problem started coming when I added spring security config class.
Please help!!

Resources