Spring MVC not returning webpage - spring-mvc

In my jsp form, I get the value of month and year from the user, and return a webpage with relevant values. Here is my form:
<div class="modal-content animate" >
<div class="imgcontainer">
<span onclick="document.getElementById('month').style.display='none'" class="close" title="Close Modal">×</span>
<img src="doctor.jpg" alt="Avatar" class="avatar">
</div>
<form id="differentMonth" action="differentMonth" method="post">
<select name="month" multiple="multiple">
<%
int i;
for(i=1;i<=12;i++){
out.print("<option value=" + i +">" + Month.of(i) + "</option>");
}
%>
</select>
<select id="year" multiple="multiple">
<% int year1 = Integer.parseInt(Year.now().toString());
for(i=0;i<=10;i++){
out.print("<option value=" + i +">" + ( year1) + "</option>");
year1=year1-1;
}
%>
</select>
<input type="submit" name="submitted" value="submit" />
</form>
</centre>
</div>
</div>
</div>
This form takes the value from the user. In the dispatcher,
#RequestMapping(value = "/differentMonth", method = RequestMethod.POST)
public String differentMonth(#Validated DifferentMonth mon, Model model) {
System.out.println("In controller");
AccessDatabase ac = new AccessDatabase(AccessDatabase.id);
System.out.println(AccessDatabase.id);
ac.setStatusOfMonth(AccessDatabase.id,Integer.toString(mon.getMonth()),Integer.toString(mon.getYear()));
System.out.println(user.getUserName()+" "+mon.getMonth()+" "+mon.getYear());
model.addAttribute("database", ac);
return "user"; // Only this is important
}
The 'user' is also well defined, as this div is called from user.jsp itself. It worked the first time. Issue is when user is return by the servlet the second time
Here is the error:
HTTP Status 500 – Internal Server Error
Type Exception Report
M
essage Request processing failed; nested exception is java.lang.NullPointerException
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Root Cause
java.lang.NullPointerException
com.PricolAttendance.spring.controller.HomeController.differentMonth(HomeController.java:95)
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.base/java.lang.reflect.Method.invoke(Method.java:567)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Note The full stack trace of the root cause is available in the server logs.
Apache Tomcat/7.0.99
Doesnt look like there is a logical error, as user.jsp works fine at first.
Please help.

