My Spring Boot controller is working just fine, except that I cannot create a mapping for the home directory. I have tried:
#Controller
public class MyController {
#GetMapping(value = {"/"})
public ModelAndView searchPage(Locale locale) {
ModelAndView model = new ModelAndView();
model.setViewName("pageTemplate");
return model;
}
}
#GetMapping(value = "/")
#GetMapping(value = "")
#GetMapping
#RequestMapping with all values above
I always get my 404 error page. If this is supposed to work, how can I debug why it is not?
Found it. I set in application.properties:
logging.level.org.springframework.web: DEBUG
which then displayed
o.s.w.s.mvc.ServletForwardingController : Forwarded to servlet [springVaadinServlet] in ServletForwardingController 'vaadinUiForwardingController'
It turns out that I have used #SpringUI without specifying a path
Related
I use the interceptor in spring to make the user has login in,but when i transfer value from front end to back,the interceptor intercept the request,but it warns me that
WARN 8484 --- [nio-8080-exec-4] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved[org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported]
and send me to "/error",but i have add the controller into the excludePath like this
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(cookiesInterceptor).addPathPatterns("/**")
.excludePathPatterns("/adminapi/login")
.excludePathPatterns("/Login.html")
.excludePathPatterns("/index.html")
.excludePathPatterns("/static/**");
}
and the controller
#RequestMapping(value = "/adminapi")
public class AdminController {
#RequestMapping("/login")
public String .....
}
the action of form
<form th:action="#{/adminapi/login}" method="post">
so i do not know why the problem occur
In your AdminController,
replace #RequestMapping("/login")
with #PostMapping("/login")
This tells Spring Boot that you are using the POST method, otherwise by default GET is expected
I don't see the #Controller annotation in your AdminController
By the way, you should specify the method for your RequestMapping, you can use
#Controller
#RequestMapping(value = "/adminapi")
public class AdminController {
#RequestMapping(value = "/login", method = RequestMethod.POST)
public String .....
}
or
#Controller
#RequestMapping(value = "/adminapi")
public class AdminController {
#PostMapping("/login")
public String .....
}
Check whether CSRF is enabled in spring security xml file . If so add the
So you should be able to submit the model attribute.
Seems duplicate check here Spring,Request method 'POST' not supported
Check whethr on the Controller receiving function for Spring MVC , you ahve this annotation. #ModelAttribute
For the requestmapping specify the method type .
#RequestMapping(value = "/login", method = RequestMethod.POST)
I have the following controller in my Spring Boot application :
#RestController
#RequestMapping(value = "/users")
public class UserController {
#Autowired
UserService userService;
#GetMapping(value ="/helloWorld")
public String getHelloWorld() {
return "Hello World!";
}
#GetMapping(value = "/getAll")
public #ResponseBody
Iterable<User> getAllInvestors() {
return userService.getAllUsers();
}
}
When I make an HTTP Get on http://127.0.0.1:5000/users/getAll, it works perfectly : I get all the users from the database...
but when I make a call on http://127.0.0.1:5000/users/helloWorld, I get an unexpected error (type=Not Found, status=404)
PS 1 : When I call http://127.0.0.1:5000/api-docs to get the API definition : Both endpoints are exposed.
PS 2 : I've already made a Maven Clean, restarted IntelliJ, deleted all cookies from the browser.
PS 3 : No errors during compilation.
The issue was the case sensitivity, it was solved when I replaced #GetMapping(value ="/helloWorld") with #GetMapping(value ="/helloworld")
Refer to this topic for further details
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";
}
i'm actually new to handling with spring mvc and in particular i have to implement session in spring mvc. Can anybody guide me out of how to handle with session in spring mvc ?
It is the example of controller method level session
#Controller
Class YourController{
#RequestMapping(value = "/yourrequest", method = RequestMethod.GET)
public String yourMethod(Model model,HttpSession session){
return null;
}
}
You can also put session valid to Controller Class.It is just done by adding SessionAttribute.This will be available in all methods in YourController Class
#Controller
#SessionAttribute("sessionName")
Class YourController{
#RequestMapping(value = "/yourrequest", method = RequestMethod.GET)
public String yourMethod(Model model){
model.addAttribute("sessionName",valueToBeAddedInSession);
return null;
}
}
Here the name of object added in Session should be same as it is added in modelAttribute e.g. sessionName.
The problem in case of session attribute is that we have to invalidate it manually
Thank you.
#Controller
#SessionAttributes({ "sessionVar1","sessionVar2" })
public class StartController {
public ModelAndView methodName(){
ModelAndView modelandView = new ModelAndView("view");
modelandView.addObject("sessionVar1", "sessionVal1");
modelandView.addObject("sessionVar2", "sessionVal2");
return modelandView;
}
}
I need to migrate a Spring web application to annotation.
It is using SimpleUrlHandlerMapping + ParameterMethodNameResolver, so url will be /myjob.do?cmd=addNew . what is the easiest way to convert it to Annotation ? is it something like this ?
#RequestMapping("/myjob.do?cmd=addNew")
public ModelAndView addNew(....) throws Exception {
}
thanks
Assuming you have more than one cmd value:
#Controller
#RequestMapping("/myjob.do")
public class MyController {
#RequestMapping(params = "cmd=addNew")
public ModelAndView addNew(....) throws Exception {
}
}