How Spring maps URL and where to read more about it - java

I'm new to Spring. I'm trying to learn it by doing instead of reading. So I found some stuff which is confusing. But it works. I want to know why and how?
#Controller
#RequestMapping("/ok")
public class MyController {
#RequestMapping(value = "/ok", method = RequestMethod.GET)
public ModelAndView findAllAccounts() throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("account");
mav.addObject("someText", "Listing all accounts!");
return mav;
}
#RequestMapping(value="/ok/{accountId}", method = RequestMethod.GET)
public ModelAndView findAccount(#PathVariable int accountId, Model model) {
ModelAndView mav = new ModelAndView();
mav.setViewName("account");
mav.addObject("someText", String.format("Showing account %d", accountId));
return mav;
}
}
For above code I found that.
working Get request url : http://localhost:8080/ok/
working Get request url : http://localhost:8080/ok/ok/888
But I was expecting url : http://localhost:8080/ok/ok/ should also work. But it doesn't work. Why? If http://localhost:8080/ok/ok/888 works why http://localhost:8080/ok/ok/ doesn't work?
Also when I deploy it in tomcat. It only works if named ROOT.war. If I change to XYZ.war, it doesn't work. Why?

The http://localhost:8080/ok/ok/ does not work as it treats your last ok as your accountId and it fails conversion to an integer. The best documenation is the javadoc
Your question about tomcat - I believe it should be fine with another name, only then you would have to access it as http://localhost:8008/XYZ/

Related

Failed to load resource: the server responded with a status of 405 | Spring MVC

Im facing a an issue while Im adding a method to the controller class with #RequestMapping(method = RequestMethod.POST) annotation. The issue is when I add this method and start application. Application unable to load resources (css,JS etc). On the browser I get:
Failed to load resource: the server responded with a status of 405 (Method Not Allowed)
and on the Run logs I get this message:
org.springframework.web.servlet.PageNotFound handleHttpRequestMethodNotSupported
WARNING: Request method 'GET' not supported
When I remove this method from the controller class, all works fine. Dont know why is this happening. Im sure its nothing to do with Configuration or resources in Dispatcher Servlet mapping because without this method every thing works perfectly fine.
I need to use this method because of some business requirement, which otherwise is not possible.
Can any body help me in Identifying where the issue is.
#Controller
public class InvoiceController
{
#RequestMapping(value = "/index", method = RequestMethod.GET)
public ModelAndView adminPage() {
String username;
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
username = auth.getName(); //get logged in username
username.toUpperCase();
// Logic to build menue based on the Role of the user.
HashMap hm = new HashMap();
OrderItems od = new OrderItems();
ModelAndView model = new ModelAndView();
model.addObject("usr", username);
//Set the object for Menue Links on the Page
model.addObject("mnue", hm);
model.setViewName("index");
model.addObject("odi",od);
return model;
}
#RequestMapping(method = RequestMethod.POST)
public String save(HttpServletRequest request,
HttpServletResponse response,
Model model)
{
System.out.println("Im here in Genaric Post Method");
return null;
}
}
Please also note that Im using Spring Security configurations. Is there anything to do with Security? Or there is some issue with Controller Class configuration.
Thanks in advance for your anticipation.
Regards,
D Kamran
Add endpoint url value to request mapping
#RequestMapping(value="/index", method = RequestMethod.POST)
This happens because Post method declared mapped to all paths as both Method and Controller class don't have that value

How to put an attribute in the URL