In your code there are errors on mapping the form with the bean.
inside jsp add this on top:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
Write you open tag for form like this. ModelAttribute attribute map the element of the form with your bean.
<form id="form_id" action="url" method="post" modelAttribute="bean_name">
Add your form elements. the attribute path map the element inside form with the attribute of the bean.
<form:select id="sel_id" multiple="multiple" path="bean_attribute_mapped" />
Inside bean class put your annotations for validations.
Write the signature of your endpoint. #Valid enable validation and #ModelAttribute map the parameter with your bean.
#RequestMapping(value = "/differentMonth", method = RequestMethod.POST)
public String differentMonth(#Valid #ModelAttribute DifferentMonth mon, Model model) {

Related

No mapping found for HTTP request with URI - No dispatcherservlet / servletmapping error

I know this is a common question but I'm getting desesperated here, Im pretty newbie and have been stuck with this for a long time now... I know this is not a DispatcherServlet or Servlet Mapping error as I'm working on a really big project that has everything working already.
What I need to do is add a form on an already existing jsp page, here is what I have
CONTROLLER:
#Controller
#RequestMapping("/messaging")
public class MessagingController {
#GetMapping
public String messagingView(Principal principal, Model model) throws ServiceException {
model.addAttribute("messagingInformation", new MessagingInformation());
return foo; -> this returns me to the main jsp where I'm creating the form
}
#PostMapping(value = "/submitInformation") -> I've also tried with #RequestMapping(value = "/submitInformation", method = RequestMethod.POST)
public String submitInformation(#ModelAttribute(value = "messagingInformation") #Valid MessagingInformation messagingInformation) {
return "redirect:/messaging"; -> shouldn't this redirect me to the main jsp?
}
}
JSP:
<form:form action="messaging/submitInformation" modelAttribute="messagingInformation" method="POST">
<div class="row col-sm-12 margin-top-container">
<div class="col-sm-4">
<span class="titles-select-box uppercase-text">RECEIVER</span>
<input name="receiver" type="email" id="receiverId" name="receiverName"
placeholder="Receiver" multiple>
</div>
</div>
<div class="col-sm-12 no-padding-left">
<div class="button-container pull-right">
<input type="submit" value="Send" class="btn btn-default"
id="sendButton" />
</div>
</div>
</form:form>
I'm mainly getting --No mapping found for HTTP request with URI [/foo/messaging/submitInformation] in DispatcherServlet -- I've asked around and I shouldn't add nothing to any cofiguration file or anything, clearly it's something wrong on my side but I can't see it
Leaving this in case anyone finds out... I was requiered to do a manual build so the java changes would show up. This is done through Projects -> Build All

How to pass multiple form parameter in "th:action" using themleaf

I am trying to pass parameter in th:action
<form class="form-inline" th:object="${search}" method="get" action="search.html" th:action="#{'/hotels/'+${search.location}+'/'+${search.adults}+'/'+${search.dateCheckOut}+'/'+${search.dateCheckIn}}" id="search-hotel-form">
<select class="selectpicker form-control input-lt" th:field="*{location}" id="city">
<option value="delhi">Delhi</option>
</select>
<input type='text' th:field="*{dateCheckIn}" id="datetimepicker1" />
<input type='text' th:field="*{dateCheckOut}" id="datetimepicker2" />
</form>
then Spring MVC contoller part
#RequestMapping(value = "/hotelsparam/{dateCheckIn}/{dateCheckOut}/{location}", method = RequestMethod.POST)
public ModelAndView searchHotel(#PathVariable("dateCheckOut") Date dateCheckOut, #PathVariable("dateCheckIn") Date dateCheckIn,#PathVariable("location") String location, BindingResult bindingResult) throws ParseException {....
//remove implemntation to make it precise
}
but getting error is
HTTP Status 500 - Request processing failed; nested exception is java.text.ParseException: Unparseable date: "null"
URL Part seem like this
http://localhost:8080/hotels/null/0/null/null?location=delhi&dateCheckIn=04%2F07%2F2015+09%3A00&dateCheckOut=04%2F07%2F2015+20%3A00&adults=1

MVC + Forms: Post error

I am getting the following error whenever I try to do a simple form post in my MVC website.
Either BinaryRead, Form, Files, or InputStream was accessed before the internal storage was filled by the caller of HttpRequest.GetBufferedInputStream.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Either BinaryRead, Form, Files, or InputStream was accessed before the internal storage was filled by the caller of HttpRequest.GetBufferedInputStream.
My sample form and actions are pretty basic...
#using (Html.BeginForm("Create", "Form"))
{
<div class="row action">
<div class="row">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
</div>
<input type="submit" id="save" class="btn" value="Save"/>
<input type="button" id="cancel" class="btn" value="Cancel"/>
</div>
}
And my Controller action is even more basic...
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Please share your route.config file that might help solving this problem.
Just in case also try removing the perimeters from Html.BeginForm() remove the name of the action and controller. As MVC has strong naming systems because of which we don't need to add that info.
if above doesn't solve your issue Share your route file.

Spring 3.1 MVC and Security: both login and registration form (multiple forms) on same page get submitted

I'm using Spring (3.1), Spring MVC (3.1) and Spring Security (3.0) in combination and I've put together a single JSP page that has two forms on it; One is a form to login and the other is a form to register (i.e. create a new user).
For the register form, I use the Spring form tags, backed up by a controller to handle the request but for the login form I don't bother with the Spring form tags as I don't believe they're needed. There is also no controller that I need to write to handle the form submission as Spring Security takes care of authenticating so long as the request is submitted to j_spring_security_check.
The register form is working fine but the login form is a problem. It seems that when I click the submit button on the login form, the registration form is also submitted, or at least Spring thinks I'm trying to submit that form. Here is the JSP:
<form id="loginform" method="POST" action="<c:url value='j_spring_security_check'/>">
<label for="existing_email">Email:</label>
<input name="j_username" id="existing_email" type="text" value="${SPRING_SECURITY_LAST_USERNAME}" />
<label for="existing_password">Password:</label>
<input name="j_password" id="existing_password" type="password" />
<input id="login-form-submit" type="submit" value="Sign in" />
</form>
<form:form id="registrationform" modelAttribute="user" method="POST" action="register">
<form:label path="username" for="email">Email:</form:label>
<form:input path="username" name="username" id="email" type="text" />
<form:errors path="username" cssClass="formError" />
<form:label path="password" for="password">Password:</form:label>
<form:input path="password" name="password" id="password" type="password" />
<form:errors path="password" cssClass="formError" />
<input id="registration-form-submit" type="submit" value="Sign up" />
</form:form>
Notice that form tags for the input of type submit are not present and this seems to be a normal thing to do in the examples I've seen. Adding form tags to the submit button I guess doesn't make sense as it doesn't map to anything on the target object (user in this case).
When I click the "Sign in" button I get the following exception:
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/project1] threw exception [An exception occurred processing JSP page /WEB-INF/views/registration.jsp at line 29
28: <form:form id="registrationform" modelAttribute="user" method="POST" action="register">
29: <form:label path="username" for="username">Username:</form:label>
30: <form:input path="username" name="username" id="username" type="text" />
31: <form:errors path="username" cssClass="formError" />
32:
Stacktrace:] with root cause
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'user' available as request attribute
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:141)
This I recognise from cases where you forget to include the modelAttribute attribute in form:form, but of course I don't want to submit this form to my controller.
I have a feeling there is a mistake I'm making or a simple solution. Can anyone recommend a way around this or perhaps a different approach?
Here is the controller method that handles requests to register in case that's needed:
#RequestMapping(value = "**/register", method = RequestMethod.POST)
public String registerUser(#ModelAttribute("user") #Validated User user, BindingResult errors, ModelMap model) {
if (errors.hasErrors()) {
return "registration";
}
// Other stuff then...
return "profile"
}
If you are using "user" modelAttribute in form tag then a non-null request attribute must be present with name "user".
One way to add that in request attribute is what you did in your answer above. Other ways are:
(1) Add in ModelMap:
#RequestMapping(value = "/loginfailed", method = RequestMethod.GET)
public String loginFailed(ModelMap model) {
model.addAttribute("user", new User());
model.addAttribute("error", "true");
return "registration";
}
(2) Add in request scope (Using WebRequest or HttpServletRequest):
#RequestMapping(value = "/loginfailed", method = RequestMethod.GET)
public String loginFailed(ModelMap model, WebRequest webRequest) {
webRequest.setAttribute("user", new User(), WebRequest.SCOPE_REQUEST);
model.addAttribute("error", "true");
return "registration";
}
(3) Use #ModelAttribute on method:
#ModelAttribute("user")
public User user() {
return new User();
}
Please also see Using #ModelAttribute on a method and Using #ModelAttribute on a method argument
Also note that you don't have to use type attribute. See form:input and form:password.
I think the problem is specifically when a login fails and the same page is served up, albeit on a different URL path and so through a different controller method. Therefore my original suspicion that the issue is that both forms are submitted may be something of a red herring, though I still don't fully understand what's going on and that may yet have something to do with it. In any case, this is what corrected the problem for me:
I had a controller method that originally looked like this:
#RequestMapping(value = "/loginfailed", method = RequestMethod.GET)
public String loginFailed(ModelMap model) {
model.addAttribute("error", "true");
return "registration";
}
In the Spring Security context I specify /loginfailed as the path to go to by default if a login attempt fails. This is where it seems the user object is needed so if I alter the signature as follows it all works:
#RequestMapping(value = "/loginfailed", method = RequestMethod.GET)
public String loginFailed(#ModelAttribute("user") User user, BindingResult errors, ModelMap model) {
model.addAttribute("error", "true");
return "registration";
}
Any comments/clarification welcome from others.

