Having an issue with displaying the index.html webpage that I have created. The output that I keep receiving when heading over to localhost:8080 is the String value "index" and not the webpage itself. Images of the /templates directory & result given from localhost can be found below (hyperlinks)
@Controller
public class IndexController {
@RequestMapping("/")
@ResponseBody
public String index() {
return "index";
}
}
template_directory localhost:8080_result
Remove @ResponseBody
from your controller method addNewBooking(...). With @ResponseBody
you tell Spring to map the result of your method to the HTTP response body and so your browser displays it as plain text (you need this if you want to develop RESTful APIs with Spring). As you are using Spring MVC, you want to return a view and therefore you don't need @ResponseBody
.
EDIT 1: Detailed explanation of what I wrote.
With Spring Web
you have two choices to write your app:
JSPs
, Thymeleaf templates
, Freemaker templates
-> Spring MVC
patternFor choice 1 you annotate your controller with @Controller
and offer several endpoints where your Spring application will respond with your server-side renderer template. All of your controller return a String
which is the name of your template which you want to transfer to the browser. Spring will take the String
name like index
and will return e.g. the rendered index.jsp
to the request. An example could look like the following:
@Controller
public class IndexController {
@RequestMapping("/")
public String index() {
return "index";
}
}
For choice 2 you annotate your controller with @RestController
OR you @Controller
and @ResponseBody
together (technically @RestController
is just a combination of @Controller
and `@ResponseBody). With this setup you tell Spring to use your controller method return type and parse it e.g. with Jackson to JSON and will put it in the HTTP body. If you access such an endpoint in your browser you get
the JSON representation of your object. Look at the following example:
@RestController
public class IndexController {
@RequestMapping("/persons")
public List<Person> getPersons() {
// ... some service calls/database access to get all persons
return personList;
}
}
The Person class:
public class Person {
private String name;
private int age;
// getter and setter ...
}
If you now access http://localhost:8080/persons
you could get the following output:
[
{
"name": "John Doe",
"age": 1337
},
{
"name": "Peter Parker",
"age": 12
}
]
To summarize the explanation: If you want to serve Views (HTML pages which are server side rendered) you have to use @Controller
and your controller methods have to return the name of your template. If plan to build a RESTful application, use @RestController
or the combination of @Controller
and @ResponseBody
together.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With