ModelAndView Spring - spring

Details:
I am testing my first spring project , I am unable to get form data in backing bean . Here my code please help me execute this.
Welcome.jsp is my landing page from here I want to take userid and password and show in userInfo page.
Controller :--
package com.accounts.common.controller;
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;
import com.accounts.common.backingBean.LoginBackingBean;
/**
* Handles requests for the application welcome page.
*/
#Controller
public class WelcomeController {
/**
* Simply selects the welcome view to render by returning void and relying
* on the default request-to-view-translator.
*/
#RequestMapping(value= "/welcome" ,method = RequestMethod.GET)
**public ModelAndView welcome() {
return new ModelAndView("welcome", "userForm", new LoginBackingBean());
}**
#RequestMapping(value="/userInfo" ,method = RequestMethod.POST)
public String userInfo(#ModelAttribute("userForm")LoginBackingBean login ,
ModelMap model){
model.addAttribute("userId" , login.getUserId());
model.addAttribute("password" , login.getPassword());
return "userInfo";
}
}
Here is code for Welcome JSP :-- Only snapshot I am adding
<body>
<form id=login method="POST" action="/AccountingSW/userInfo" >
<div align="center">
<table>
<tr>
<td>User ID : </td>
<td> <input type="text"> </td>
</tr>
<tr>
<td>Password :</td>
<td><input type="password"> </td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value ="Login">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<label style="font-size: 10;color: red">Already existing Member</label>
</td>
</tr>
<tr><td colspan="2" align="center">OR</td></tr>
<tr><td colspan="2" align="center">
<input type="submit" value ="SignUp"></td></tr>
<tr>
<td colspan="2" align="center">
<label style="font-size: 10;color: red">New Member</label>
</td>
</tr>
</table>
</div>
</form >
</body>
</html>
Here is code for UserInfo JSP :
I am putting only snapshot of what the jsp contains
<title>Hello ${userForm.userId}</title>
</head>
<body>
<h2>User Info</h2>
<table>
<tr>
<td>UserId</td>
<td>${userForm.userId}</td>
</tr>
<tr>
<td>Password</td>
<td>${userForm.password}</td>
</tr>
</table>
</body>
</html>
Here is code for Backing Bean :--
package com.accounts.common.backingBean;
public class LoginBackingBean {
private String userId;
private String password;
/* Getter and setters generated */
}
I am able to execute the jsp(s) but the userId and Password is not getting set

