Required String parameter 'username' is not present when trying to set session attribute - spring

I'm trying to set username as Http session attribute when user loging in but it gives me an error
Required String parameter 'username' is not present
This is my controller class, getLoginForm method. Here I'm trying to get username string from input and puting it to httpSession (because i will need this username to use in other requests).
package com.vandh.app.controller;
import javax.servlet.http.HttpSession;
#Controller
#SessionAttributes("username")
public class LoginController {
#RequestMapping(value = { "/", "/home" })
public String getUserDefault() {
return "home";
}
#RequestMapping("/login")
public ModelAndView getLoginForm(#ModelAttribute Users users,
#RequestParam(value = "error", required = false) String error,
#RequestParam(value = "logout", required = false) String logout,
#RequestParam(value="username") String username,
HttpSession httpSession) {
String message = "";
if (error != null) {
message = "Incorrect username or password !";
} else if (logout != null) {
message = "Logout successful !";
}
else
if(error==null)
{
httpSession.setAttribute("username", username);
}
return new ModelAndView("login", "message", message);
}
#RequestMapping("/admin**")
public String getAdminProfile() {
return "admin";
}
#RequestMapping("/403")
public ModelAndView getAccessDenied() {
Authentication auth = SecurityContextHolder.getContext()
.getAuthentication();
String username = "";
if (!(auth instanceof AnonymousAuthenticationToken)) {
UserDetails userDetail = (UserDetails) auth.getPrincipal();
username = userDetail.getUsername();
}
return new ModelAndView("403", "username", username);
}
}
Here is my DAO class of finding users in DB (MySQL)
#Repository("loginDao")
public class LoginDaoImpl implements LoginDao {
#Autowired
SessionFactory sessionFactory;
//public String userLogIn; // checking username in auth. process
Session session = null;
Transaction tx = null;
#Override
public Users findByUserName(String username ) {
String login = username;
session = sessionFactory.openSession();
tx = session.getTransaction();
session.beginTransaction();
Users user = (Users) session.load(Users.class, new String(username));
tx.commit();
return user;
}
}
And this is my login.jsp page
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Login </title>
</head>
<body>
<br /> <br /> <br />
<div style="border: 1px solid black; width: 300px; padding-top: 10px;">
<br /> Please enter your username and password to login ! <br /> <span
style="color: red">${message}</span> <br />
<form:form method="post" action="j_spring_security_check"
modelAttribute="users">
<table>
<tr>
<td>Username:</td>
<td><form:input path="username" /></td>
</tr>
<tr>
<td>Password:</td>
<td><form:input path="password" type="password" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" /></td>
</tr>
</table>
</form:form>
</div>
</body>
</html>

Related

Page in my project doesn't work (Tomcat Error)

