Spring MVC, Form Submission not working - spring

Can some one help me with this?
My Controller class looks like this, and i have created the customer model class..
/**
* Handles requests for the application home page.
*/
#Controller
#RequestMapping("/customer")
public class CustomerController {
#RequestMapping(method = RequestMethod.GET)
public ModelAndView student() {
return new ModelAndView("customer", "command", new Customer());
}
#RequestMapping(value = "/addCustomer", method = RequestMethod.POST)
public String addStudent(#ModelAttribute Customer customer,
ModelMap model) {
model.addAttribute("customerName", customer.getCustomerName());
model.addAttribute("emailId", customer.getEmailId());
model.addAttribute("sex", customer.getSex());
return "customerDetails";
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>Customer Form Handling</display-name>
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>Customer</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/Customer/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Customer</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
JSP Pages
customer.jsp
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Customer Form Handling</title>
</head>
<body>
<h2>Customer Information</h2>
<form:form method="POST" commandName = "command" action="/addCustomer">
<table>
<tr>
<td><form:label path="customerName">customerName</form:label></td>
<td><form:input path="customerName" /></td>
</tr>
<tr>
<td><form:label path="emailId">emailId</form:label></td>
<td><form:input path="emailId" /></td>
</tr>
<tr>
<td><form:label path="sex">sex</form:label></td>
<td><form:input path="sex" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
customerDetails.jsp
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Customer Form Handling</title>
</head>
<body>
<h2>Customer Detail Information</h2>
<table>
<tr>
<td>CustomerName</td>
<td>${customerName}</td>
</tr>
<tr>
<td>emailId</td>
<td>${emailId}</td>
</tr>
<tr>
<td>sex</td>
<td>${sex}</td>
</tr>
</table>
</body>
</html>
Servlet-Context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<!-- <resources mapping="/resources/**" location="/resources/" /> -->
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.customerinfo.controller" />
</beans:beans>
But when I run this application in Tomcat Server.. The first url points to
localhost:8080/controller/.
If I append localhost:8080/controller/customer I get the first form page..
But once I click on submit.. it says page not found error.

It's a relative path problem. Your form action is /addCustomer (has / prefix), if you resolve it it's http://localhost:8080/addCustomer. What you wanted is probably http://localhost:8080/appname/customer/addCustomer.
In some cases simply changing it into customer/addCustomer might resolve it, but if your page can also be accessed by http://localhost:8080/appname/customer/ (pay attention to the trailing slash) then this could be a problem. The relative path will translate into http://localhost:8080/appname/customer/customer/addCustomer
Of course now you can think to just do /appname/customer/addCustomer and problem solved, but in fact you are now hard-coding the context path name. If one day the context path changes all this code will break.
One approach I like to use so my JSP can figure out the context path is by defining a root variable
<c:set var="root" value="${pageContext.request.contextPath}"/>
...
<form:form action="${root}/customer/addCustomer">

try as
<form:form method="POST" commandName = "command" action="addCustomer">
instead of
<form:form method="POST" commandName = "command" action="/addCustomer">

Related

Spring MVC Controller URL not mapped

I am trying to make simple project in Spring MVC,but getting this error :
WARNING: No mapping found for HTTP request with URI [/SpringMVCForm/login.htm] in DispatcherServlet with name 'springform'
HTTP Status 404 - Not Found.
Not able to get what I am missing. Please let me know.
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>SpringMVCForm</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>springform</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springform</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
</web-app>
springform-servlet.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="com.mvcform.*" />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
LoginController.java
package com.mvcform.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
#Controller
#RequestMapping("/login.htm")
public class LoginController {
#RequestMapping(method=RequestMethod.POST)
public ModelAndView processCredentials(#RequestParam("userId") String userId, #RequestParam("password") String password) {
String message = "Invalid Credentials";
if (userId != null && userId.length() >= 5) {
if (userId.equals(password)) {
//message = "Welcome " + userId + " !!!";
return new ModelAndView("redirect:/showform");
}
}
return new ModelAndView("index", "message", message);
}
}
index.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Spring MVC Form</title>
</head>
<body>
<h1> Index.jsp </h1>
<h1>Enter your user id and password</h1>
<form action="login.htm" method="post">
<table>
<tr>
<td> User Id </td>
<td> <input type="text" name="userId" /></td>
</tr>
<tr>
<td>Password </td>
<td> <input type="password" name="password" /></td>
</tr>
<tr>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
</table>
</form>
</body>
</html>
I think Spring is not able to scan base package: com.mvcform.*
Please let me know what I am missing here.
1) if you configured correct then you must check the json format which you sending to server to save it may be wrong (refere the urlenter link description here)
2) please check your controller controller doesn't have this url "URI [/SpringMVCForm/login.htm]" you have only /login.htm url.
Remove
#RequestMapping("/login.htm")
and keep only
#RequestMapping("/login")
in controller

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'configbean' available as request attribute

