java springBoot - How to render a html page - java

I am using spring boot to try and build my own mini website.
I have a controller
package hello;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
#RestController
public class HelloController {
#RequestMapping("/greeting")
public String index() {
return "index";
}
}
and a html file resources/templates/index which I am trying to render but I just get the text "index" rendered. How can I return the html file instead of the text?

You have specified #RestController which says the result should be put into the #ResponseBody. You would want to use #Controller instead and then make sure you have a template framework (Thymeleaf, etc) in the classpath. Normally with most template frameworks you have to include the .html on the file that is within the templates folder.

Related

How do I address this mapping problem for Spring MVC?

package com.coding;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
#RequestMapping("/customer")
public class CustomerController {
#RequestMapping(value="/showForm")
public String showForm(Model theModel) {
theModel.addAttribute("customer",new Customer());
return "customer-form";
}
#RequestMapping("/processForm")
public String processForm
(#Valid #ModelAttribute("customer") Customer theCustomer,BindingResult theBindingResult) {
if(theBindingResult.hasErrors()) {
return"customer-form";
}else {
return "customer-confirmation";
}
}
}
New to Spring!:)
I am trying to build a dynamic project using Spring MVC which is "form validation" . I tried everything possible to solve this problem "WARNING: No mapping for GET /spring-mvc-demo/customer/showForm" but its not working . Any solution please?
As you can see this warning clearly tells the path does not exist and that it's not able to recognize at this path any handlers are available.
What you can do is, Make sure the path matches your controller method mappings.
Have you checked localhost:8080/customer/showForm? Try this URL it will work?
Hii Anjita I tried to reConstruct your problem it is working fine for me I have created a CustomerController class like this.
I created a login form like this
And I made a request from a browse with the URL "http://localhost:8080/customer/showForm". And the output is
Whenever I tried to give a URL "localhost:8080/spring-mvc-demo/customer/showForm" it is showing a Whitelabel error try removing your project name in URL and try once.

How to identify whether web service is REST or SOAP?

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.

404 on jQuery AJAX request in Spring boot

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.

How to return html from Rest API with spring boot application

I need to return an html page from Rest API in Spring boot Application. The html "test.html" is in src/main/resource directory. Below is my code snippet
#RequestMapping(value ="/get/getReportById",method = RequestMethod.GET)
#ResponseBody()
public String getReportsByCategory(String id) throws Exception{
try{
//Do something
}catch(Exception e){
e.printStackTrace();
}
return "test";
}
Class should be #Controller, remove #ResponseBody, you also should have configured template processor (Thymeleaf, for example).
Update
If you look inside code of #RestController, you will see that it is composition from #Controller and #ResponseBody annotations. So ResponseBody would be automatically applied to all methods.
If you want to return a view you do not want to have your controller method annotated as a #ResponseBody so remove that and it should work.
You need to read test.html from classpath and return it as a string:
InputStream htmlStream = getClass().getResourceAsStream("test.html");
return new Scanner(htmlStream, "UTF-8").useDelimiter("\\A").next();
#RestController
is to deal with webservices, it is all about data, presentation markup such as HTML doesn't have any role here.
#Controller
This is what you want to use if there is a view involved. view can be anything which will spit out an html (with or without interpolating the model). You can use good old JSP, JSF or templating engines like thymeleaf, velocity, freemarker etc.
You can use ModelAndView to view HTML page as follows,
#RequestMapping(value ="/get/getReportById")
public ModelAndView getReportsByCategory() throws Exception{
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("test.html");
return modelAndView;
}
Import library,
import org.springframework.web.servlet.ModelAndView;
This test.html file should be inside the src/main/resource/static/ directory.

Single Spring mvc 4 controller with no #RequestMapping returns strips css from my html view

I have a simple controller in a spring boot mvc app packaged as a .war (for aws deployment). I have Thymeleaf on the build path and bootstrap 3.3.6 in resources/static folder. I use #EnableAutoConfiguration in the main.
This controller displays a view just fine.
#Controller
#RequestMapping(value = "/handeware")
public class HomeController {
#RequestMapping(value = "/home", method = RequestMethod.GET)
public String viewHome() {
return "home";
}
}
However, when I remove the #RequestMapping part like this
#Controller
public class HomeController {
#RequestMapping(method = RequestMethod.GET)
public String viewHome() {
return "home";
}
}
It appears that the view gets returned with the Bootstrap CSS styling stripped.
Essentially, I have a domain name www.blah.com with the CNAME pointing to my spring mvc app hosted in aws elastic beanstalk. The idea is that I want someone to be able to type www.blah.com into the browser and be able to see my home page. In order to do this, I removed the #RequestMapping's from my controller, and it works. People can now visit my site at www.blah.com and see my home.html. However, the CSS styling is not showing up now. If I add the #RequestMapping back, the CSS shows back up. Isn't that odd? I confirmed in my local as well as in aws that this is the case. Not sure what to make of it.
How do you reference your css files from your html? You may need to update those references to match the new path.

Categories