I have recently created a Spring boot project and am trying to work with jQuery AJAX to get data from Controller in Spring. It returns 404 for some reason.
My controller
import java.util.ArrayList;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class HomeController {
#RequestMapping(value="/", method=RequestMethod.GET)
public String loadHome() {
return "index";
}
#RequestMapping(value="/getMajors", method=RequestMethod.GET)
public ArrayList<String> getMajors(){
ArrayList<String> majors = new ArrayList<>();
majors.add("Computers");
majors.add("Physics");
return majors;
}
}
The first method was to load the home page index.html the second was the method that maps to AJAX request.
My jQuery AJAX Request
$.ajax({
type:"get",
url:"/getMajors",
success:function(data){
console.log(data);
},
error:function(data){
console.log(data);
}
});
Please tell me why I'm getting a 404 here. TIA.
Edit: This app was created in Springboot. Standard config with web, dev-tools packages - from spring initializer.
I guess you are missing two things. One is the context name which usually is the name of the project or the war file deployed to the server, unless you are providing another context in web.xml. A sample servlet mapping from web.xml file:
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
So when your ajax call hits /getMajors it usually points to "localhost:port/getMajors" instead of say "localhost:port/sampleproj/getMajors" .You are missing the context there.
So your method needs to look like this:
#RequestMapping(value = "/getMajors", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ArrayList<String> getMajors(){
ArrayList<String> majors = new ArrayList<>();
majors.add("Computers");
majors.add("Physics");
return majors;
}
One good method to debug these is to see the developer console(Chrome) for request response information.
Happy Coding!
Edit 1: removing #ResponseBody from method as the class is annotated with #RestController. But my statement stands correct in case the class is annotated with #Controller.
Related
We are migrating jsp mapping to Spring controller and we want move jsp code to Spring service as we have only scriptlet code in jsp files but the main thing we do not want to change the url that we are calling from UI using ajax call.
Ajax call sample
/ProjectContext/jsp/project/module/downloadFile.jsp
So here .jsp extension will remain same so what should I have to mention in viewResolver.
Please do let me know is there any better way to migrate jsp scriptlet code to spring controller and service.
I have tried below code but not work for me.
#Controller
public class DownloadController {
#Autowired
private DownloadService downloadService;
#RequestMapping(value = "/jsp/project/module/downloadFile.jsp", consumes = APPLICATION_FORM_URLENCODED_VALUE)
public void downloadFileToLocal(HttpServletRequest request, HttpServletResponse response) {
downloadService.downloadFileToLocal(request, response);
}
}
I am learning spring MVC and have wrote following code. I read some articles about SOAP and REST but in the beginner level controller code I have written I am not able to distinguish whether SOAP or REST is used. My controller code is as follows:
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.model.Customer;
#Controller
public class SelectController {
#RequestMapping("/")
public String display(){
System.out.println("Inside controller");
return "demo";
}
#RequestMapping("/index")
public String indexpage(HttpServletRequest req, Model m){
String name = req.getParameter("name");
String pass = req.getParameter("pass");
String random = req.getParameter("abc");
System.out.println("Index page"+name+pass+random);
Customer cust = new Customer();
cust.setUsername(name);
cust.setPassword(pass);
System.out.println("Index page"+name+pass);
m.addAttribute("customer", cust);
return "hello";
}
The Controller that you have written is
neither REST nor SOAP.
Its a MVC Controller.
In your case, your returning "hello" string at the end of controller method, which in-turn gets translated/mapped to a page(hello.jsp or hello.html based on the configuration) and returns the same. So, at the end, what you get is Page rendered in a beautiful way with all the necessary Stylings and scripts applied.
In contrast, REST and SOAP doesn't work in that way. Its main purpose is for transferring the data alone(Yet you can send HTML page also)
Writing a REST Service is almost similar to what you have currently and is fairly easy. If you use Springboot then all you have to do is just replace the #Controller annotation with #RestController and return Customer object directly. In REST Controller you wont have HttpServletRequest & Model arguments.
But writing a SOAP service is another topic which may seem entirely different.
There are tons of examples and tutorials scattered around the web, which you can find easily on these topics.
References :
Controller vs RestController in Spring
Difference between Controller & RestController in Spring
SOAP vs REST
Hope this gives some high level idea of what those three are.
I have a spring mvc controller, which accepts a post request and it needs to redirect to a URL (GET request).
#RequestMapping(value = "/sredirect", method = RequestMethod.POST)
public String processForm(HttpServletRequest request) {
System.out.println("Ews redirect hit !!! ");
request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE,HttpStatus.MOVED_PERMANENTLY);
return "redirect:https://www.google.com/";
}
And the class is annotated with #RestController. I am always getting 405, method not allowed for the redirect url. (i.e google.com).
As per docs (https://www.rfc-editor.org/rfc/rfc7238), it should allow the method to be changed . I am not sure what am I doing wrong? Can someone help
It looks like Rest Controllers can't use the simple "redirect:" convention, like non-Rest Controllers can. See Spring MVC #RestController and redirect
Have you tried accepting GET in the request mapping?
method = { RequestMethod.POST, RequestMethod.GET }
HTTP Status 404 - /SpringMVCHibernate/WEB-INF/views/user/userHome.jsp
shown in the webpage as error, even the page userHome.jsp is present in the correct package.
Thanking in Advance
You need to use the path given in #RequestMapping annotation on a controller method.Check for the controller method which returns userHome.jsp view.
Refer spring controller documentation
https://docs.spring.io/spring-framework/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-controller
The error message says for 404 that it's looking for userHome.jsp. And indeed, your controller returns the following view name: " userHome". But in your case shows that your file is naled userHome.jsp. The case matters.
Try returning the properly cased view name which matches the JSP userHome.jsp from the controller. Currently the controller returns Hello while the JSP is named userHome.jsp, causing the 404
#Controller
public class UserHomeController {
#RequestMapping(value = "/greeting")
public String sayHello (Model model) {
model.addAttribute("greeting", "Hello");
//return "Hello";
return "userhome";
}
}
I'm trying to invoke a spring web service, using below url in browser the service "myservice" should return XML, ie based on the #RequestMapping annotations is the below URL correct?
> http://localhost:8080/mywebapp/myservice/feeds/allFeeds.xml/
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
#RequestMapping("myservice")
public class TheController {
private TheService TheServiceWS;
public TheController(TheService TheServiceWS) {
this.TheServiceWS = TheServiceWS;
}
#RequestMapping(value = "feeds/allFeeds.xml", produces = MediaType.APPLICATION_XML_VALUE)
#ResponseBody
public String getValues() {
return TheServiceWS.getAllFeeds();
}
}
The problem for me was :
The #RequestMapping annotation value "myservice" was incorrect
should have been "mywebservice"
If the web service return as XML, it is the original the SOAP web service. In this case, you couldn't build the web service with #RequestMapping. The #RequestMapping is used when you want to build a REST web service.
In this case, you should use the Spring WS. You have to annotate the class with #Endpoint to create an web service endpoint. In the this endpoint, you create your request mapping with #Payloadroot. Please refer to this