When try to run spring sample application using maven i have got the exception mentioned.
Here is my program
Firstpage1.jsp [present in Webcontent]
<html>
<head>
<title>Finacle data retriever</title>
</head>
<body>
<h2>Enter the configuration details</h2>
<form:form method="POST" action="/formexample/Configgen" commandName="configbean">
<table>
<tr>
<td><form:label path="tnu">Total number of Users</form:label></td>
<td><form:input path="tnu" /></td>
</tr>
<tr>
<td><form:label path="cnu">Concurrent number of Users</form:label></td>
<td><form:input path="cnu" /></td>
</tr>
<tr>
<td><form:label path="kat">Keep Alive Timeout</form:label></td>
<td><form:input path="kat" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
result.jsp [ Webcontent/WEB-INF/jsp]
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Result page</title>
</head>
<body>
<h2> Result page information</h2>
<table>
<tr>
<td>Total Number of users</td>
<td>${congibean.tnc}</td>
</tr>
<tr>
<td>Concurrent Number of users</td>
<td>${congibean.cnu}</td>
</tr>
<tr>
<td>Keep alive timeout</td>
<td>${congibean.kat}</td>
</tr>
</table>
</body>
</html>
**spring dependencies are present in maven dependencies.**
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<jsp-config>
<taglib>
<taglib-uri>/WEB-INF/spring-form.tld</taglib-uri>
<taglib-location>spring-form.tld</taglib-location>
</taglib>
</jsp-config>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/formex-servlet.xml</param-value>
</context-param>
<welcome-file-list>
<welcome-file>Firstpage1.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>formex</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>formex</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
formex-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<context:component-scan base-package="formexamplepack1"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
formexamplepack1 - package
configbean.java
package formexamplepack1;
public class configbean {
private int tuc;
private int cnu;
private int kat;
public int getTuc() {
return tuc;
}
public void setTuc(int tuc) {
this.tuc = tuc;
}
public int getCnu() {
return cnu;
}
public void setCnu(int cnu) {
this.cnu = cnu;
}
public int getKat() {
return kat;
}
public void setKat(int kat) {
this.kat = kat;
}
}
ConfigurationController.java
package formexamplepack1;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping(value = "/Configgen")
public class ConfigurationController {
#RequestMapping(method=RequestMethod.GET)
public String showform(ModelMap model) {
configbean configbean=new configbean();
model.addAttribute("configbean",configbean);
return "Firstpage";
}
#RequestMapping(method=RequestMethod.POST)
public String getdetails(#ModelAttribute("configbean")configbean configbean,ModelMap model,BindingResult bindingResult){
model.addAttribute("tnu", configbean.getTuc());
model.addAttribute("cnu", configbean.getCnu());
model.addAttribute("kat",configbean.getKat());
return "result";
}
}
Help me in resolving the below exception. I have gone through all the answers but not able to figure out. Using java 1.8 and spring jars latest [4.2.6]
tomcat- 7.0.68
Below is the exception
org.apache.jasper.JasperException: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'configbean' available as request attribute
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:556)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:472)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'configbean' available as request attribute
org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:144)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:168)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:188)
org.springframework.web.servlet.tags.form.LabelTag.autogenerateFor(LabelTag.java:130)
org.springframework.web.servlet.tags.form.LabelTag.resolveFor(LabelTag.java:120)
org.springframework.web.servlet.tags.form.LabelTag.writeTagContent(LabelTag.java:90)
org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:84)
org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:80)
org.apache.jsp.Firstpage1_jsp._jspx_meth_form_005flabel_005f0(Firstpage1_jsp.java:216)
org.apache.jsp.Firstpage1_jsp._jspx_meth_form_005fform_005f0(Firstpage1_jsp.java:152)
org.apache.jsp.Firstpage1_jsp._jspService(Firstpage1_jsp.java:105)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:439)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Try:
without ModelAttribute annotation
Binding Result direct after the command object
like:
#RequestMapping(method=RequestMethod.POST)
public String getdetails(configbean configbean, BindingResult bindingResult){
model.addAttribute("tnu", configbean.getTuc());
model.addAttribute("cnu", configbean.getCnu());
model.addAttribute("kat",configbean.getKat());
return "result";
}
you are trying to use ${congibean.tnc} in your result.jsp file , but you are not passing it as a model attribute . Instead you are trying to pass "tnu","cnu" and "kat" .
As a result it's giving you a jasper exception , as the compiler is unable to find any model attribute called "configbean" .
To solve this either pass only "configBean" as your model Attribute in the getdetails() method , or change your result.jsp file to use only "${tnc}", "${cnu}" and "${kat}"

