I am following this example:
User controller:
#Controller
public class UserController {
/**
* Static list of users to simulate Database
*/
private static List<User> userList = new ArrayList<User>();
/**
* Saves the static list of users in model and renders it
* via freemarker template.
*
* #param model
* #return The index view (FTL)
*/
#RequestMapping(value = "/index", method = RequestMethod.GET)
public String index(#ModelAttribute("model") ModelMap model) {
userList.add(new User("Bill", "Gates"));
userList.add(new User("Steve", "Jobs"));
userList.add(new User("Larry", "Page"));
userList.add(new User("Sergey", "Brin"));
userList.add(new User("Larry", "Ellison"));
model.addAttribute("userList", userList);
return "index";
}
/**
* Add a new user into static user lists and display the
* same into FTL via redirect
*
* #param user
* #return Redirect to /index page to display user list
*/
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String add(#ModelAttribute("user") User user) {
if (null != user && null != user.getFirstname()
&& null != user.getLastname() && !user.getFirstname().isEmpty()
&& !user.getLastname().isEmpty()) {
synchronized (userList) {
userList.add(user);
}
}
return "redirect:index.html";
}
class User {
private String firstname;
private String lastname;
public User() {
}
public User(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}
}
*-servlet.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
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="ua.epam.spring.hometask" />
<context:annotation-config/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="cache" value="true"/>
<property name="prefix" value="/WEB-INF/ftl"/>
<property name="suffix" value=".ftl"/>
</bean>
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/ftl/"/>
</bean>
</beans>
WEB-INF/ftl/intex.ftl:
<html>
<head><title>ViralPatel.net - FreeMarker Spring MVC Hello World</title>
<body>
<div id="header">
<H2>
<img height="37" width="236" border="0px" src="http://viralpatel.net/blogs/wp-content/themes/vp/images/logo.png" align="left"/>
FreeMarker Spring MVC Hello World
</H2>
</div>
<div id="content">
<fieldset>
<legend>Add User</legend>
<form name="user" action="add.html" method="post">
Firstname: <input type="text" name="firstname" /> <br/>
Lastname: <input type="text" name="lastname" /> <br/>
<input type="submit" value=" Save " />
</form>
</fieldset>
<br/>
<table class="datatable">
<tr>
<th>Firstname</th> <th>Lastname</th>
</tr>
<#list model["userList"] as user>
<tr>
<td>${user.firstname}</td> <td>${user.lastname}</td>
</tr>
</#list>
</table>
</div>
</body>
</html>
and got this exception:
javax.servlet.ServletException: Could not resolve view with name 'index' in servlet with name 'index'
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1237)
org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1037)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:980)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Question: what can be a reson of this exception? How to fix it?
In controller redirection use only index instead of index.html. it will redirect to index method of controller.And you can view the output on index page itself after clicking on button.
As shown below:
#RequestMapping(value = "/Add", method = RequestMethod.POST)
public String add(#ModelAttribute ("usr") User user){
if (null != user && null != user.getFirstname()
&& null != user.getLastname() && !user.getFirstname().isEmpty()
&& !user.getLastname().isEmpty()) {
synchronized (userList) {
userList.add(user);
}
}
return "redirect:index";
Related
I am returning modelAndView object from my Spring API. And view is a JSP form.
The request param to the API is binded with DTO PaymentInput.
The API is working fine on localhost but it is giving blank response when deployed to server. I have checked the logs but there is no exception as such.
Edited
When I change new ModelAndView("payuForm", "paymentInput", paymentInput);
to ModelAndView mav = new ModelAndView(new MappingJackson2JsonView());
it starts returning output as Json
"paymentInput": {
"furl": "https://dev.travelkhana.com/callback/PayUfurl",
"surl": "https://dev.travelkhana.com/callback/PayUsurl",
"txnid": "472663",
"key": "gtKFFx",
"hash": "3c0eeb0cefd5c0637e0a50adee3fd0fe81af6c69f46a52b2fa50711eafa054b43af13957c02ef3a71c0dbcb8c05129829281fd256a55c0c0c04bbc40c84fd474",
"orderid": "472663",
"email": "test#test.com",
"emailid": "test#test.com",
"amount": "270",
"productinfo": "vegthali,nonvegthali",
"firstname": "rahul",
"phone": "9716221914"
}
but still it is not working for HTML response.
payuForm.jsp
<%#page import="com.tk.utilities.CommonFunction"%>
<%
String paymentUrl = CommonFunction.getProperties("payu_payment_url");
System.out.println("paymentUrl:"+paymentUrl);
%>
<html>
<head>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
</head>
<body>
<form:form action="<%=paymentUrl%>" method="post" id='payuForm' modelAttribute="paymentInput">
<form:input type="hidden" name="firstname" path="FIRSTNAME"/>
<form:input type="hidden" name="surl" path="surl"/>
<form:input type="hidden" name="furl" path="furl" />
<form:input type="hidden" name="phone" path="PHONE" />
<form:input type="hidden" name="email" path="EMAIL" />
<form:input type="hidden" name="amount" path="AMOUNT" />
<form:input type="hidden" name="key" path="key" />
<form:input type="hidden" name="hash" path="hash" />
<form:input type="hidden" name="txnid" path="txnid" />
<form:input type="hidden" name="productinfo" path="PRODUCTINFO" />
<input type="hidden" name="isMobileView" value="1" />
</form:form>
</body>
</html>
Model class
package com.tk.payu.dto;
public class PaymentInput {
private String AMOUNT;
private String ORDERID;
private String PRODUCTINFO;
private String FIRSTNAME;
private String EMAIL;
private String EMAILID;//for mapping EMAILID to EMAIL
private String PHONE;
private String furl;
private String surl;
private String txnid;
private String key;
private String hash;
PaymentInput.java
public String getFurl() {
return furl;
}
public void setFurl(String furl) {
this.furl = furl;
}
public String getSurl() {
return surl;
}
public void setSurl(String surl) {
this.surl = surl;
}
public String getTxnid() {
return txnid;
}
public void setTxnid(String txnid) {
this.txnid = txnid;
}
public String getAMOUNT() {
return AMOUNT;
}
public void setAMOUNT(String aMOUNT) {
AMOUNT = aMOUNT;
}
public String getORDERID() {
return ORDERID;
}
public void setORDERID(String oRDERID) {
ORDERID = oRDERID;
}
public String getPRODUCTINFO() {
return PRODUCTINFO;
}
public void setPRODUCTINFO(String pRODUCTINFO) {
PRODUCTINFO = pRODUCTINFO;
}
public String getFIRSTNAME() {
return FIRSTNAME;
}
public void setFIRSTNAME(String fIRSTNAME) {
FIRSTNAME = fIRSTNAME;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getHash() {
return hash;
}
public void setHash(String hash) {
this.hash = hash;
}
public String getPHONE() {
return PHONE;
}
public void setPHONE(String pHONE) {
PHONE = pHONE;
}
public String getEMAIL() {
return EMAIL;
}
public void setEMAIL(String eMAIL) {
EMAIL = eMAIL;
}
public String getEMAILID() {
return EMAILID;
}
public void setEMAILID(String eMAILID) {
EMAILID = eMAILID;
}
}
Controller
#RequestMapping(value = "/payuPaymentNew", method = RequestMethod.POST)
public #ResponseBody ModelAndView payuPaymentNew(
#ModelAttribute("paymentInput") PaymentInput paymentInput,
BindingResult result) throws IOException {
String SURL = CommonFunction.getProperties("payu_surl");
String FURL = CommonFunction.getProperties("payu_furl");
System.out.println("order id:" + paymentInput.getORDERID());
String salt = CommonFunction.getProperties("salt");
String key = CommonFunction.getProperties("key");
paymentInput.setSurl(SURL);
paymentInput.setFurl(FURL);
paymentInput.setKey(key);
System.out.println("payumasterDao:.....");
return new ModelAndView("payuForm", "paymentInput", paymentInput);
}
Expected Output
<html>
<head>
</head>
<body>
<form id="payuForm" action="" method="post">
<input id="FIRSTNAME" name="FIRSTNAME" name="firstname" type="hidden" value="rahul"/>
<input id="surl" name="surl" name="surl" type="hidden" value=""/>
<input id="furl" name="furl" name="furl" type="hidden" value="/>
<input id="PHONE" name="PHONE" name="phone" type="hidden" value="9716221914"/>
<input id="EMAIL" name="EMAIL" name="email" type="hidden" value="test#test.com"/>
<input id="AMOUNT" name="AMOUNT" name="amount" type="hidden" value="270"/>
<input id="key" name="key" name="key" type="hidden" value=""/>
<input id="hash" name="hash" name="hash" type="hidden" value="3c0eeb0cefd5c0637e0a50adee3f/>
<input id="txnid" name="txnid" name="txnid" type="hidden" value="472663"/>
<input id="PRODUCTINFO" name="PRODUCTINFO" name="productinfo" type="hidden" value="vegthali,nonvegthali"/>
<input type="hidden" name="isMobileView" value="1" />
</form>
</body>
</html>
XML entry
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
Remove #ResponseBody from your controller.
#ResponseBody annotation is basically telling Spring: take the object I (method) return and use any serializer you have that supports it and write it directly to the body of the HTTP response. There's no JSP involved here.
I'm using Hibernate validator with Hibernate and Spring, but it seems that validations don't work. When I don't enter a String or enter a String of 1 character (which is not between min=4 and max=20) is not showing any error and therefore saves in the table. What am I missing?
package dao;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
#Entity
#Table(name="etudiant")
public class Etudiant {
#Id
#Column(name="ID_ETUDIANT")
#GeneratedValue
private Long idEtudiant;
#Column(name="NOM")
#Size (min=4, max=20)
private String nom;
#Size(min=4, max=20, message="nom doit etre entre 4 et 20 svp..")
#Column(name="PRENOM")
private String prenom;
#Column(name="DATE_NAISSANCE")
#Temporal(TemporalType.DATE)
private Date dateNaissance;
#NotNull
#Column(name="EMAIL")
private String email;
public Etudiant() {
super();
}
public Long getIdEtudiant() {
return idEtudiant;
}
public void setIdEtudiant(Long idEtudiant) {
this.idEtudiant = idEtudiant;
}
public Etudiant(String nom, String prenom, Date dateNaissance, String email) {
super();
this.nom = nom;
this.prenom = prenom;
this.dateNaissance = dateNaissance;
this.email = email;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public Date getDateNaissance() {
return dateNaissance;
}
public void setDateNaissance(Date dateNaissance) {
this.dateNaissance = dateNaissance;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Controller:
#RequestMapping(value="save",method=RequestMethod.POST)
public String saveetudient(Model md,
#Valid #ModelAttribute("etudiant") Etudiant et,
BindingResult res) {
if (res.hasErrors()) {
List <Etudiant> ets=service.listeEtudiants();
md.addAttribute("etudiants",ets);
return "etudiant1";
}
else {
service.addEtudiant(et);
List <Etudiant> ets=service.listeEtudiants();
md.addAttribute("etudiants",ets);
return "etudiant1";
}
}
In JSP I put this line to show errors:
<form action="save" method="post">
<table border="1" width="500" bgcolor="grey">
<tr>
<th>Nom </th>
<th>Prenom </th>
<th> Date de naissance</th>
<th>Email </th>
</tr>
<tr>
<td> <input type="text" name="nom" > </td>
<td> <input type="text" name="prenom" > </td>
<td> <input type="text" name="dateNaissance" > </td>
<td> <input type="text" name="email" > </td>
</tr>
</table> <br>
<input type="submit" value="ajouter">
<sform:errors path="etudiant.*"/>
<sform:errors path="prenom"/>
</form>
XML file configuration :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd ">
<context:component-scan base-package="controller"/>
<mvc:annotation-driven/>
<bean class="dao.DaoEtudiantImpl" name="daoetud"></bean>
<bean class="service.EtudiantMetierImpl" name="servetud">
<property name="dao" ref="daoetud"></property>
</bean>
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
Finally I found the error ,
the problem was that I didin't add hibernate-validator jar I only added files in the dist/lib/required :
classmate-1.3.1
javax.el-2.2.4
-javax.el-api-2.2.2
jboss-logging-3.3.0.Final
validation-api-1.1.0
So if that happens to someone just add : hibernate-validator-5.3.2.Final.
After spent one hour to study two validation tutorials:
Hibernate Validator Annotations Example
Spring MVC Form Validation Annotation Example
I suggest you some solutions.
1) Verify hibernate validation annotation working or not
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<Etudiant>> constraintViolations = validator.validate(etudiant);
2) You can create custom validator, for example EtudiantValidator, then validate manually like below:
#RequestMapping(value="save",method=RequestMethod.POST)
public String saveetudient(Model md,#ModelAttribute("etudiant") Etudiant etudiant, BindingResult res){
new EtudiantValidator().validate(etudiant, result);
...
}
However I deep into your code,I see that you have a mistake on this method:
#RequestMapping(value="save",method=RequestMethod.POST)
public String saveetudient(Model md,
#Valid #ModelAttribute("etudiant") Etudiant et,
BindingResult res)
Should change it to like below
#RequestMapping(value="save",method=RequestMethod.POST)
public String saveetudient(Model md,
#Valid #ModelAttribute("etudiant") Etudiant etudiant,
BindingResult res)
Hope this help!
I am trying to run a project in Spring MVC. Here is the code
index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="form" uri="http://www.springframework.org/tags/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>Welcome to Spring Web MVC project</title>
</head>
<body>
<h1>Spring 3 Register!</h1>
click
<form:form action="${pageContext.request.contextPath}/register" method="POST" modelAttribute="userForm">
<table>
<tr>
<td colspan="2" align="center">Spring MVC Form Demo - Registration</td>
</tr>
<tr>
<td>User Name</td>
<td><form:input path="username" /></td>
</tr>
<tr>
<td>Password</td>
<td><form:password path="password" /></td>
</tr>
<tr>
<td>Email</td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td>BirthDate (mm/dd/yyyy)</td>
<td><form:input path="birthDate" /></td>
</tr>
<tr>
<td>Profession</td>
<td><form:select path="profession" items="${professionList}" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Register" /></td>
</tr>
</table>
</form:form>
</body>
</html>
RegistrationController.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package RegisterInfo;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
*
* #author Harshit Shrivastava
*/
import RegisterInfo.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.Model;
#Controller
#RequestMapping(value = "/register")
public class RegistrationController {
#RequestMapping(method = RequestMethod.GET)
public String viewRegistration(Model model)
{
User userForm = new User();
model.addAttribute("userForm", new User());
/*List<String> professionList = new ArrayList();
professionList.add("Developer");
professionList.add("Designer");
professionList.add("IT Manager");
model.put("professionList", professionList);*/
return "index";
}
#RequestMapping(method = RequestMethod.POST)
public String processRegistration(#ModelAttribute("userForm") User user, Map<String, Object> model)
{
System.out.println("Username : " + user.getUserName());
model.put("userForm", new User());
return "index";
}
}
User.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package RegisterInfo.model;
/**
*
* #author Harshit Shrivastava
*/
import java.util.Date;
public class User {
private String username;
private String password;
private String email;
private Date birthDate;
private String profession;
public String getUserName()
{
return username;
}
public void setUserName(String username)
{
this.username = username;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public Date getBirthDate()
{
return birthDate;
}
public void setBirthDate(Date birthDate)
{
this.birthDate = birthDate;
}
public String getProfession()
{
return profession;
}
public void setProfession(String profession)
{
this.profession = profession;
}
}
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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd ">
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<context:component-scan base-package="SpringRegister" />
<mvc:annotation-driven />
<!--
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>
In the above program, Whenever I go to http://localhost:8080/SpringRegister/index.htm, I always gets this error
Error:
neither bindingresult nor plain target object for bean 'userForm' available as request attribute
What is wrong with the code?
When you hit the http://localhost:8080/SpringRegister/index.htm from browser, Your request is handled by ParameterizableViewController which does not set the model attribute (userForm) and forwards to index.jsp, the index.jsp's form tag expects the model attribute userForm <form:form action="${pageContext.request.contextPath}/register" method="POST" modelAttribute="userForm"> , which is not available. that why the error. To resolve this you can create your own conrtoller which handles your http://localhost:8080/SpringRegister/index.htm URL,
ModelAndView modelAndView = new ModelAndView("your view name");
model.addAttribute("userForm", new User());
configure that controller instead of class="org.springframework.web.servlet.mvc.ParameterizableViewController" in your servlet xml. Hope this helps.
You need to Change in Controller To bind userForm with Bean ----
Jsp Form --
<form:form action="userAction" modelAttribute="userForm " class="form-search" role="form">
Controller --
#RequestMapping (value = "/userAction")
public ModelAndView checkFeasibility(#ModelAttribute("userForm ")User userForm)
{
// Any Action
model.addObject("userForm",userForm);
return model;
}
In order to Bind userForm modelAttribute of form with User Bean.
I am trying to learn spring MVC. I have a User Registration form which has some validations to be applied. I have written a controller for it and used javax validation annotations on the model class i.e. UserBo.
I have used Spring MVC tag to show any errors found by #Valid annotation. However, the errors are not visible on screen.
Following are the files in my setup.
The Model: UserBO
package com.shailesh.beans;
import javax.validation.constraints.NotNull;
public class UserBO {
public enum MaritalStatus {
SINGLE, MARRIED
}
#Override
public String toString() {
return "UserBO [firstName=" + firstName + ", lastName=" + lastName
+ ", id=" + id + ", phone=" + phone + ", maritalStatus="
+ maritalStatus + "]";
}
#NotNull(message="First Name can not be null")
private String firstName;
#NotNull
private String lastName;
#NotNull
private Long id;
#NotNull
private String phone;
#NotNull
private MaritalStatus maritalStatus;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public MaritalStatus getMaritalStatus() {
return maritalStatus;
}
public void setMaritalStatus(MaritalStatus maritalStatus) {
this.maritalStatus = maritalStatus;
}
}
The Controller : AllPathController
package com.shailesh.controller;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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;
import com.shailesh.beans.UserBO;
#Controller
public class AllPathController {
#RequestMapping(value="/register", method=RequestMethod.GET)
public String register(Model model) {
model.addAttribute("userBo", new UserBO());
return "registerform";
}
#RequestMapping(value="/register", method=RequestMethod.POST)
public String register(#Valid #ModelAttribute("userBo") UserBO userBo, BindingResult result, Model model) {
if(result.hasErrors()) {
System.out.println("Input has some errors :"+result.toString());
//model.addAttribute("userBo", userBo);
return "registerform";
}
System.out.println("Input user details :" +userBo);
return "helloboss";
}
#RequestMapping(value="/homepage", method=RequestMethod.GET)
public String show() {
return "homepage";
}
#RequestMapping(value="/helloboss.do", method=RequestMethod.GET)
public String show2() {
System.out.println("get");
return "helloboss";
}
#RequestMapping(value="/helloboss.do", method=RequestMethod.POST)
public String show3() {
System.out.println("post");
return "hellobosspost";
}
}
The Spring context.xml file :
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd ">
<mvc:annotation-driven />
<!-- <context:component-scan base-package="com.shailesh.controller.*" /> -->
<bean id="allPathController" class="com.shailesh.controller.AllPathController" />
<bean id="resolver" class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basename" value="views" />
</bean>
</beans>
And the very own registerform.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="sf"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css">
.error {
color: red;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2>Registration Form</h2>
<sf:form method="POST" commandName="userBo">
First Name : <sf:input path="firstName" />
<br />
<sf:errors path="firstName" element="div"/>
Last Name : <sf:input path="lastName" />
<br />
<sf:errors path="lastName" />
Phone : <sf:input path="phone" />
<br />
<sf:errors path="phone" />
Marital Status :
<sf:select path="maritalStatus">
<sf:options path="maritalStatus" />
</sf:select>
<sf:errors path="maritalStatus" />
<input type="submit" value="Register" />
</sf:form>
</body>
</html>
My observation is, when i give path value for as "*", it works. However, when i use some specific value ex. firstName , it doesn't show any errors. I tried debugging in this case. I can see the errors being populated inside BindingResult but not shown on UI.
Any help is appeciated. Thanks.
Think this is an easy one but don't know how to handle it.
I have a form like this.
<c:url value="edit" var="editprofileUrl" />
<form:form class="form" id="signup" action="${editprofileUrl}" method="post" modelAttribute="editProfileForm">
<div class="formInfo">
<s:bind path="*">
<c:choose>
<c:when test="${status.error}">
<div class="text-danger">Unable to change profile. Please fix the errors below and resubmit.</div>
</c:when>
</c:choose>
</s:bind>
</div>
<div class="form-group">
<label for="firstName">First name</label>
<form:errors path="firstName" cssClass="text-danger" />
<form:input class="form-control" path="firstName" />
</div>
<div class="form-group">
<label for="lastName">Last name</label>
<form:errors path="lastName" cssClass="text-danger" />
<form:input class="form-control" id="last-name" path="lastName" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Save profile</button>
</div>
</form:form>
And the java form like this:
public class EditProfileForm {
#NotEmpty
private String firstName;
#NotEmpty
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
And a controller like this:
#Controller
#Transactional
public class EditProfileController {
#PersistenceContext
private EntityManager entityManager;
#RequestMapping(value = "/users/{username}/edit", method = RequestMethod.POST)
public String editProfile(#PathVariable String username, Principal currentUser, #Valid EditProfileForm form, BindingResult formBinding) {
if (formBinding.hasErrors()) {
return null;
}
Account user = entityManager.find(Account.class, currentUser.getName());
user.setFirstName(form.getFirstName());
user.setLastName(form.getLastName());
entityManager.persist(user);
return "home";
}
#RequestMapping(value = "/users/{username}/edit", method = RequestMethod.GET)
public ModelAndView editProfileForm(#PathVariable String username, Principal currentUser, WebRequest request, Model model) {
Account account = entityManager.find(Account.class, username);
if (account != null) {
model.addAttribute("account", account);
}
EditProfileForm form = new EditProfileForm();
form.setFirstName(account.getFirstName());
form.setLastName(account.getLastName());
return new ModelAndView("editprofile", "editProfileForm", form);
}
}
Everything works good besides when I don't fill in anything in one of the fields and it should give an error.
Something breaks in this code snippet:
if (formBinding.hasErrors()) {
return null;
}
Instead of returning the same page again with the errors it looks for a view that does not exist:
HTTP Status 404 - /project/WEB-INF/views/users/nilsi/edit.jsp
How do I return the same view again with the errors? Usually it works when i have a shorter #RequestMapping like /signup.
Thanks for any help on this!
In the event of binding errors, return the name of the form view again so that the user can correct the errors.
if (formBinding.hasErrors()) {
return "editprofile";
}
If you return null, Spring tries to guess a view name by looking at the url. Since your url ends with ".../edit", it tries to load edit.jsp.