Controller or RestController - spring

i'm new to jEE, and this is my first jEE code using spring. The code bellow is working fine. He just print the string index when i go to my localhost; and otherwise he print handling error.
My question is: Why this code isn't working anymore if I use #Controller instead of #RestController
I can't find any simple explanation in the docs from spring and I was hoping someone could explain this.
I have the feelings that a controller alone can't work without something like thymeleaf (I know if I were using thymeleaf the string index would be replaced by the index page from the ressources folder) where a RestController might be returning data as xml or json or something else.
Thanks
#RestController
public class HelloController implements ErrorController {
#RequestMapping("/")
public String index() {
return "index";
}
#RequestMapping("/error")
public String error() {
return "gestion erreur";
}
#Override
public String getErrorPath() {
return "/error";
}
}

The job of #Controller is to create a Map of model object and find a view but #RestController simply return the object and object data is directly written into HTTP response as JSON or XML.
The #Controller is a common annotation which is used to mark a class as Spring MVC Controller while #RestController is a special controller used in RESTFul web services and the equivalent of #Controller + #ResponseBody.
If you want the same functionality of #RestController without using it you can use #Controller and #ResponseBody.
#Controller
public class HelloController{
#RequestMapping("/")
#ResponseBody
public String index() {
return "index";
}
}

Related

Thymleaf not returning templates but strings

I'm building an application with thymeleaf, and i've encountered this problem where when returning a template as for example ...return "products";... and when I visit the url i addressed in #GetMapping() i get the string "products" instead of rendered template
.
#Service
public class HomeService {
#Autowired
ProductRepository productRepository;
public String getProducts(Model model) {
List<Product> products= productRepository.findAll();
if (!products.isEmpty()){
model.addAttribute("product", products);
return "products";
}else{
return "404";
}
}
}
#RestController
public class HomeController {
#Autowired
HomeService homeService;
#GetMapping("/home")
public String home(Model model){
return homeService.getProducts(model);
}
}
As stated above, the #RestController annotation should be replaced with the #Controller annotation.
The #RestController annotation in Spring is designed for building REST web services that return data in JSON or XML format, and it does not support the use of view templating engines like Thymeleaf. If you want to render HTML views, you should use the #Controller. In #Controller, we can return a view in Spring Web MVC.
Use #Controller, #RestController is for RestAPI only, and not MVC ;)

How to call Spring Boot RESt api using Spring MVC?

I have created REST api using Spring Boot.
So, that is the fragment of it:
#RestController
#RequestMapping("/api/employee")
public class EmployeeController {
#Autowired
private EmployeeService employeeService;
#GetMapping(value = "/all", produces = "application/json")
public ResponseEntity<List<Employee>> getAllEmployees() {
return ResponseEntity.ok(employeeService.findall());
}
Now, I would like to create more like MVC application part - simple view that shows all Employees using thymeleaf. (Just simple UI to use this app more convinient than sending curl requests)
#Controller
public class MainPageController {
#GetMapping("/employees")
public String showEmployees() {
// i don't know what to do here
return "employeesPage";
}
What is the appropriate way to do so? Is there a more simple way to do it?
Looking forward for your answers!
So you do exactly the same you did on your EmployeeController but instead of a JSON, you return a view.
Get your employes through EmployeeService and put them on a collection
Create your employee view under /templates folder (many tutorials of how to do it)
return this view with your collection of employees
Example:
#GetMapping(value = "employees")
public ModelAndView showEmployees() {
ModelAndView mav = new ModelAndView("employeesPage");
mav.addObject("employees", employeeService.findall());
return mav;
}
Check here for more detailed info:
https://www.thymeleaf.org/doc/articles/springmvcaccessdata.html

How to resolve return modal not working in spring boot

#PostMapping("/api/file/delete")
public String deleteMultipartFile(HttpServletRequest request) {
try {
String keyname=request.getParameter("keyname");
s3Services.deleteFile(keyname);
return "redirect:/welcome";
} catch(Exception e) {
return "redirect:/welcome";
}
}
Actual result :
printing "redirect:/welcome " in white page
Expected Result : it redirect to welcome modal.
Spring is a Java application framework and Spring boot is an evloution of Spring that helps create stand-alone, production-grade spring based application that you can "just run".
Spring boot supports #Controller and #RestController annotation, where
#Controller annotation indicates that the annotated class is a controller. It is a specialization of #Component and is autodetected through classpath scanning. It is typically used in combination with annotated handler methods based on the #RequestMapping annotation. #RestController is a sibling convenience annotation for creating Restful controllers.
If you created spring boot application having controller with annotation #Controller and you have #GetMapping method which return index.html(file location /src/main/resources/templates/index.html) view page. like code below :-
#Controller
public class MyController{
#GetMapping("/")
public String indexPage(){
return "index";
}
#GetMapping("/index")
public String routeWithIndex(){
return "redirect:/";
}
}
Both function returns index.html page. If you want more knowledge about spring annotation of #Controller and #RestController with examples visit baeldung site or official site about spring.

White Label error Page in Spring boot in spite of having main and controller in same package

I am attaching the project structure.When I run as Spring boot application it shows white label errror. Since controller is in base package there is no need of component scan too.Can some one say whats the mistake.
Controller:
#Controller
public class HelloWorldController
{
#RequestMapping("/greeting")
public String greeting()
{
return "Hello World";
}
}
Use #RestController instead of #Controller if want to test you response output. Spring will treat this as rest controller. else, add #ResponseBody to your controller

Springboot #Controller cannot be invoked, but #RestController works

My controller has been annotated with #Controller and it cannot be invoked
- The browser shows
There was an unexpected error (type=Not Found, status=404).
But, if it is annotated with #RestController, then it works. My SpringBoot version:1.5.3.RELEASE
My Controller : (in com.sbootsecurityjsp.controller)
#Controller
public class LoginController {
#RequestMapping(value = "/login", method= RequestMethod.GET )
public String login() {
return "Login Controller";
}
}
Main Class: (in com.sbootsecurityjsp)
#SpringBootApplication(scanBasePackages = {"com.sbootsecurityjsp"})
public class SbootSecurityJspApplication {
public static void main(String[] args) {
SpringApplication.run(SbootSecurityJspApplication.class, args);
}
}
I am curious why the #Controller cannot work if the #RestController annotation works. If component scan is not working, #RestController also should not work. I have added scanbasePackages too. Even without scanbasePackages, it does not work.
By the way, when the app starts, the logs also show a line as following:
INFO 532 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/login],methods=[GET]}" onto public java.lang.String com.sbootsecurityjsp.controller.LoginController.login()
Why #Controller is used is to differentiate requests to pages and rest calls. Please correct me if I am wrong. My idea is to use #RestController s for REST requests, on the other hand #Controller for pages related requests- redirecting to JSP or any logics related to views. Is it a bad practice ?
Why does it return a 404 when I use #Controller annotation?
When using #Controller, Spring expects the String you return in #RequestMapping methods to correspond to the page you want to redirect the user to.
#RequestMapping(value = "/login", method= RequestMethod.GET )
public String login() {
return "Login Controller";
}
Here, Spring will try to redirect the user to Login Controller.jsp, which cannot be found and thus returns a 404.
Why does it not return 404 when I use #RestController
When using #RestController, the String you return is not mapped to any page. Instead, Spring just transforms it to e.g. a JSON response. This is why this doesn't give you a 404.
Proposed solution
If you have a jsp page called login.jsp, simply return "login":
#RequestMapping(value = "/login", method= RequestMethod.GET )
public String login() {
return "login";
}

Resources