I have gone through url mapping topics but I couldn't find a way to solve my problem despite I'm sure more than one has had this kind of setback. Maybe it is quite simple.
I have a login process, when the login form is submited (user and password)
localhost:8080/library/login the controller leads to the main page of the user, All I would like to do is to set the username in the URL like localhost:8080/library/{username}/mainPage
It seems it has nothing to do with PathVariable or RequestParam as I tried many ways to go through this however 400 error is all I got.
#RequestMapping(value="/mainPage", method = RequestMethod.POST)
public ModelAndView showMainPage(#Valid #ModelAttribute("loginUserForm") LoginUserForm loginUserForm, ModelAndView modelAndView, BindingResult result, final RedirectAttributes attributes){
logger.info("Showing login page.");
modelAndView.addObject(loginUserForm);
attributes.addFlashAttribute("loginUserForm", loginUserForm);
if(result.hasErrors()){
modelAndView.setViewName("login");
return modelAndView;
}
modelAndView.setViewName("mainPage");
return new ModelAndView("redirect:/mainPage");
}
And this leads to another controller class
#RequestMapping(value = "/{userName}/mainPage", method = RequestMethod.GET)
public #ResponseBody ModelAndView showMyArea(ModelAndView model, #ModelAttribute("loginUserForm") LoginUserForm loginUserForm, #PathVariable("email")String email){
logger.debug("Showing mainPage");
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("mainPage");
return modelAndView;
}
What should I change or what do I miss? I guess the value, but I do not why
I came up with this wrongly:
#RequestMapping(value="/{userName}/mainPage", method = RequestMethod.POST)
public ModelAndView showMainPage(#Valid #ModelAttribute("loginUserForm") LoginUserForm loginUserForm, ModelAndView modelAndView, BindingResult result, #PathVariable("userName") String userName){
Thanks a ton!

Display exception message handled by Spring using JSP

I'm new in Spring and also in JSP. I'm working in the project and I needed to create a page where application will be redirected in case of specific exceptions.
I have service's method which throws one of exceptions. This method is called in one of our page controller with #RequestMapping annotation. So to redirect to specific error page, I created two methods with #ExceptionHanlder which handle this exceptions in this controller. How it looks:
#ExceptionHandler(IllegalStateException.class)
public ModelAndView handleIllegalStateException (IllegalStateException ex) {
ModelAndView modelAndView = new ModelAndView("redirect:/error");
modelAndView.addObject("exceptionMsg", ex.getMessage());
return modelAndView;
}
But there wasn't enough. I also need to create ErrorPageController:
#Controller
#RequestMapping("/error")
public class ErrorPageController {
#RequestMapping(method = RequestMethod.GET)
public ModelAndView displayErrorPage() {
return new ModelAndView("error");
}
}
And now works displaying error page. But my problem is, that I can't display error message in JSP...
I have:
<h3>Error page: "${exceptionMsg}"</h3>
But I don't see a message ;/ Instead of it, I see message in URL:
localhost/error?exceptionMsg=Cannot+change+participation+status+if+the+event+is+cancelled+or+it+has+ended.
And it's wrong because in URL I want to have only an "localhost/error" and nothing more. This message I want to display in JSP.
To fix both of your issues (show the message, and have the proper url) you should in original code change you exception handler method to e.g.
#ExceptionHandler(IllegalStateException.class)
public RedirectView handleIllegalStateException(IllegalStateException ex, HttpServletRequest request) {
RedirectView rw = new RedirectView("/error");
FlashMap outputFlashMap = RequestContextUtils.getOutputFlashMap(request);
if (outputFlashMap != null) {
outputFlashMap.put("exceptionMsg", ex.getMessage());
}
return rw;
}
Why? If you want your attributes to persist through redirect, you need to add them to flash scope. The code above uses the FlashMap, from the docs
A FlashMap is saved before the redirect (typically in the session) and
is made available after the redirect and removed immediately.
If it were to be a normal controller method, you could have simply added RedirectAttributes as an argument, but on #ExceptionHandler methods, the arguments of RedirectAttributes are not resolved, so you need to add the HttpServletRequest and use the RedirectView.
You have to change ModelAndView to:
#ExceptionHandler(IllegalStateException.class)
public ModelAndView handleIllegalStateException (IllegalStateException ex) {
ModelAndView modelAndView = new ModelAndView("error");
modelAndView.addObject("exceptionMsg", ex.getMessage());
return modelAndView;
}
And have this part in error.jsp:
<h3>Error page: "${exceptionMsg}"</h3>

Java Spring Controller mapped properly, but server returns 302 instead of 200

I have following controller
#Controller
#RequestMapping("/adwords")
public class AdwordsController
{
#RequestMapping(method = RequestMethod.GET)
public ModelAndView showForm(#ModelAttribute(Const.ADWORDS_COMMAND) AdwordsCommand adwordsCommand, BindingResult result)
throws HttpSessionRequiredException
{
this.checkSessionExpired();
ModelAndView mav = new ModelAndView("adwords/adwordsRequest");
if(adwordsCommand == null)
adwordsCommand = new AdwordsCommand();
User user = this.getUser();
adwordsCommand.setEmail(user.getEmail());
mav.addObject(Const.ADWORDS_COMMAND, adwordsCommand);
return mav;
}
}
That is mapped properly:
13:17:49,276 INFO RequestMappingHandlerMapping:185 - Mapped "{[/adwords],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.ModelAndView pl.ifirma.domeny.controller.adwords.AdwordsController.showForm(java.lang.String,org.springframework.validation.BindingResult) throws org.springframework.web.HttpSessionRequiredException
But when I type URL in browser I get 302 code and server redirects immediately to main page of application. Can anyone help? Why server does not return 200 or at least 404?
Adam
#Comments:
Such code acts exactly the same.
#Controller
#RequestMapping("/adwords")
public class AdwordsController
{
#RequestMapping(method = RequestMethod.GET)
public ModelAndView showForm(#ModelAttribute(Const.ADWORDS_COMMAND) AdwordsCommand adwordsCommand, BindingResult result)
{
ModelAndView mav = new ModelAndView("adwords/adwordsRequest");
if(adwordsCommand == null)
adwordsCommand = new AdwordsCommand();
User user = this.getUser();
adwordsCommand.setEmail(user.getEmail());
mav.addObject(Const.ADWORDS_COMMAND, adwordsCommand);
return mav;
}
}
I wonder if this weird redirection could be caused by some spring configuration, but where to check it? And it is only place in project where problem occurs.
Solved. There was a hidden redirect in a view...

How to redirect to another site in Spring MVC JavaEE

I've been googling a while and I couldn't find a clear answer or documentation about this specific method.
I want to redirect to another site, like stackoverflow.com using this method... But I don't know how to do it. Any help will be appreciated.
#RequestMapping(value = "/redirectTravelocity", method = RequestMethod.GET)
private ModelAndView processForm()
{
ModelAndView modelAndView = new ModelAndView( "redirect:stackoverflow.com" );
Map<String, Object> model = modelAndView.getModel();
model.put( "error", "this.is.my.error.code" );
return new ModelAndView( "redirect:stackoverflow.com", model );
}
It doesn't work, it redirects within my site and it crashes... I know this is stupid but I don't know how to do it.
Here is one way to do it:
#RequestMapping(value = "/redirectTravelocity", method = RequestMethod.GET)
private String processForm()
{
return "redirect:http://stackoverflow.com";
}
change redirect:stackoverflow.com to redirect:http://stackoverflow.com

Categories

Resources