404 error on a simple spring mvc aplication

Project Folder structureI have gone through most of the question on this site related to 404 resource not found error on Sring mvc application. I tried all solutions and still ended up with no resolution for over two days. I am new to spring MVC and tried out a sample application from the link
Simple Spring MVC app
My code is exactly as mentioned on the site above. But no matter what change I make, still get a 404 error.
Here's my web.xml section
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>abc</display-name>
<welcome-file-list>
<welcome-file>/</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>sdnext</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name><param-value>/WEB-INF/config/sdnext-servlet.xml</param-value></init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>sdnext</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
The controller file,
EmployeeController.java
#Controller
public class EmployeeController {
#RequestMapping(value = "/employee", method = RequestMethod.GET)
public ModelAndView employee() {
return new ModelAndView("employeeForm", "command", new Employee());
}
#RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
public String addEmployee(#ModelAttribute("SpringWeb")Employee employee, ModelMap model) {
model.addAttribute("name", employee.getName());
model.addAttribute("age", employee.getAge());
model.addAttribute("empId", employee.getEmpId());
model.addAttribute("salary", employee.getSalary());
return "employeeDetail";
}
}
where Employee is my POJO class with setter and getter methods.
Here is my employeeForm.jsp
<form:form action="/addEmployee" method="POST">
<table><tbody>
<tr> <td><form:label path="empId">Employee :</form:label></td> <td><form:input path="empId"></form:input></td> </tr>
<tr> <td><form:label path="name">EmployeeName:/form:label></form:label></td> <td><form:input path="name"></form:input></td> </tr>
<tr> <td><form:label path="age">Employee Age:</form:label></td> <td><form:input path="age"></form:input></td> </tr>
<tr> <td><form:label path="salary">Employee Salary:</form:label></td> <td><form:input path="salary"></form:input></td> </tr>
<tr> <td colspan="2"><input type="submit" value="Submit"/> </td> </tr>
</tbody></table>
</form:form>
here is my sdnext-servlet.xml
<context:component-scan base-package="com.dineshonjava.emp.controller">
</context:component-scan>
<context:annotation-config/>
<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="viewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
You are doing a fundamental mistake. Say your project name is bunbub-proj, so the url to access is localhost:8080/bunbub-proj. When you POST to /addEmployee, you are actually hitting localhost:8080/addEmployee instead of localhost:8080/bunbub-proj/addEmployee
The fix is to simply append a . to all of your links/urls. E.g. <form:form action="./addEmployee" method="POST">
Note: Browser considers localhost:8080 as the base url or the host
url.

Spring MVC - app with no default index page and textfield not showing

All,
A Spring newbie here.
I am trying to build a spring mvc(Sping 4.1.6 release) app. This app does not have a default landing page(like index.jsp, I have removed index.jsp from my app). This app will be called from another app by URL links or directly typing the path. My issue is I am not able to get this working. When I type localhost:8080/app/user.jsp(this is in WEB-INF/jsp folder) or localhost:8080/app/jsp/user.jsp(I would prefer not to use this path though).
Another question: I tweaked the app to have an index.jsp redirecting to user.jsp in the WEB-INF folder(not the WEB-INF/jsp) and the Controller #RequestMapping("/"), the user.jsp loads but the textbox is not displayed.
My web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>selfsrvc</display-name>
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
my spring-dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.company"></context:component-scan>
<mvc:annotation-driven />
<mvc:resources mapping="/**" location="/" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value="/WEB-INF/jsp/" />
<property name = "suffix" value=".jsp" />
</bean>
<bean class="org.springframework.context.support.ResourceBundleMessageSource"
id="messageSource">
<property name="basename" value="messages" />
</bean>
My Controller
#Controller
#RequestMapping("/user.jsp")
public class userController {
#RequestMapping(method = RequestMethod.GET)
public String initForm(Model model){
user user = new user();
model.addAttribute("user", user);
System.out.println("IIIIIIIIInside user Controller");
return "user";
}
}
My jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form:form method="POST" commandName="user">
<table>
<tr>
<td>Enter your name:</td>
<td><form:input path="user" /></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Submit"></td>
</tr>
<tr>
</table>
</form:form>
</body>
</html>
I am not sure what I am missing in both the scenarios. Thanks.
EDIT: The suggestion by minion solved my issue. Thanks.
There are couple of issues or changes you need to do. Here is the Gist of the issue :
Your spring servlet is mapped to / and the requested url is of the
pattern *.jsp. So it would never hit the controller that you wrote.
So change your controller to like one below.
#Controller
#RequestMapping("/user")
public class userController {
#RequestMapping(method = RequestMethod.GET)
public String initForm(Model model){
user user = new user();
model.addAttribute("user", user);
System.out.println("IIIIIIIIInside user Controller");
return "user";
}
Use the url localhost:8080/app/jsp/user to hit the controller.
}