My page doesn’t open. On this page I can create a user and give him a username and password + role (admin or user). Why does page doesn t work. You can look at the code, it seems to have written correctly. Maybe somewhere I made a mistake in the code.Tomcat gives error 404. I just need him to open this page, you can see the controller
Admin Controller
#Controller
#RequestMapping("/admin")
public class AdminController {
#Autowired
private StudentService studentService;
#GetMapping("/allStudentsAdmin")
public ModelAndView allStudentsForUser() {
ModelAndView mv = new ModelAndView();
List<Student> studentList = studentService.getAllStudents();
mv.addObject("studentList", studentList);
mv.setViewName("allStudentsAdmin");
return mv;
}
#GetMapping(value = "/deleteStudent/{id}")
public ModelAndView deleteUserById(#PathVariable Long id) {
studentService.deleteStudentById(id);
ModelAndView mv = new ModelAndView("redirect:/admin/allStudentsAdmin");
return mv;
}
#GetMapping(value = "/editStudent/{id}")
public ModelAndView displayEditUserForm(#PathVariable Long id) {
ModelAndView mv = new ModelAndView("adminEditStudent");
Student student = studentService.getStudentById(id);
mv.addObject("headerMessage", "Редактирование студента");
mv.addObject("student", student);
return mv;
}
#PostMapping(value = "/editStudent")
public String saveEditedUser(
#RequestParam("id") Long id,
#RequestParam("name") String name,
#RequestParam("surname") String surname,
#RequestParam("avatar") MultipartFile file) {
try {
studentService.updateStudent(name, surname, file, studentService.getStudentById(id));
} catch (FileSystemException ex) {
ex.printStackTrace();
} catch (IOException e) {
return "redirect:/errors";
}
return "redirect:/admin/allStudentsAdmin";
}
#GetMapping(value = "/addStudentAdmin")
public ModelAndView displayNewUserForm() {
ModelAndView mv = new ModelAndView("addStudentAdmin");
mv.addObject("headerMessage", "Add Student Details");
mv.addObject("student", new Student());
return mv;
}
#PostMapping(value = "/addStudentAdmin")
public String saveNewStudent(#RequestParam("name") #NonNull String name,
#RequestParam("surname") #NonNull String surname,
#RequestParam("avatar") MultipartFile file)
throws IOException {
Student student = new Student();
student.setSurname(surname);
student.setName(name);
if (file != null && !file.isEmpty()) {
student.setAvatar(studentService.saveAvatarImage(file).getName());
}
studentService.saveStudent(student);
return "redirect:/admin/allStudentsAdmin";
}
#GetMapping(value = "/addUser")
public ModelAndView displayAddUserForm() {
ModelAndView mv = new ModelAndView("addStudentAdmin");
mv.addObject("headerMessage", "Add Student Details");
mv.addObject("student", new Student());
return mv;
}
#PostMapping(value = "/addUser")
public String saveNewUser(#RequestParam("name") #NonNull String name,
#RequestParam("surname") #NonNull String surname,
#RequestParam("role") #NonNull String role)
throws IOException {
Student student = new Student();
student.setSurname(surname);
student.setName(name);
studentService.saveStudent(student);
return "redirect:/admin/allStudentsAdmin";
}
}
Admin Decorator
<body>
<div id="container">
<div id="header">
</div>
<div id="nav">
<ul>
<li><span>Главная</span></li>
<li class="dropdown"><span>Студенты</span>
<ul>
<li><span>Список студентов</span></li>
<sec:authorize access="hasRole('ADMIN') || hasRole('USER')">
<li><span>Добавить студента</span></li>
</sec:authorize>
<sec:authorize access="hasRole('ADMIN')">
<li><span>Добавить юзера</span></li>
</sec:authorize>
</ul>
</li>
<li><a><span>О нас </span></a></li>
<sec:authorize access="!isAuthenticated()">
<li><span>Выйти</span></li>
</sec:authorize>
</ul>
</div>
</div>
<sitemesh:write property='body'/>
<jsp:include page="/WEB-INF/template/admintemplate.jsp"/>
</body>
</html>
AddUser.JSP
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<title>Home</title>
</head>
<body>
<div class="add">
<br>
<br>
<br>
<br>
<center>
<h1>${headerMessage}</h1>
<form:form method="POST" action="${pageContext.request.contextPath}/admin/addUser" enctype="multipart/form-data">
<table>
<tr>
<td><label path="Name">Name</label></td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td><label path="Surname">Surname</label></td>
<td><input type="text" name="surname"/></td>
</tr>
<tr>
<td><select name="select" size="3" multiple>
<option selected value="s1">Admin</option>
<option value="s2">User</option>
</select></td>
<td>
<input type="text" name="Role"/>
</td>
</tr>
<tr>
<td><input class="btn btn-primary" type="submit" value="Добавить"></td>
</tr>
</table>
</form:form>
</center>
</div>
</body>
</html>
Change URL to admin/addUser
because in your controller you have added a root level admin
#RequestMapping("/admin")
ex .http://localhost:8080/SchoolMaven/admin/addUser

org.springframework.web.util.NestedServletException Netbeans

I am using Spring Framework to develop a web app.
The problem is when i tried to add an article in my database It shows a NestedServlet exception. Can any one help me ?
This is my controler class :
#Controller
public class Controler {
ArticleFacadeLocal articleModel;
CategorieFacadeLocal categorieModel;
ConnexionFacadeLocal connexionModel;
public Controler(){
articleModel = new ArticleModel();
categorieModel = new CategorieModel();
connexionModel = new ConnexionModel();
}
#RequestMapping("/home.do")
public String home(HttpServletRequest request){
if(isConnected(request))
return addPage(request);
else return "page:login";
}
#RequestMapping("login.do")
public String login(HttpServletRequest request){
String login=request.getParameter("login");
String password=request.getParameter("password");
if(ConnexionModel.connect(login, password)){
request.getSession().setAttribute("login",login);
ServletContext application=request.getServletContext();
application.setAttribute("categories", categorieModel.findAll());
return addPage(request);}
else
request.setAttribute("error",true);
return "forward:/home.do";
}
#RequestMapping("logout.do")
public String logout(HttpServletRequest request) {
request.getSession(false).invalidate();
return "forward:/home.do";
}
#RequestMapping("articles.do")
public String list(HttpServletRequest request){
request.setAttribute("articles",articleModel.findAll());
return "page:articles";
}
#RequestMapping("addPage.do")
public String addPage(HttpServletRequest request){
request.setAttribute("categories", categorieModel.findAll());
return "page:add";
}
#RequestMapping("add.do")
public String add(HttpServletRequest request){
try{
Article a=getArticleFromView(request);
articleModel.create(a);
request.setAttribute("error", false);
}catch(Exception e){request.setAttribute("error", true);}
return "forward:/addPage.do";
}
#RequestMapping("modifyPage.do")
public String modiyPage(HttpServletRequest request){
int idArticle=Integer.parseInt(request.getParameter("idArticle"));
request.setAttribute("categories", categorieModel.findAll());
Article article = articleModel.find(idArticle);
request.setAttribute("article", article);
return "page:modify";
}
#RequestMapping("modify.do")
public String modify(HttpServletRequest request){
try{
Article a=getArticleFromView(request);
articleModel.edit(a);
return "forward:/articles.do";
}catch(Exception e){
request.setAttribute("error", true);
return "forward:/modifyPage.do";
}
}
#RequestMapping("searchPage.do")
public String searchPage(HttpServletRequest request){
return "page:search";
}
#RequestMapping("search.do")
public String search(HttpServletRequest request){
String libelle=request.getParameter("libelle");
request.setAttribute("article",articleModel.find(libelle));
return "page:search";
}
public boolean isConnected(HttpServletRequest request){
HttpSession session = request.getSession(false);//recupere une session sans la creer
return (session!=null && session.getAttribute("login")!=null);
}
public Article getArticleFromView(HttpServletRequest request){
Article a = new Article();
String libelle = request.getParameter("libelle");
String description = request.getParameter("description");
String prix = request.getParameter("prix");
String qte = request.getParameter("qte");
String categorie = request.getParameter("categorie");
a.setLibelle(libelle);
a.setDescription(description);
a.setPrix(Double.parseDouble(prix));
a.setQte(Integer.parseInt(qte));
a.setCategorie(new Categorie(categorie));
return a;
}
}
And this is my jsp file
<%#include file="include.jsp" %>
<form action="add.do" method="post">
<table align="center">
<tr >
<td>Libelle :
<td><input type="text" required="required" name="libelle"/>
</tr>
<tr >
<td>Description :
<td><input type="text" required="required" name="description">
</tr>
<tr>
<td>Prix :
<td><input type="text" required="required" name="prix">
</tr>
<tr>
<td>Quantité :
<td><input type="text" required="required" name="qte">
</tr>
<tr >
<td> Catégorie :
<td>
<select name="categorie" >
<c:forEach items="${categories}" var="c">
<option value="${c.idCategorie}"> ${c.libelleCategorie} </option>
</c:forEach>
</select>
</tr>
<tr align="center" >
<td colspan="2"><button type="submit" id="btn">Ajouter</button></td>
</tr>
</table>
</form>
<c:if test="${not empty error && error}"> <p style="color: red;"> Echec d'ajout de l'article </p></c:if>
<c:if test="${not empty error && not error}"> <p style="color: green;">Article ajouté avec succes </p></c:if>
This is error exception :
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.AssertionFailure: null id in model.beans.Article entry (don't flush the Session after an exception occurs)
cause première
org.hibernate.AssertionFailure: null id in model.beans.Article entry (don't flush the Session after an exception occurs)
I am not using Maven.

Spring MVC : unable to display drop down

I am not getting the drop down value in Profession. Actually I am getting exception
javax.servlet.ServletException: Type [java.lang.String] is not valid for option items
org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:848)
org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:781)
org.apache.jsp.WEB_002dINF.views.Registration_jsp._jspService(org.apache.jsp.WEB_002dINF.views.Registration_jsp:85)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:322)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:263)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1208)
org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:992)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:939)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
javax.servlet.http.HttpServlet.service(HttpServlet.java:697)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:81)
root cause
javax.servlet.jsp.JspException: Type [java.lang.String] is not valid for option items
org.springframework.web.servlet.tags.form.OptionWriter.writeOptions(OptionWriter.java:142)
org.springframework.web.servlet.tags.form.SelectTag.writeTagContent(SelectTag.java:223)
org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:103)
org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:80)
org.apache.jsp.WEB_002dINF.views.Registration_jsp._jspx_meth_form_select_0(org.apache.jsp.WEB_002dINF.views.Registration_jsp:283)
org.apache.jsp.WEB_002dINF.views.Registration_jsp._jspx_meth_form_form_0(org.apache.jsp.WEB_002dINF.views.Registration_jsp:144)
I understand something wrong with select tag .
please help
RegisterController
package net.codejava.spring.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.codejava.spring.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
#RequestMapping(value = "/register")
public class RegisterController {
#RequestMapping(method = RequestMethod.GET)
public ModelAndView initForm() {
User user = new User();
user.setUsername("Anukul");
ModelAndView mav = new ModelAndView("Registration");
//=== default user name======
//model.addAttribute("userNameDefault", "Enter Name");
mav.addObject("userNameDefault", "Enter Name");
//==== creating drop down list =====
Map<String,String> profDropDown = new HashMap<String, String>();
profDropDown.put("Lecturer", "Lecturer");
profDropDown.put("proff", "proff");
// //==== adding drop down to user ====
mav.addObject("ProffesionList", profDropDown);
mav.addObject("user",user);
//==== user added to model =========
return mav;
}
#RequestMapping(method = RequestMethod.POST)
public String submitForm(Model model,#ModelAttribute User user) {
model.addAttribute(user);
// implement your own registration logic here...
return "RegistrationSuccess";
}
}
Registration.jsp
<%# page language="java" contentType="text/html; charset=UTF-8" 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>Registration</title>
</head>
<body>
<div align="center">
<h1>reached here</h1>
<form:form action="register" method="POST" commandName="user">
<table border="0">
<tr>
<td colspan="2" align="center"><h2>Spring MVC Form Demo - Registration</h2></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>E-mail:</td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td>Birthday (mm/dd/yyyy):</td>
<td><form:input path="birthDate" /></td>
</tr>
<tr>
<td>Profession:</td>
<td><form:select path="profession" items="${ProffesionList}" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Register" /></td>
</tr>
</table>
</form:form>
</div>
</body>
User.java
package net.codejava.spring.model;
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;
}
}
----------------
does this works for you
<form:select id="profession" path="profession">
<form:options items="${ProffesionList}"/>
</form:select>
or try with this
<form:select id="profession" path="profession">
<c:forEach var="prof" items="${ProffesionList}">
<form:option value="${prof.key}" label="${prof.value}" />
</c:forEach>
</form:select>
Controller
#RequestMapping(method = RequestMethod.POST)
public String submitForm(Model model,#ModelAttribute User user) {
//==== creating drop down list =====
Map<String,String> profDropDown = new HashMap<String, String>();
profDropDown.put("Lecturer", "Lecturer");
profDropDown.put("proff", "proff");
// //==== adding drop down to user ====
mav.addObject("ProffesionList", profDropDown);
model.addAttribute(user);
// implement your own registration logic here...
return "RegistrationSuccess";
}
or add #ModelATtribute
#ModelAttribute("ProffesionList")
public Map<String,String> getProfessions(){
Map<String,String> profDropDown = new HashMap<String, String>();
profDropDown.put("Lecturer", "Lecturer");
profDropDown.put("proff", "proff");
return profDropDown;
}