Spring 3 MVC error: Neither BindingResult nor plain target object for bean name 'user' available

I know this issue might have been addressed elsewhere but I'm unable to find a satisfactory solution to my problem. Btw, I'm working with spring 3.0.2
Login.jsp
<form:form id="_LoginForm" name="LoginForm" modelAttribute="user" action="login" method="POST">
<form:input path="username" value=""/>
<form:input path="password" value=""/>
<input type="submit" value="Submit"/>
LoginController.java
#RequestMapping(value="login", method=RequestMethod.POST)
public String login(#ModelAttribute("user") User user, BindingResult result) {
System.out.println("recd request");
return null;
}
When I try to access the login.jsp page, I get the following error:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'user' available as request attribute
at org.springframework.web.servlet.support.BindStatus.(BindStatus.java:141)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:174)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:194)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getName(AbstractDataBoundFormElementTag.java:160)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.writeDefaultAttributes(AbstractDataBoundFormElementTag.java:123)
at org.springframework.web.servlet.tags.form.AbstractHtmlElementTag.writeDefaultAttributes(AbstractHtmlElementTag.java:409)
at org.springframework.web.servlet.tags.form.InputTag.writeTagContent(InputTag.java:140)
at org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:102)
Can you please provide your RequestMethod.GET method in the controller?
Just want to make sure you are adding the modelAttribute in the GET method as well.
I added the the following method to make this work, though I feel there must be a better way to get this working without having to write a setup method everytime.
applicationContext.xml
<mvc:view-controller path="/" view-name="index" />
index.jsp
<jsp:forward page="index.action"/>
LoginController.java
#RequestMapping(value="index.action", method=RequestMethod.GET)
public String setupLogin(Map<String, Object> modelMap) {
modelMap.put("user", new User());
return "Login";
}

Resources