Need help on Spring MVC hello world

I am trying to learn Spring MVC on NetBeans 8.0.2 using Hibernate and frankly I am stuck. Any help is appreciated. I am only trying to do a very simple "hello world" type site.
Someone would on the first page hit a submit button and the resulting page would have a list of values from the DB. Sounds pretty simple right?
I've included 5 very short files here that will hopefully help you to help me if you are so inclined.
"web.xml", "dispatcher-servlet.xml","index.jsp", "TeamController.java", "secondView.jsp"
The way I understand how Spring MVC should work, using my files, is as follows...
1) Running the project from NetBeans, the index.jsp file is brought up.
This happens because the Web.xml is consulted, which has the following line...
"<welcome-file>redirect.jsp</welcome-file>"
once the redirect.jsp is consulted, we see that it has the following...
"<% response.sendRedirect("index.htm"); %>"
so with that redirect we go back to the web.xml which has the following...
"<servlet-name>dispatcher</servlet-name>"
"<url-pattern>*.htm</url-pattern>"
so with that request coming in as index.htm it is to be handled by the dispatcher servlet.
In the dispatcher servlet's config file, the view resolver will add the following...
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
so index.htm gets changed to /WEN-INF/jsp/index.jsp and that page is brought up.
2) At this point the index.jsp is brought up. The only thing in this file is a form with a submit button. The intent is just to have someone press the button and info from the DB is returned on screen. I have Hibernate as part of this web project and I have created a java class "Team.java" based on a DB table "Team". It is populated with a few records.
Currently what I am seeing is that once the index.jsp comes up and I hit submit, it is giving a 404.
This is the URL shown for the form
"host:port/HelloWebFour/index.htm "
if I do a view source it shows it as the index.jsp. When I hit submit it gives a 404 with this url
"host:port/HelloWebFour/team? "
btw, "HelloWebFour" is the name of my project in NetBeans.
I am not sure what is happening, if my understanding is right or if I need to add anything. any help is appreciated...
The very short code files are below...
"Web.xml"
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>redirect.jsp</welcome-file>
</welcome-file-list>
</web-app>
"dispatcher-servlet.xml"
<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?xml version="1.0" encoding="UTF-8"?> -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd" xmlns:context="http://www.springframework.org/schema/context">
<context:component-scan base-package="testnew1" />
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<!--
Most controllers will use the ControllerClassNameHandlerMapping above, but
for the index controller we are using ParameterizableViewController, so we must
define an explicit mapping for it.
-->
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index.htm">indexController</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<!--
The index controller.
-->
<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
</beans>
"index.jsp"
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>index.jsp - the submit page</title>
</head>
<body>
<h2>Hit submit to get DB information</h2>
<form:form method="GET" action="/HelloWebFour/team">
<table>
<tr>
<td>
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
"TeamController.java"
package testnew1;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class TeamController {
#RequestMapping(value = "/team", method = RequestMethod.GET)
public String getTeam(#ModelAttribute("SpringWeb") Team team,
ModelMap model) {
model.addAttribute("city", team.getCity());
model.addAttribute("state", team.getState());
model.addAttribute("nickname", team.getNickname());
return "secondView";
}
}
"secondView.jsp"
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>secondView.jsp - the results page</title>
</head>
<body>
<h2>Database Information</h2>
<table>
<tr>
<td>City</td>
<td>${city}</td>
</tr>
<tr>
<td>State</td>
<td>${state}</td>
</tr>
<tr>
<td>Nickname</td>
<td>${nickname}</td>
</tr>
</table>
</body>
</html>
As far I see you Submiting to "/HelloWebFour/team but your only request handler method is mapped to /team, try to submit to just /team. I don't use any prefix on Dispatcher mapping so can be a missed .htm on url combining with the unknown request url /HelloWebFour/team.
Then if one of above solutions work, your method may fail because you are expecting a modelAttribute named as "SpringWeb" of type Team, but your form actually dont post any data and it's modelAttribute is mapped to "command", the default value, so removing this can possibly remove a further error if occurs.

Resources