Neither BindingResult nor plain target object for bean name 'registerForm' available as request attribute

I am getting this error.I have tried allot but could not understand what it means?
worker class which interacts with db:
public class EmpLeaveApplyWorker{
private Connection con;
private PreparedStatement pstmt;
public boolean validateUser(LeaveApplyForm leaveapplyform){
try{
con=DBConnection.getConnection();
// String query="select MAX(user_id)from emplogin";
String query1 = "insert into empLeave(LeaveType,leavePeriod,FirstApprover,finalApprover) values(?,?,?,?)";
//String query2 = "insert into emplogin(user_id) values(?)";
System.out.println("------Not able to go ahead---in worker"); pstmt=con.prepareStatement(query1);
// String empName=registerForm.getName()+" "+registerForm.getMname()+" "+registerForm.getLname();
pstmt.setString(1, leaveapplyform.getLeaveType());
pstmt.setString(2,leaveapplyform.getLeavePeriod() );
pstmt.setString(3, leaveapplyform.getFirstApprover());
pstmt.setString(4, leaveapplyform.getFinalApprover());
// pstmt.executeUpdate();
System.out.println("$--------------------details may have updated successfully -----------------------check that out---------------");
int status= pstmt.executeUpdate();
/* pstmt=con.prepareStatement(query2);
pstmt.setString(2, leaveapplyform.getPassword());
*/
pstmt.executeUpdate();
if(status>0){
System.out.println("Employee Account Created Scuucessfully");
}
}catch(Exception e)
{
e.printStackTrace();
System.out.println(e);
}
return false;}
/* public int getEmpNumber(){
try{
con=DBConnection.getConnection();
String query="select MAX(user_id)from emplogin";
PreparedStatement pstmt=con.prepareStatement(query);
ResultSet rs=pstmt.executeQuery();
if(rs.next()){
return rs.getInt(1);
}
}catch(Exception e){
e.printStackTrace();
}
return 0;
}*/}
I am posting controller class and dispatcher-servlet.xml is configured and it is working working fine but the problem is with controller,cany any one solve this error?:
#Controller
public class EmpLeaveApplyController
{
static Logger log = Logger.getLogger(EmpLeaveApplyController.class.getName());
#RequestMapping(value = "/leaveapplyform", method = RequestMethod.GET)
public String showForm(ModelMap model,HttpServletRequest request)
{
log.info("Inside Controller returning to leaveapplyform page....");
LeaveApplyForm leaveapplyform = new LeaveApplyForm();
model.put("leaveapplyform", leaveapplyform);
/*EmpLeaveApplyWorker worker1=new EmpLeaveApplyWorker();*/
return GlobalConstants.LEAVE_APPLY;
}
/*
int emp_id=worker1.getEmpNumber();
if(emp_id > 0){
CommonDTOBean dtoBean=new CommonDTOBean();
dtoBean.setEmp_id(emp_id);
registerForm.setEmpID(emp_id);
HttpSession session=request.getSession();
session.setAttribute("dtoBean", dtoBean);
}else{
System.out.println("Error While getting the emp id ");
}
return GlobalConstants.REGISTER_PAGE;
}
*/
#RequestMapping(value = "/leaveapplyform" ,method = RequestMethod.POST)
public String processForm(#ModelAttribute("leaveapplyform") LeaveApplyForm leaveapplyform, BindingResult result,HttpServletRequest request, HttpServletResponse response, ModelMap model)
{
System.out.println("-------I think can not go head---------------");
leaveapplyform = (LeaveApplyForm) model.get("leaveapplyform");
/*if(result.hasErrors()){
return GlobalConstants.ERRORPAGE;
}*/
EmpLeaveApplyWorker worker=new EmpLeaveApplyWorker();
boolean status=worker.validateUser(leaveapplyform);
if(status)
{
System.out.println("------------------came to the last point of todays task-------------------------------");
return GlobalConstants.HOME_PAGE;
}
else
{
System.out.println("------do not come here------------------");
return GlobalConstants.REGISTER_PAGE;
} }
}
I created all the setter and getter for all required variables.And If possible,tell me where I am wrong?
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%#taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<html>
<head>
<title> Application </title>
<link rel="stylesheet" href="CSS/style2.css">
</head>
<body background="Background.gif">
<h2> Application Form </h2>
<div id="align">
<form:form method="POST" action="leaveapplyform.do" commandName="leaveapplyform" modelAttribute="leaveapplyform">
<spring:message code="label.leaveType"/>
<form:select path="LeaveType" id="date">
<form:option value="Five Live Carry Forward"></form:option>
<form:option value="Live Carry Forward"></form:option>
<form:option value="Hello"></form:option></form:select>
<spring:message code="label.leavePeriod"/>
<form:select path="leavePeriod" name="leavePeriod" id="choice" class="date" onchange="ShowReg(this.selectedIndex)">
<form:option value="Platinum Package" ></form:option>
<form:option value="Gold Package"></form:option></form:select>
<div id="Platinum" style="display:none">
<div class="style12"><spring:message code="label.selectHours" /></div>
<form:select path="selectHours" name="eselect" id="selecte" class="date" onchange="ShowSkill(this.selectedIndex)">
<form:option selected="selected" value="event_select"></form:option>
<form:option value="event_golf"></form:option>
<form:option value="event_other"></form:option>
<form:option value="event_golf"></form:option>
<form:option value="event_other"></form:option></form:select>
</div>
<div id="Gold" style="display:none">
</div>
<spring:message code="label.firstApprover"/>
<form:select path="firstApprover"name="firstApprover" id="date">
<form:option value="Full Day " ></form:option>
<form:option value="Half Day"></form:option>
</form:select>
<spring:message code="label.finalApprover"/>
<form:select path="finalApprover" id="date" name="finalApprover" >
<form:option value="Full Day " >Zafar .M . </form:option>
<form:option value="Half Day">Raut . P</form:option></form:select>
<input type="submit" class="submit" name="submit" value="Submit">
<input type="reset" name="reset"class="reset" value="Reset">
</form:form>
</div>
<script type="text/javascript">
function ShowReg(op) {
document.getElementById('Platinum').style.display = 'none';
document.getElementById('Gold').style.display = 'none';
if (op == 1) {
document.getElementById('Platinum').style.display = "block";
}
if (op == 2) {
document.getElementById('Gold').style.display = "block";
}
}
function ShowSkill(op) {
document.getElementById('golf').style.display = 'none';
document.getElementById('other').style.display = 'none';
if (op == 1) {
document.getElementById('golf').style.display = "block";
}
if (op == 2) {
document.getElementById('other').style.display = "block";
}
}
</script>
</body>
</html>
Problem is with your showForm() method.
Probable Mistake 1:
May be in your jsp you have given name as "registerForm"
<form:form modelAttribute="registerForm"> //Change to leaveapplyform
or
<form:form commandName="registerForm">
And here you are writing as
model.put("leaveapplyform", leaveapplyform);
Change it either in jsp or here.
Probable Mistake 2 and can say Actual mistake
your validateUser() is always returning false;
Hence in processForm your control is going to
else{
System.out.println("------do not come here------------------");
return GlobalConstants.REGISTER_PAGE;
}
So here your view set is register***.jsp which may have
<form:form commandName="registerForm">
So you don't have registerForm Command coming from processForm.
So inorder to make it work make this change in your validateUser() method.
if(status>0){
System.out.println("Employee Account Created Scuucessfully");
return true;
}

spring form controller with html checkbox

I am trying to bind the input type checkbox using spring form controller,But i failed .
Here i am posting Controller,bean and jsp example,One more thing is i can't use
.
Below is the code:
Controller:
package com.test.web;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import com.vaannila.domain.User;
import com.vaannila.service.UserService;
#SuppressWarnings("deprecation")
public class UserController extends SimpleFormController {
private UserService userService;
public UserController() {
setCommandClass(User.class);
setCommandName("user");
}
public void setUserService(UserService userService) {
this.userService = userService;
}
#Override
protected ModelAndView onSubmit(Object command) throws Exception {
User user = (User) command;
user.setCommunity(user.getCommunity());
userService.add(user);
return new ModelAndView("userForm","user",user);
}
}
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>Registration Page</title>
<script>
function submitForm(){
document.testForm.submit();
}
</script>
</head>
<body>
<form:form method="POST" commandName="user" name="testForm" action="./userRegistration.htm">
<table>
<tr>
<td>User Name :</td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Password :</td>
<td><form:password path="password" /></td>
</tr>
<tr>
<td>Gender :</td>
<td><form:radiobutton path="gender" value="M" label="M" />
<form:radiobutton path="gender" value="F" label="F" /></td>
</tr>
<tr>
<td>Country :</td>
<td><form:select path="country">
<form:option value="0" label="Select" />
<form:option value="1" label="India" />
<form:option value="2" label="USA" />
<form:option value="3" label="UK" />
</form:select></td>
</tr>
<tr>
<td>About you :</td>
<td><form:textarea path="aboutYou" /></td>
</tr>
<tr>
<td>Community :</td>
<td><input type="checkbox" name="community" value="Hibernate"/>Hibernate</br>
<input type="checkbox" name="community" value="test"/>test</br>
<input type="checkbox" name="community" value="test1"/>test1</br>
</td>
</tr>
<tr>
<td></td>
<td><form:checkbox path="mailingList"
label="Would you like to join our mailinglist?" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" onclick="submitForm();"></td>
</tr>
</table>
</form:form>
</body>
</html>
Java beans:
package com.test.domain;
public class User {
private String name;
private String password;
private String gender;
private String country;
private String aboutYou;
private String[] community;
private Boolean mailingList;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getAboutYou() {
return aboutYou;
}
public void setAboutYou(String aboutYou) {
this.aboutYou = aboutYou;
}
public String[] getCommunity() {
return community;
}
public void setCommunity(String[] community) {
this.community = community;
}
public Boolean getMailingList() {
return mailingList;
}
public void setMailingList(Boolean mailingList) {
this.mailingList = mailingList;
}
}
I tried different ways,but no luck.Any hints please.
the browser will not send the field in the request if the checkbox isn't checked. the value will either be "true" or not sent. you will never get a "false" value.
add a hidden field with _name for every checkbox
EX:
<input type="checkbox" name="community" value="Hibernate"/>
<input type="hidden" name="_community" value="on"/>
Then, spring will take care of it.
If you do not use the form tag it will not automaticly bind your checkboxes. If you use plain html you have to bind the your self.
You can solve this by adding a list of community objects and then use form:checkboxes.
For example:
<form:checkboxes path="communityList" items="${communityList}" itemValue="key" itemLabel="value" />
I would also recomend you to use a HashMap when using ModelAndView like this:
Map<String, Object> model = new HashMap<String, Object>();
model.put("user", user);
model.put("communityList", communityList);
return new ModelAndView("userFormat", model);
Manually bind using 'ServletRequestUtils'... http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/bind/ServletRequestUtils.html
Example
public ModelAndView test(HttpServletRequest request, HttpServletResponse response) throws ServletRequestBindingException {
Long subscriptionOwnerId = ServletRequestUtils.getLongParameter(request, "id");
return new ModelAndView('test'); }`

Resources