404 error on a simple spring mvc aplication - spring

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.

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}"

Spring MVC, Form Submission not working

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">

Spring MVC form validation not working

I am using Spring 4.
My form contains the following variables:
#NotNull
#Email
private String email;
#NotNull
private String firstName;
#NotNull
private String lastName;
#Digits(fraction = 0, integer = 10)
private String phoneNo;
#NotNull
private String role;
My controller:
#Controller
#RequestMapping("/user")
public class UserController {
#RequestMapping(value = "/add", method = RequestMethod.POST)
public ModelAndView add(#ModelAttribute("user") #Valid UserBean user, BindingResult result) {
String message;
if (result.hasErrors() && user != null)
return new ModelAndView("userAdd");
else {
userService.addUser(user);
message = "Successfully added user";
}
return new ModelAndView("success", "message", message);
}
#RequestMapping(value = "/register")
public ModelAndView register(#ModelAttribute("user") UserBean user, BindingResult result) {
List<String> roles = new ArrayList<String>();
roles.add("Receiver");
roles.add("Resolver");
roles.add("Logger");
Map<String, List<String>> model = new HashMap<String, List<String>>();
model.put("roles", roles);
return new ModelAndView("userAdd", "model", model);
}
}
My jsp:
<c:url var="userAdd" value="user/add.do" />
<sf:form method="post" action="${userAdd}" modelAttribute="user">
<table>
<tr>
<td>First Name</td>
<td><sf:input path="firstName" /><br /> <sf:errors
path="firstName" cssClass="error" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><sf:input path="lastName" /><br /> <sf:errors
path="lastName" cssClass="error" /></td>
</tr>
<tr>
<td>Email</td>
<td><sf:input path="email" /><br /> <sf:errors
path="email" cssClass="error" /></td>
</tr>
<tr>
<td>Phone No.</td>
<td><sf:input path="phoneNo" /><br /> <sf:errors
path="phoneNo" cssClass="error" /></td>
</tr>
<tr>
<td>Role</td>
<td><sf:select path="role" items="${model.roles}" /><br /> <sf:errors
path="role" cssClass="error" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</sf:form>
When I leave the the inputs blank, the form does not validate and does not throw any error. The BindingResult does not have any errors in it.
My libraries are:
My dispatcher-serlvet.xml is:
<?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/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">
<!-- Scans for annotated #Controllers in the classpath -->
<context:component-scan base-package="com.mj.cchp.controller">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<bean id="myBeansValidator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
<mvc:annotation-driven validator="myBeansValidator" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
My applicationContext is:
<?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.xsd">
<!-- Scans for annotated #Controllers in the classpath -->
<context:component-scan base-package="com.mj.cchp">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.ibm.db2.jcc.DB2Driver" />
<property name="url" value="jdbc:db2://172.16.2.181:60000/CCHP" />
<property name="username" value="db2inst1" />
<property name="password" value="db2inst1" />
</bean>
</beans>
My web.xml is:
<?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>CCHP</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/application-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>
</web-app>
You need to add
<bean id="myBeansValidator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
and
<mvc:annotation-driven validator="myBeansValidator">
and
<!-- Hibernate Validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.2.0.Final</version>
</dependency>
Should work!
I had a similar problem and in my case it was sufficient to just add dependency for hibernate validator: org.hibernate:hibernate-validator:5.2.4.Final.
The validation is done by LocalValidatorFactoryBean bean and documentation about it comes handy (here).
Yet at the same time it is worth mentioning that you do not have to instantiate LocalValidatorFactoryBean explicitly as long as you use #EnableWebMvc annotation : http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-config-validation
By default use of #EnableWebMvc or
automatically registers Bean Validation support in Spring MVC through
the LocalValidatorFactoryBean when a Bean Validation provider such as
Hibernate Validator is detected on the classpath.
Hope this helps.
I faced the same problem. I resolved by adding below statement in dispatcher-serlvet.xml file.
<mvc:annotation-driven />
I'm not sure whether you have found ways to fix this. I am facing the same issue as well. and I managed to solve it. The problem with my setting is totally manual and I'm doing big mistake by placing the whole hibernate-validator-5.1.3.Final-dist.zip inside lib folder.
So what I did is I get this 6 files inside "hibernate-validator-5.1.3.Final-dist.zip" in dist folder and place this with web app lib.
classmate-1.0.0.jar
hibernate-validator-5.1.3.Final.jar
javax.el-2.2.4.jar
javax.el-api-2.2.4.jar
jboss-logging-3.1.3.GA.jar
validation-api-1.1.0.Final.jar
This fixed my issue.
i also faced the same issue where my entire code was properly written.
The problem was the different version of jar files that i was using .
I had hibernate-validator-cdi- 5.0.7.Final and hibernate-validator-6.0.2.Final.
Just make sure your jar files are of the same version.
When i kept all the jars of same version, my issue got resolved. I hope this will help you .
You need to add #Valid in register method
#RequestMapping(value = "/register") public ModelAndView register(#Valid #ModelAttribute("user") UserBean user, BindingResult result) {
If you are using hibernate-validator, use version-6.2.4
Version 7 might not work.
In my case hibernate-validator jars are not available in run time. I've copied them to .../WEB-INF/lib/ then it worked correctly.
I added the usual stuff you have done (libraries in pom, #Valid on RequestBody etc)
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.3.Final</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>3.0.1-b11</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
What the Spring docs (and many blogs) leave it as subtle is that Spring looks for an exit point to throw the error but if that exit doesn't exist, it will reply with 404. After reading a lot especially this blog, adding this class got Spring to recognize #Valid and find an exit point to throw the error
#RestControllerAdvice
#Order(1)
public class RestControllerExceptionHandler {
#RequestMapping(value = { "error/404" }, method = RequestMethod.GET)
#ExceptionHandler(Exception.class)
public String handleUnexpectedException(Exception e) {
return "views/base/rest-error";
}
#ResponseStatus(HttpStatus.BAD_REQUEST)
#ExceptionHandler(MethodArgumentNotValidException.class)
public String handlemethodArgumentNotValid(MethodArgumentNotValidException exception) { //
// TODO you can choose to return your custom object here, which will then get transformed to json/xml etc.
return "Sorry, that was not quite right: " + exception.getMessage();
}
#ResponseStatus(HttpStatus.BAD_REQUEST)
#ExceptionHandler(ConstraintViolationException.class)
public String handleConstraintViolation(ConstraintViolationException exception) { //
// TODO you can choose to return your custom object here, which will then get transformed to json/xml etc.
return "Sorry, that was not quite right: " + exception.getMessage();
}
}
i spent nearly 2 days fixing the same problem and ultimately found one solution, if you still have this problem, i would like to suggest you one answer, in my case, i tried using hibernate-validator-5.1.3.Final-dist.zip,5.2.4.Final-dist.zip, 7.0.0.Final-dist.zip but none of these worked for me but when i used *hibernate-validator-6.2.0.Final-dist*, it supports jarkarta validation but it works perfectly even though people say because of Jakarta Bean Validation it does not work in hibernate-validator's version post 5. it worked miraculously and believe me, it might work for you as well.

Spring MVC 404 Error on some requests

I’m developing Spring MVC, on Apache 7.xx application and have setup everything without any errors.
I have a my application map my dispatcher servlet to HomeController , which serves the view “home/View” which is also working.
I want to implement UserAccount & Registeration use case before wiring & itegrating with spring security.
However my registration form (Register.jsp) on form submit ( or action="UserRegisteration/RegisterForm" method="POST">) gives 404 error rather than serving a view via (for testing I have UserRegisterationController serve Register.jsp again)
Register.jsp (form snippet)
<form action="/UserRegisteration/RegisterForm" method="POST">
<table width="283" border="1">
<tr>
<td width="123"><label for="firstname">First Name</label></td>
<td width="144"><input type="text" name="firstname" id="firstname"></td>
</tr>
<tr>
<td><label for="lastname">Last Name</label></td>
<td><input type="text" name="lastname" id="lastname"></td>
</tr>
<tr>
<td><label for="email">Email</label></td>
<td><input type="text" name="email" id="email"></td>
</tr>
<tr>
<td><label for="phonecontact1">Phone Contact 1</label></td>
<td><input type="text" name="phonecontact1" id="phonecontact1"></td>
</tr>
<tr>
<td><label for="phonecontact2">Phone Contact 2</label></td>
<td><input type="text" name="phonecontact2" id="phonecontact2"></td>
</tr>
<tr>
<td><label for="address1">Address 1</label></td>
<td><input type="text" name="address1" id="address1"></td>
</tr>
<tr>
<td><label for="address2">Address 2</label></td>
<td><input type="text" name="address2" id="address2"></td>
</tr>
<tr>
<td><label for="industry ">Industry </label></td>
<td><input type="text" name="industry " id="industry "></td>
</tr>
<tr>
<td><label for="password">Enter Desired Password</label></td>
<td><input type="text" name="password" id="password"></td>
</tr>
<tr>
<td><input type="reset" name="clear " id="clear " value="Clear Fields"></td>
<td><input type="submit" name="register" id="register" value="Register"></td>
</tr>
</table>
</form>
I have the following method createUserAccountRegisteration()mapped to
#RequestMapping(value="/RegisterForm", method=RequestMethod.POST) see below:
(UserRegisterationController.java)
#Controller
#RequestMapping("/UserRegisteration")
public class UserRegisterationController {
#Autowired
private RegisterationService registerationService;
#Autowired
private UserAccountService userAccountService;
#Autowired
private PasswordService passwordService;
public UserRegisterationController() {
}
public UserRegisterationController(RegisterationService registerationService, UserAccountService userAccountService, PasswordService password) {
this.registerationService = registerationService;
this.userAccountService = userAccountService;
this.passwordService = password;
}
//if checked on register link , forward to registeration page
#RequestMapping(value="/RegisterForm", method=RequestMethod.GET)
public String serveRegisterationView()
{
return "UserAccount/Register";
}
#RequestMapping(value="/RegisterForm", method=RequestMethod.POST)
public String createUserAccountRegisteration()
{
//if submited registeration
//check for previous registeration
//if registered prompt , forward to sign in
//else create registeration , and user account , and password , forward to main user page
return "UserAccount/Register";
}
}
web.xml
<web-app metadata-complete="true" version="3.0" 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_3_0.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
/WEB-INF/hibernate-context.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>cmgr</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>cmgr</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
spring-servlet relevat snippet (in my case cmgr-servlet)
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/views/" p:suffix=".jsp" p:viewClass="org.springframework.web.servlet.view.JstlView" />
applicationContext.xml (relevant snippet)
<!-- Activates various annotations to be detected in bean classes -->
<context:annotation-config />
<!-- Scans the classpath for annotated components that will be auto-registered as Spring beans. For example #Controller and #Service. Make sure to set the correct base-package-->
<context:component-scan base-package="com.cmgr.*" />
<!-- Configures the annotation-driven Spring MVC Controller programming model. Note that, with Spring 3.0, this tag works in Servlet MVC only! -->
<mvc:annotation-driven/>
<!-- mapping of static resources-->
<mvc:resources mapping="/resources/**" location="/resources/" />
</beans>
Result of Register.jsp form sumbmit:
Browser URL: (http://localhost:8084/UserRegisteration/RegisterForm)
HTTP Status 404 - /UserRegisteration/RegisterForm
type Status report
message /UserRegisteration/RegisterForm
description The requested resource (/UserRegisteration/RegisterForm) is not available.
Apache Tomcat/7.0.22
What i noticed is the browser url is missing my applications context (/cmgr) the correct url should be "http://localhost:8084/cmgr/UserRegisteration/RegisterForm"
Result of Register.jsp form sumbmit:
Browser URL: (http://localhost:8084/UserRegisteration/RegisterForm)
What i noticed is the browser url is missing my applications context (/cmgr) the correct url >should be "http://localhost:8084/cmgr/UserRegisteration/RegisterForm"
This is right, the context root "/cmgr" is missing. Show us your view, presumably the form action is the problem.
You could use the Spring url tag, like this:
<spring:url value="/UserRegisteration/RegisterForm" var="targetURL"/>
<form action="${targetURL}" [...] >
</form>`

Resources