Cross origin blocked between Ajax and Spring Controller - ajax

I want a Javascript function to send data to a Spring controller and get a response. However, due to the strict-origin-when-cross-origin Referrer policy, the request does not go through.
Spring Controller :
#Controller
public class EventController {
#ResponseBody
#RequestMapping(value = "/event", method = RequestMethod.POST)
public String handleAjax(#RequestParam Integer id, HttpServletRequest request, HttpServletResponse response) {
response.setHeader("Access-Control-Allow-Origin", "*");
return "OK";
}
}
Javascript functions :
function getContextPath() {
return window.location.pathname.substring(0, window.location.pathname.indexOf("/",2));
}
function move(moveDir,velocity){
$.ajax({
type : "POST",
url : getContextPath() + "/event",
success: function(data){
console.log(data)
}
});
}
I know that I have to allow cross-origin for these files. So far, the things I tried didn't work.
List of what I tried :
-> Adding #CrossOrigin(origins = "http://localhost:8081", maxAge = 3600) to the controller
-> Adding response.setHeader("Access-Control-Allow-Origin", "*"); to the controller
-> Adding crossorigin="anonymous" to the Javascript <script> tag

Your code won't work because you specify to support POST method only
#RequestMapping(value = "/event", method = RequestMethod.POST)
OPTIONS method is required as Preflighted requests in CORS.
So you must support POST and OPTIONS also to make it work.
#RequestMapping(value = "/event")
#RequestMapping(value = "/event", method = { RequestMethod.POST, RequestMethod.OPTIONS })
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS

I finally got it. There were two problems.
The first was that I had to add that header to the ajax request, to allow the request to be handled by the server: headers: { 'Access-Control-Allow-Origin': '/path_to_request_target' },. Putting '*' instead of '/path_to_request_target' would also work.
The second was with my dispatcher servlet. I had to put .html at the end of the URL : url : getContextPath() + "/event.html",. This is due of the mapping of my dispatcher servlet :
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/index.jsp</url-pattern>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
Adding .html to the URL worked because of <url-pattern>*.html</url-pattern>. Adding a <url-pattern> that satisfied the format of the inital URL would also work.

Related

How to send JSON response from controller?

I want to pass a boolean value from my controller to javascript using json but couldnot find a way as I am new to spring mvc.
While using servlet we wrote:
response.getWriter().println(somevalue)
and the somevalue can be received using ajax.
Here my controller method is:
#RequestMapping(value = REGISTERACTION , method = RequestMethod.POST)
#ResponseBody
public boolean RegisterUser(#ModelAttribute("register") Register register,HttpServletRequest request, HttpServletResponse response)
{
boolean Registrationsuccess = userService.RegisterUser(register);
return Registrationsuccess;
}
So, here the boolean variable is Registrationsuccess which I want to send to js file and receive it using ajax.
And in my javascipt function which is called using onsubmit event-->
function AccountExists()
{
$.ajax({
type: 'POST',
url: 'registerProcess',
success: function(data){
let detail = JSON.parse(data);
if( data == true)
alert("Success");
else
alert("Not ");
}
});
}
Getting error --
The target resource does not have a current representation that would be acceptable to the user agent, according to the proactive negotiation header fields received in the request, and the server is unwilling to supply a default representation.
You need to use ResponseEntity and #RestController for JSON Response.
Note : #RestController includes both annotations #Controller and #ResponseBody.
Try with this :
#RestController
#RequestMapping("controller")
public class Controller {
#PostMapping("REGISTERACTION")
public ResponseEntity<Boolean> RegisterUser(#ModelAttribute("register") Register register)
{
Boolean registrationSuccess = userService.RegisterUser(register);
return new ResponseEntity<Boolean>(registrationSuccess , HttpStatus.OK);
}
}
Try to use #ResponseBody annotation in your controller's method. And change the return type of the method to Boolean, then return Registrationsuccess instead of ModelAndView.
You can achieve this using 2 approach
Approach 1: Set model attribute and using expression language you can find on jsp
model.addAttribute("test",true);
in Jsp page
${test}
Approach 2: If you are sending ajax request instead of ModelAndView create a object
set any attribute boolean and return object from method #ResponseBody annotation you will get json in Ajax Response
#RequestMapping(value = REGISTERACTION , method = RequestMethod.POST)
public #ResponseBody MyCustomObject RegisterUser(#ModelAttribute("register") Register register,HttpServletRequest request, HttpServletResponse response)
{
boolean Registrationsuccess = userService.RegisterUser(register);
MyCustomObject cusobj=new MyCustomObject();
cusobj.setStatus(true);
return cusobj;
}
Whatever code you have written it will not return json(It is basically form submission approach) so you have to go with first approach.

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);
}

No mapping found for HTTP request with URI - in spring 3.2.4

I have this controller:
...
#RequestMapping(value = "/accounts/manageaccount.do", method = RequestMethod.GET)
public String initForm(HttpServletRequest request, Model model) {
model.addAllAttributes(getModel(request));
return "registerAccountView";
}
#RequestMapping(value = "/accounts/saveaccount.do", method = RequestMethod.POST)
public String saveaccount(HttpServletRequest request, Model model) {
model.addAllAttributes(getModel(request));
return "registerAccountView";
}
...
The controller its mapping well when I put this URL in the browser
http://127.0.0.1:7001/devices/accounts/manageaccount.do
Then I have this jsp
<form method="post" action="saveaccount.do">
</form>
But when I submit I got this strange error
URL: /devices/accounts/saveaccount.do
???error404.error???
Make sure the servlet mapping in your web-xml is configured to handle the .do requests :
<servlet-mapping>
<servlet-name>yourServletName</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

HTTP Status 404 Spring rest The requested resource is not available

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

Spring Controller + Ajax return String

I want to return String from Spring MVC Controller to Ajax.
It is not working as expected and gives error.
My Ajax codes for this:
function ajaxRequest(item) {
$.ajax({
type: "POST",
url: "/myPage",
data: {
item: item
},
success: function (html) {
alert(html);
},
error: function(e) {
console.log("Error:" + e);
}
});
}
My Controller:
#RequestMapping(value = "/myPage", method= RequestMethod.POST, produces="text/plain")
public #ResponseBody String myController(HttpServletRequest request) {
String myItem = request.getParameter("item");
...
return myItem + "bla bla bla";
}
Chrome console result:
POST http://localhost:8080/myPage 406 (Not Acceptable) jquery.js
Error:[object XMLHttpRequest]
What am i missing here?
When you return a String from a handler method annotated with #ResponseBody, Spring will use a StringHttpMessageConverter which sets the return content-type to text/plain. However, your request does not have an Accept header for that content-type so the Server (your Spring app) deems it unacceptable to return text/plain.
Change your ajax to add the Accept header for text/plain.
I have solved it. We can return correct values with response writer.
#RequestMapping(value = "/myPage")
public void myController(HttpServletRequest request, HttpServletResponse response) throws IOException {
String myItem = request.getParameter("item");
...
response.getWriter().println(myItem + "bla bla bla");
}
Be sure that you have Jackson dependency. Spring MVC can relies on it.

Resources