Please try to change from
public String userInfo(#ModelAttribute("userForm")LoginBackingBean login
to
public String userInfo(#ModelAttribute("loginBackingBean")LoginBackingBean login
as #ModelAttribute's document
The default model attribute name is inferred from the declared
attribute type (i.e. the method parameter type or method return type),
based on the non-qualified class name: e.g. "orderAddress" for class
"mypackage.OrderAddress", or "orderAddressList" for
"List".
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/ModelAttribute.html#name--

In your welcome.jsp you are missing property name on inputs:
<td> <input type="text" name ="userId"> </td>
<td><input type="password" name="password"> </td>

Related

Why Http status code 404 shows when I click on submit using war file deployed

Image 1. Successful GET request
Image 2. Failed POST when click on submit
Welcome page i.e. index.jsp aprears on localhost:8080/war_filename
but when we click on login in index page it shows http status code 404
Is anyone there, who's having the same issue?
I've copied the war file in apache\webapps
WebController.java
#Controller
public class indexController {
String errorMessage = "Invalid credentials";
#GetMapping("/login")
public String login() {
return "index.jsp";
}
/*********** Login using form ************/
#RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(#RequestParam("firstname") String firstName,
#RequestParam("lastname") String lastName) {
System.out.println("inside login form");
Customer object = repository.findByFirstNameAndLastName(firstName,
lastName);
if (object != null) {
return "home.jsp";
}
return "index.jsp";
}
}
index.jsp
<h3>Do Login Here</h3>
<form method="POST" action="/login">
<table>
<tr>
<td>Employee ID</td>
<td><input type="text" name="firstname" placeholder="Username" required></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="lastname" placeholder="Password" required></td>
</tr>
<tr>
<td><input type="submit" value="Login" /></td>
</tr>
</table>
</form>
home.jsp
<body>
<h3>Operations</h3>
<form action="/selectusingform" method="get">
Select
</form>
<table>
<tr>
<td>Insert</td>
</tr>
<tr>
<td>Update</td>
</tr>
<tr>
<td>Delete</td>
</tr>
<tr>
<td>Find</td>
</tr>
</table>

Spring MVC Form Validation Neither BindingResult nor plain target object for bean name 'BanqueForm' available as request attribute

I have a probleme when validating a form with spring MVC
i have this exception
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'BanqueForm' available as request attribute
this is my controller
package org.gestion.banque.controllers;
import java.util.Map;
import javax.validation.Valid;
import org.gestion.banque.entities.Compte;
import org.gestion.banque.metier.IBanqueMetier;
#Controller
public class BanqueController {
#Autowired
private IBanqueMetier metier;
#RequestMapping(value="/index",method=RequestMethod.GET)
public String index(Model model){
model.addAttribute("BanqueForm", new BanqueForm());
return"banque";
}
#RequestMapping(value="/chargerCompte", method=RequestMethod.GET)
public String charger(Model m) {
m.addAttribute("BanqueForm", new BanqueForm());
return "banque";
}
#RequestMapping(value="/chargerCompte",method=RequestMethod.POST)
public String charger(#Valid BanqueForm bf,
BindingResult result,Model model){
if(result.hasErrors())
{
return "banque";
}
try {
Compte c=metier.ConsulterCompte(bf.getCode());
bf.setTypeCompte(c.getClass().getSimpleName());
bf.setCompte(c);
} catch (Exception e) {
bf.setException(e.getMessage());
}
model.addAttribute("BanqueForm", bf);
return "banque";
}
}
and this is my view
<body>
<div>
<f:form modelAttribute="BanqueForm" method="post" action="chargerCompte" >
<table>
<tr>
<td>Code :</td>
<td><f:input path="code"/></td>
<td><f:errors path="code"></f:errors> </td>
</tr>
<tr>
<td>
<input type="submit" value="OK" />
</td>
</tr>
</table>
</f:form>
</div>
<c:if test="${ not empty BanqueForm.exception}">
<div>${BanqueForm.exception} </div>
</c:if>
<c:if test="${not empty BanqueForm.compte}">
<div>
<table>
<tr>
<td>Solde :</td>
<td>${BanqueForm.compte.solde}</td>
</tr>
<tr>
<td>Solde :</td>
<td>${BanqueForm.compte.dateCreation}</td>
</tr>
<tr>
<td>Type de Compte :</td>
<td>${BanqueForm.typeCompte}</td>
</tr>
<c:if test="${BanqueForm.typeCompte=='CompteCourant'}">
<tr>
<td>Decouvert :</td>
<td>${BanqueForm.compte.decouvert}</td>
</tr>
</c:if>
<c:if test="${BanqueForm.typeCompte=='CompteEpargne'}">
<tr>
<td>taux :</td>
<td>${BanqueForm.compte.taux}</td>
</tr>
</c:if>
</table>
</div>
</c:if>
</body>
</html>
Add #ModelAttribute("BanqueForm") annotation when obtaining BanqueForm object. Something like this:
public String charger(#Valid #ModelAttribute("BanqueForm") BanqueForm bf,
BindingResult result, Model model) { ... }

Spring 3 Form Validation is working for #NotNull but not working for #Size annotation

I am facing a problem with Spring form validation.
It works for #NotNull annotation but some how not working for #Size. I am attaching some code below. Thanks in advance.
package com.doctor;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Doctor
{
#NotNull(message="Cannot be Null")
private String uname;
#Size(min=1,max=8,message="Min 1 and Max 8")
private String password;
private String doctor_fname,doctor_lname,address,dept_id,experience,email,phone,resume,image;
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
....................
...................
DoctorController
package com.doctor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.Model;
import javax.validation.Valid;
#Controller
public class DoctorController {
#RequestMapping(value="/registerDoctor", method=RequestMethod.GET)
public String showRegisterForm(Model model)
{
System.out.println("test");
model.addAttribute(new Doctor());
//return "register1";
return "doctor/edit";
}
#RequestMapping(value="/registerDoctor", method=RequestMethod.POST)
public String addDoctorformForm(#Valid Doctor doctor,BindingResult bindingresult)
{
if(bindingresult.hasErrors())
{
return "doctor/edit";
}
else
{
return "doctor/added";
}
}
}
Display page
<%# taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<h2>Create a Doctor account</h2>
<sf:form method="POST" modelAttribute="doctor"
enctype="multipart/form-data">
<fieldset>
<table>
<tr>
<td><sf:label path="uname">User Name:</sf:label></td>
<td><sf:input path="uname" /><br /> <sf:errors
path="uname" /> </td>
</tr>
<tr>
<td><sf:label path="password">Password:</sf:label></td>
<td><sf:password path="password" showPassword="true" />
<br /> <sf:errors
path="password" /></td>
</tr>
<tr>
<td><sf:label path="doctor_fname">First Name:</sf:label></td>
<td><sf:input path="doctor_fname" size="15" /><br /> </td>
</tr>
<tr>
<td><sf:label path="doctor_lname">Last Name:</sf:label></td>
<td><sf:input path="doctor_lname" size="15" /><br /></td>
</tr>
<tr>
<td><sf:label path="address">Address:</sf:label></td>
<td><sf:input path="address" size="15" /><br /></td>
</tr>
<tr>
<td><sf:label path="dept_id">Department:</sf:label></td>
<td><sf:input path="dept_id" size="15" /><br /></td>
</tr>
<tr>
<td><sf:label path="experience">Experience:</sf:label></td>
<td><sf:input path="experience" size="15" /><br /></td>
</tr>
<tr>
<td><sf:label path="email">Email Address:</sf:label></td>
<td><sf:input path="email" size="30" /> <small>In case
you forget something</small><br /> </td>
</tr>
<tr>
<td><sf:label path="phone">Phone:</sf:label></td>
<td><sf:input path="phone" size="30" /> <small>In case
you forget something</small><br /> </td>
</tr>
<tr>
<td><label for="resume">Resume:</label></td>
<td><input name="resume" type="file" />
</tr>
<tr>
<td><label for="image">Profile image:</label></td>
<td><input name="image" type="file" />
</tr>
<tr>
<th></th>
<td><input name="commit" type="submit">
</tr>
</table>
</fieldset>
</sf:form>
I don't understand why #Size for password is not working.
Help will be highly appreciated.
It is because null is a valid value from #Sizes point of view.
You need both annotations:
#Size(min=1,max=8,message="Min 1 and Max 8")
#NotNull
private String password;
BTW: Your form is a simple form with no file upload, so there is no need to have `enctype="multipart/form-data" - I would remove it
The issue it seems is you are using multipart form but I dont think I see a mention about multipartResolver. If needed here is how you can add it
<bean id="multipartResolver class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

Values for th:field attributes in checkbox

I have table with datas from database (insert dynamically). In one column I insert checkbox. Now I want to select one of them and send to next form (I select one product and send properties to another form. In this form should be displayed properties only the select product). But I don't know what kind of value insert in th:field="*{}". I tried many solutions but doesn't work. My html form with all products table:
<form action="/oferta/zamow" th:action="#{/oferta/zamow}"
th:object="${oferta}" method="post">
<table border="1" id="display-data">
<tr>
<td>#</td>
<td>title</td>
<td>author</td>
<td>rok</td>
<td>cena</td>
<td></td>
</tr>
<tr th:each="produkt, pozycja : ${oferta}">
<td th:text="${pozycja.count}"></td>
<td><span th:text="${produkt.tytul}"></span></td>
<td><span th:text="${produkt.autor}"></span></td>
<td><span th:text="${produkt.rok}"></span></td>
<td><span th:text="${produkt.cena}"></span></td>
<td>
<input type="submit" value="zamow"/>
<!-- <a th:href="#{/zamowienie}">zamow</a> -->
</td>
<td>
<label>zamow</label>
<input type="checkbox" th:field="*{produkt}" th:value="${produkt}"/>
</td>
</tr>
</table>
</form>
Form to display select product:
<form action="/zamowienie/zam" th:action="#{/zamowienie/zam}"
th:object="${zamowienie}" method="post">
<table border="1" id="display-data">
<tr align="center">
<td colspan="2">twoje zamowienie</td>
</tr>
<tr>
<td>tytul</td>
<td><span th:text="${produkt.tytul}"></span></td>
</tr>
<tr>
<td>autor</td>
<td><span th:text="${produkt.autor}"></span></td>
</tr>
<tr>
<td>rok</td>
<td><span th:text="${produkt.rok}"></span></td>
</tr>
<tr>
<td>cena</td>
<td><span th:text="${produkt.cena}"></span></td>
</tr>
<tr>
<td>data zlozenia zamowienia</td>
<td><span th:text="${datazam}"></span></td>
</tr>
</table>
</form>
Thanks for help.
I am not sure if this is the answer you seek, but you can find an example at http://www.thymeleaf.org/doc/html/Thymeleaf-Spring3.html#checkbox-fields.
Here is a simple example to illustrate how to use a checkbox in Thymeleaf with Spring MVC.
Controller:
#RequestMapping(value = "/showForm", method=RequestMethod.GET)
public String showForm(Model model) {
List<String> allItems = new ArrayList<String>();
allItems.add("value1");
allItems.add("value2");
allItems.add("value3");
model.addAttribute("allItems", allItems);
Foo foo = new Foo();
List<String> checkedItems = new ArrayList<String>();
// value1 will be checked by default.
checkedItems.add("value1");
foo.setCheckedItems(checkedItems);
model.addAttribute("foo", foo);
...
}
#RequestMapping(value = "/processForm", method=RequestMethod.POST)
public String processForm(#ModelAttribute(value="foo") Foo foo) {
// Get value of checked item.
List<String> checkedItems = foo.getCheckedItems();
...
}
html:
<form action="#" th:action="#{/processForm}" th:object="${foo}" method="post">
<div th:each="item : ${allItems}">
<input type="checkbox" th:field="*{checkedItems}" th:value="${item}" />
<label th:text="${item}">example</label>
</div>
<input type="submit" />
</form>
Foo.java:
public class Foo {
private List<String> checkedItems;
public List<String> getCheckedItems() {
return checkedItems;
}
public void setCheckedItems(List<String> checkedItems) {
this.checkedItems = checkedItems;
}
}
Hope this helps.
Take a look at the thymeleaf spring integration docs.
All th:field are mapped against the command object. Thats why you need the *{} expression.
One thing the template engine is not able to do (yet) is mapping fields inside a loop directly. So you cannot use the *{} approach to reference the produkt variable from the loop.
What you have to do is use the index of the th:each expression and build a property accessor with a pre-evaluated expression for the index.
<input type="checkbox" th:field="*{produkts[__${index}__].checked" />
You do not need the th:value, th:field is taking care of it. (Except if you want to superseed it)

How are Spring MVC Controllers being bound to JSP pages?

Hi I am new to spring and I am trying to develop a simple portlet that accepts users first and last name and saves it to db using hibernate.
Basically I cannot figure out how the jsps and controllers communicate; I am missing some chunk here.
This is my first controller that needs to be called (where do I mention so?)
package codes.controller;
import javax.portlet.RenderResponse;
import codes.base.User;
import codes.service.UserService;
#Controller(value="SimpleUserController")
#RequestMapping(value = "VIEW")
public class SimpleUserController {
// -- auto-wiring of service dependency
#Autowired
#Qualifier("userService")
private UserService userService;
// --maps the incoming portlet request to this method
#RenderMapping
public String showUsers(RenderResponse response) {
return "home";
}
#ExceptionHandler({ Exception.class })
public String handleException() {
return "errorPage";
}
// -- #ModelAttribute here works as the referenceData method
#ModelAttribute(value="user")
public User getCommandObject() {
return new User();
}
}
Initially I am displaying a home.jsp that will display the form with two input boxes and a submit button.
<%#include file="include.jsp" %>
<portlet:actionURL var="addUserActionUrl">
<portlet:param name="myaction" value="addUser" />
</portlet:actionURL>
<form:form name="home" commandName="user" method="post"
action="${addUserActionUrl}">
<table>
<tr>
<td>First Name:<font style="color: #C11B17;">*</font></td>
<td><form:input path="firstname" /></td>
</tr>
<tr>
<td>Last Name:<font style="color: #C11B17;">*</font></td>
<td><form:input path="lastname" /></td>
</tr>
<table align="right">
<tr>
<td> </td>
<td><input type="submit" value="SUBMIT" /></td>
</tr>
</table>
</table>
</form:form>
This JSP should call the action method in the AddUserController.java:
package codes.controller;
import javax.portlet.ActionResponse;
import javax.portlet.RenderResponse;
import codes.base.User;
import codes.service.UserService;
#Controller(value = "AddUserController")
#RequestMapping(value = "VIEW")
public class AddUserController {
#Autowired
#Qualifier("userService")
private UserService userService;
#RenderMapping(params = "myaction=addUser")
public String showRegisterPage(Model model) {
model.addAttribute("user", new User());
model.addAttribute("users", getUsers());
return "addUser";
}
public List<User> getUsers() {
return userService.getAllUsers();
}
#ActionMapping(params = "myaction=addUser")
public void addBook(#ModelAttribute(value = "user") User user,
BindingResult bindingResult, ActionResponse response,
SessionStatus sessionStatus) {
if (!bindingResult.hasErrors()) {
userService.addUser(user);
response.setRenderParameter("myaction", "users");
sessionStatus.setComplete();
} else {
response.setRenderParameter("myaction", "addUser");
}
}
}
This time this firstname+last name should be saved in the db AND the screen should refresh to show a new form that will have a dropdown with the current users' names in the database and another first name and last name form fields. If you select a username from the dropdown the form fields are populated and you can edit these values and click on UPdate button to save the values in DB. Otherwise you can add a new user to the database using submit button.
addUser.jsp:
<%#include file="include.jsp" %>
<portlet:actionURL var="addUserActionUrl">
<portlet:param name="myaction" value="addUser" />
</portlet:actionURL>
<portlet:renderURL var="homeUrl">
<portlet:param name="myaction" value="Users" />
</portlet:renderURL>
<script type="text/javascript" src="js/userRelated.js"></script>
<form:form name="addUser" commandName="user" method="post"
action="${addUserActionUrl}">
<form:select path="model">
<form:option value="NONE" label="--- Select ---" id="userList" onchange="showHide()"/>
<form:options items="${users}" />
</form:select>
<table>
<tr>
<td>First Name:<font style="color: #C11B17;">*</font></td>
<td><form:input path="firstname" /></td>
</tr>
<tr>
<td>Last Name:<font style="color: #C11B17;">*</font></td>
<td><form:input path="lastname" /></td>
</tr>
<table align="right">
<tr>
<td> </td>
<td><input type="submit" id="submit" value="SUBMIT" />SUBMIT</td>
</tr>
<tr>
<td> </td>
<td><input type="submit" id="update" value="SUBMIT" />UPDATE</td>
</tr>
</table>
</table>
</form:form>
I am hiding and unhiding the SUBMIT/UPDATE button using onchange of dropdown. How do I call different functions in the addUsercontroller depending on the button available?
by updating the action attribute of form element with javascript

Resources