spring MVC two forms with one controller - spring

Here is the Jsp file. I want a controller that handles both the forms in just one page. is there a way to handle this form? I create a controller but it cannot bind the forms.
<%#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>Welcome to Spring Web MVC project</title>
</head>
<body>
<form:form method="POST" modelAttribute="logindetails" name ="LoginForm" autocomplete="off" >
Dept_Code :
<form:input path="departmentcode"/>
Dept_name
<form:input path="departmentname" placeholder="name" />
<button type="submit" >Save</button>
</form:form><br/>
<form:form method="POST" modelAttribute="emp_details" name = "emp_Form" autocomplete="off" >
Emp_Code :
<form:input path="emp_code"/>
Emp_Coded
<form:input path="Emp_coded" placeholder="coded" />
DDO_Desc
<form:input path="ddo_desc" placeholder="DDO_DESC" />
<button type="submit" >Save</button>
</form:form>
</body>
</html>
Here is my controller Class if you need in case. but I only bind for one form.
#Controller
public class DepartmentController {
#Autowired
Deptservices deptservices;
#RequestMapping(value="index", method= RequestMethod.GET)
public ModelAndView insert(#ModelAttribute("logindetails") Department insert)
{
ModelAndView mav=new ModelAndView("index");
return mav;
}
#RequestMapping(value="index", method= RequestMethod.POST)
public ModelAndView insertPost(#ModelAttribute("logindetails") Department insert)
{
ModelAndView mav=new ModelAndView("index");
deptservices.insert(insert);
return mav;
}
}

You have bind the model with name logindetails.
So, change modelAttribute="emp_details" to modelAttribute="logindetails" in second form.

take a view model like
EmployeeViewMOdel{
logindetails
emp_details
}
model.addAttribute("EmployeeViewMOdelObj",EmployeeViewMOdel);
<form:form method="POST" modelAttribute="*EmployeeViewMOdelObj*" name ="LoginForm" autocomplete="off" >
<form:form method="POST" modelAttribute="EmployeeViewMOdelObj" name = "emp_Form" autocomplete="off" >
bind this object to both the forms and then single controller may handle your request.

Related

Problem in fetching multipart request in spring

I am trying to learn how to handle multi-part request in controller using spring framework/mvc.
And here I got stuck where i wanted to get 2 things from the user 1) Id and 2) pic (image file).
Therefore I had created a simple form like this.
Name:check.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="finaltest" method="post" enctype='multipart/form-data' >
id: <input type="text" name="id">
Pic: <input type="file" name="pic">
<input type="submit">
</form>
</body>
</html>
Controller file
(one of the method) which is relevant to this jsp page
#RequestMapping(path="/finaltest",method=RequestMethod.POST)
public String handlepic(#RequestParam("id")int id,#RequestBody String name) {
return "showform";
}
The Error i am getting is:
Required int parameter 'id' is not present (by tomcat)
WARNING: Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required int parameter 'id' is not present](by java console)

Type [java.lang.String] is not valid for option items

I am trying to bind a list to drop down in JSP. Below is my controller and JSP.
Controller:
#Controller
public class WeatherServiceController {
#Value("#{'${countryList}'.split(',')}")
private List<String> countries;
#ModelAttribute("CountriesList")
private List<String> getCountries(){
System.out.println(countries.size());
return countries;
}
#RequestMapping(value = "/getweather", method=RequestMethod.GET)
public ModelAndView getWeather(){
Place p = new Place();
ModelAndView mav = new ModelAndView();
mav.addObject("place",p);
mav.setViewName("home");
return mav;
}
}
JSP:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# 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=ISO-8859-1">
<title>Weather Service Client - Home</title>
</head>
<body>
<h2>Welcome to Weather Service</h2>
<form:form modelAttribute="place" action="getWeather">
<table>
<tr>
<td><form:label path="country">Country:</form:label></td>
<td>
<form:select path="country" items="${CountriesList}">
</form:select>
</td>
</tr>
</table>
</form:form>
</body>
</html>
But I am getting error like "Type [java.lang.String] is not valid for option items". Country list is not coming in jsp page. Please help me what I did wrong here.
It is working now.
I have added below line in jsp page.
<%# page isELIgnored="false" %>
I thought by default "isELIgnored" is set to false, so I haven't included earlier. After including this page is binding list result.

Displaying validation Errors in form with Spring MVC

I've searched through several tutorials and answers to this forum to try to solve my problem: I want to show the validation errors from my bean in my form using spring MVC.
No matter what I try, I can't get it to work. Im not using redirections, my binding results are directly after the model class and so on.
Here's what I have so far:
Login Class:
public class LoginUser implements Serializable {
#NotNull
#Column(name="username", unique=true)
#Size(min=5)
private String username;
#NotNull
#Size(min=5)
private String password;
Login Controller:
#Transactional
#Controller
public class LoginController {
#Autowired
UserDao dao;
#RequestMapping(value = "enter", method = RequestMethod.POST)
public String doLogin(#ModelAttribute("user") #Valid LoginUser user, BindingResult result, HttpSession session) {
if (result.hasErrors()) {
return "login/loginForm";
} else {
if (dao.authenticate(user)) {
session.setAttribute("userLoggedIn", user.getUsername());
return "forward:index";
} else {
return "redirect:login";
}
}
}
Login Form:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%# 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=ISO-8859-1">
<script type="text/javascript" src="resources/js/bootstrap.js"></script>
<script type="text/javascript" src="resources/js/jquery-3.1.0.min.js"></script>
<link rel="stylesheet" href="resources/css/bootstrap.css">
<title><spring:message code="title.login" /></title>
</head>
<body>
<spring:message code="login.message.login" />
<form:form action="enter" commandName="loginForm" method="POST">
<spring:message code="username.login" />
<input type="text" name="username" id="username" /><br />
<form:errors path="username" />
<spring:message code="password.login" />
<input type="password" name="password" id="password" /><br /> <input
type="submit" value="<spring:message code='button.login'/>"><br />
<spring:message code="does.not.have.account.login" />
<spring:message code="register.link.login" />
</form:form>
</body>
</html>
Ohh, I forgot to add - I have a messages.properties configured (working fine, tested) and the messages are comming from there. Here is the line related to the form:
messages_en.Properties
NotEmpty.loginForm.username= Please fill the username field
By the way, it may be worth to note that my view is mounted trough a composite view (made of JSP includes of header, mainpage and footer) that overrides the customary viewloading in Sping-MVC.
You are using RedirectAttributes but you are not redirecting user any where. Try to use "redirect:/<register_path>" or just add Model model to method params and use model.addAtribute("someName", result);
Try below code..
<form:form action="enter" commandName="loginForm" method="POST">
commandName is loginForm so #ModelAttribute("loginForm").
#RequestMapping(value = "enter", method = RequestMethod.POST)
public String doLogin( #Valid #ModelAttribute("loginForm") LoginUser user, BindingResult result, Map<String, Object> model, HttpSession session) {
if (result.hasErrors()) {
return "login/loginForm";
} else {
if (dao.authenticate(user)) {
session.setAttribute("userLoggedIn", user.getUsername());
return "forward:index";
} else {
return "redirect:login";
}
}
}
UPDATE :
You are using NotEmpty.loginForm.username= Please fill the username field which is wrong,It should be NotNull.loginForm.username= Please fill the username field
And also
#NotNull will not validate for empty string..Request from the front end will be "" which is not null.So use #NotEmpty instead.
If you still want to use #NotNull add InitBinder in your controller as shown below
#InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
}
Then it will validate for empty string.
That is the reason you are getting size error directly and since you have not mentioned any message for that no message is displaying.

Flash attributes and ResourceBundleViewResolver

I am facing an issue with the flash attributes which I have not able to retrieve it in the GET phase of POST/redirect/GET scenario. This is only happening when I use the ResourceBundleViewResolver.
view resolver
<bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basename" value="spring-views" /> </bean>
view properties
form.(class)=org.springframework.web.servlet.view.JstlView
form.url=/WEB-INF/pages/form.jsp
home.(class)=org.springframework.web.servlet.view.JstlView
home.url=/WEB-INF/pages/home.jsp
home_redirect.(class)=org.springframework.web.servlet.view.RedirectView
home_redirect.url=home
form.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 action="register" method="post">
Name: <input type="text" name="name"/> <br/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
home.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<body>
<h2> ${status} </h2>
</body>
</html>
so in this page, home.jsp, the status should contain the value set as the flash attribute.
controller
#Controller
public class WebController {
#RequestMapping(value="/form", method=RequestMethod.GET)
public String showFormPage(){
return "form";
}
#RequestMapping(value="/register", method=RequestMethod.POST)
public ModelAndView login(#RequestParam("name") String name, RedirectAttributes flashMap){
System.out.println("name = " + name);
flashMap.addFlashAttribute("status", "Registered successfully");
//return new RedirectView("home"); -- with this returned its working
return new ModelAndView("home_redirect"); //-- with this returned its not working
//return "redirect:home"; // -- not working
}
#RequestMapping(value="/home")
public String showHomePage(){
return "home";
}
}
on the whole this is the observation made:
if used resource bundle view resolver
return view names as string - not working
return ModelAndView - not working
return RedirectAndView - working
if used internal view resolver
return view names as string - working
2 return modelandview - cannot be used to redirect
return RedirectAndView - working

How to pass variable value from jstl to controller

I have name and password in jsp/jstl
i tried to pass name and password to controller.
this is my controller class
package com.simple.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping("/welcome")
public class HelloController {
private String name;
private String password;
private String user;
#RequestMapping(method = RequestMethod.POST)
public String printWelcome(ModelMap model) {
System.out.println(user);
model.addAttribute(name);
model.addAttribute(password);
model.addAttribute("message", "Spring 3 MVC Hello World");
return "hello";
}
}
this is index.jsp with form tag and c tag libraries
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>Registration Page</title>
</head>
<body bgcolor="#999966">
<p> </p>
<form method="POST" action="welcome">
<p><font color="#800000" size="5">
UserName:</font><input type="text" name="name" size="20"></p>
<c:set var="user" value="{param.name}" scope="request">
</c:set>
<p><font color="#800000" size="5">
password:</font><input type="text" name="password" size="20"></p>
<p><input type="submit" value="Submit" name="B1"></p>
</form>
</body>
</html>
i am trying to pass the variable user( the value is taken from the name variable) from this form to controller.
<c:set var="user" value="{param.name}" scope="request">
</c:set>
can any body help me how to do this with c tags..
i have done with using commandName="registereduser" where user is the object of class RegisteredUser.
But i am trying with just passing the variable (with c tags)
I am getting null value for user in sysout
is there any way to do with c tags with the set
thank you..
In your controller:
#Controller
#RequestMapping("/welcome")
public class HelloController {
#RequestMapping(method = RequestMethod.POST)
public String printWelcome(ModelMap model, #RequestParam String name, #RequestParam String password) {
// do something with name & password
model.addAttribute(name);
model.addAttribute(password);
model.addAttribute("message", "Spring 3 MVC Hello World");
return "hello";
}
}
and in your JSP (you have to use a regular HTML form):
<form method="POST" action="welcome">
<table>
<tr>
<td>User Name :</td>
<td><input type="text" id="name" name="name"/></td>
</tr>
<tr>
<td>Password :</td>
<td><input type="password" id="password" name="password"/></td>
</tr>
</table>
<tr>
<td colspan="2"><input type="submit"></td>
</tr>
</table>
</form>
EDIT TO QUESTION (user variable added):
You need to pass user to controller with an input hidden and add another #RequestParam to controller method:
JSP:
<input type="hidden" id="user" name="user" value="${name}"/>
Controller method:
public String printWelcome(ModelMap model, #RequestParam String name,
#RequestParam String password, #RequestParam String user) {
...
I think you can't send user value to server with c tags, you need to submit data (form) to controller.

Resources