Spring Thymeleaf Cannot resolve 'global' - spring

i am trying to create login-register page application in spring framework.
In my registration form, intelij idea says Cannot resolve 'global'.
i changed springsecurity4 to springsecurity3 but didn't change anything.
This my form element:
<form class="form-signin" th:action="#{/registration}" th:object="${user}" method="post">
<input type="text" class="form-control" placeholder="Full Name" th:field="*{fullname}" required autofocus>
<label style="color: red" th:if="${#fields.hasErrors('fullname')}" th:errors="*{fullname}">Username Error</label>
<input type="text" class="form-control" placeholder="email" th:field="*{email}" required autofocus>
<label style="color: red" th:if="${#fields.hasErrors('email')}" th:errors="*{email}">Username Error</label>
<input type="password" class="form-control" placeholder="Password ..." name="password" required>
<label style="color: red" th:if="${#fields.hasErrors('password')}" th:errors="*{password}">Password Error</label>
<input type="submit" class="btn btn-lg btn-default btn-block" value="Sign Up" />
<td th:if="${#fields.hasGlobalErrors()}" th:errors="*{global}">Global Error</td>
</form>
this is my html element:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
This is my controller method :
#RequestMapping(value = "/registration", method = RequestMethod.POST)
public ModelAndView createNewUser(#Valid User user, BindingResult bindingResult) {
ModelAndView modelAndView = new ModelAndView();
User userExists = userService.findUserByEmail(user.getEmail());
if (userExists != null) {
bindingResult
.rejectValue("email", "error.user",
"There is already a user registered with the email provided");
}
if (bindingResult.hasErrors()) {
modelAndView.setViewName("registration");
} else {
userService.saveUser(user);
modelAndView.addObject("successMessage", "User has been registered successfully");
modelAndView.addObject("user", new User());
modelAndView.setViewName("registration");
}
return modelAndView;
}
This is my pom.xml file :
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
</dependency>
</dependencies>

I believe the source of the problem is related to the th:object tag and that the solution (actually linked to other related questions) is already to be found here: Spring Thyme Leaf checking for global errors results in NPE
Additionally, I noticed you are using <td> tag outside of a <table> element, this is not how it should be used according to: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td

Related

how fix form validation, when itdoesn't work

I need your help, form validation doesn't work, after following several articles, its still not working
here my pom.xml
<?xml version="1.0" encoding="UTF-8"?>
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.3.2.RELEASE
com.king
Gestpeacesecurity
0.0.1-SNAPSHOT
Gestpeacesecurity
peace security project for Spring Boot
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.0.11.RELEASE</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<version>3.0.11.RELEASE</version>
</dependency>
<dependency>
<groupId>nz.net.ultraq.thymeleaf</groupId>
<artifactId>thymeleaf-layout-dialect</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- <dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency> -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
My entitie Agent, i use lomback for getter and setter
package com.king.Entities;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.springframework.format.annotation.DateTimeFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
#Entity
#Data #NoArgsConstructor #AllArgsConstructor
public class Agent implements Serializable {
#Id
#NotNull
#Size(min=5,max=5)
private String matricule;
#NotNull
#Size(min=4,max=15)
private String nom;
private String prenom;
private String postnom;
private String fonction;
private String typeagent;
private String niveaetude;
private String contact1;
private String contact2;
private String sexe;
private String adresse1;
private String adresse2;
private String photo;
#DateTimeFormat(pattern = "yyyy-MM-dd")
private Date dateNaiss;
private String lieuNais;
private String status;
}
this is my controller
#RequestMapping(value="/showFormAgent", method = RequestMethod.GET)
public String showFormAgent(Model model) {
model.addAttribute("agent", new Agent());
return "peacedrh/formAgent";
}
#RequestMapping(value="addAgent", method = RequestMethod.POST)
public String addAgent(#RequestParam(name="picture")MultipartFile file, Model model, String matricule, #Valid Agent A, BindingResult result) {
try {
if (!(file.isEmpty())) {
A.setPhoto(file.getOriginalFilename());
}
agentDao.AddAgent(matricule, A);
if (!(file.isEmpty())) {
A.setPhoto(file.getOriginalFilename());
file.transferTo(new File (imageDir+A.getMatricule()));
}
} catch (Exception e) {
// TODO: handle exception
model.addAttribute("error", e);
return "redirect:/showFormAgent?matricule="+matricule+"&error="+e.getMessage();
}
model.addAttribute("agent", agentDao.getBymatricule(matricule));
return "peacedrh/Accuse";
}
this my html page(thymeleaf)
<form role="form" method="post" th:action="#{addAgent}" th:object="${agent}" enctype="multipart/form-data">
<div class="card-body">
<div class="form-group">
<label for="exampleInputEmail1">Matricule</label>
<input type="text" th:field="*{matricule}" class="form-control" id="exampleInputEmail1" placeholder="Enter Matricule"/>
<span class="text-danger" th:errors="*{matricule}"> </span>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="exampleInputEmail1">Nom</label>
<input type="text" th:field="*{nom}" class="form-control" id="exampleInputEmail1" placeholder="Enter Nom"/>
<span class="text-danger" th:errors="*{matricule}"> </span>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Post nom</label>
<input type="text" th:field="*{postnom}" class="form-control" id="exampleInputPassword1" placeholder="Post nom"/>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Prenom</label>
<input type="text" th:field="*{prenom}" class="form-control" id="exampleInputPassword1" placeholder="Prenom"/>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Sexe</label>
<select th:field="*{sexe}">
<option value="M">M</option>
<option value="F">F</option>
</select>
</div>
<div class="input-group mb-3">
<div class="form-group">
<label for="exampleInputPassword1">Statut Sociale</label>
<select th:field="*{status}">
<option value="Single">Single</option>
<option value="Maried">Maried</option>
<option value="Veuve">Veuve</option>
<option value="Veuf">Veuf </option>
<option value="Divorce">Divorce</option>
<option value="separe">Separe(é)</option>
</select>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Lieu de naissance</label>
<input type="text" th:field="*{lieuNais}" class="form-control" id="exampleInputPassword1" placeholder="Lieu de naissance"/>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Date de naissance</label>
<input type="date" th:field="*{dateNaiss}" class="form-control"/>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Niveau Etudet</label>
<input type="text" th:field="*{niveaetude}" class="form-control" id="exampleInputPassword1" placeholder="Niveau d'étude"/>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Type Agent</label>
<select th:field="*{typeagent}">
<option value="Admin">Admnistratif</option>
<option value="Terrain">Terrain</option>
</select>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="exampleInputPassword1">Fonction</label>
<select th:field="*{fonction}">
<option value="Comptable">Comptable</option>
<option value="DRH">Direc Res Hum</option>
</select>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Contact 1</label>
<input type="text" th:field="*{contact1}" class="form-control" id="exampleInputPassword1" placeholder="Contat 1"/>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Contact 2</label>
<input type="text" th:field="*{contact2}" class="form-control" id="exampleInputPassword1" placeholder="Contact 2"/>
</div>
<div class="form-group">
<label for="exampleInputFile">File input</label>
<div class="input-group">
<div class="custom-file">
<input type="file" name="picture" class="custom-file-input" id="exampleInputFile"/>
<label class="custom-file-label" for="exampleInputFile">Choose file</label>
</div>
</div>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Adresse 1</label>
<textarea th:field="*{adresse1}" class="form-control" rows="5" cols="5"></textarea>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Adresse 2</label>
<textarea th:field="*{adresse2}" class="form-control" rows="5" cols="5"></textarea>
</div>
</div>
</div>
<div class="card-footer">
<div class="row col-md-5 ml-20" >
<div class="col-md-6"><button type="submit" class="btn btn-primary">Submit</button></div>
<div class="col-md-6"><button type="reset" class="btn btn-primary">Cancel</button></div>
</div>
</div>
</form>
the addition is going well but the form validation still does not work
You must add a #RequestBody because you want to request the form from the view:
#Valid Agent A
Becomes
#Valid #RequestBody Agent A
Otherwise you can pass the Agent object as a #ModelAttribute on your showFormAgent
public String showFormAgent(#ModelAttribute Agent A) {
return "peacedrh/formAgent";
}
and then just get the data from your addAgent
#RequestMapping(value="addAgent", method = RequestMethod.POST)
public String addAgent(#ModelAttribute #Valid Agent A, BindingResult result) { //doSomething }
and the BindingResult holds the validation result so you have to check whether you have errors or not:
if (result.hasErrors()) {
return "previus_form";
} else {
return "success";
}

springMVC 5.1.6 validation not working (BindingResult errors are 0 ?)

I am facing an issue with my "User" Object being Validated before being registered into a database
Used Technologies :
- Spring Web MVC with Hibernate Validator
- Spring Data (JDBC)
- Maven
Here is a snippet from my Controller Code :
#RequestMapping(method = RequestMethod.POST,params = "add")
public ModelAndView add(#Valid #ModelAttribute("user") User user, BindingResult result) throws Exception {
if (!result.hasErrors()) { // ERRORS NEVER HAPPEN ??
userDao3.insertUser(user);
}
return returnHome();
}
my User Validation is as follows :
#Size(min = 3, max = 20, message = "{required.name}")
String name;
#Min(value = 25, message = "{min.age}")
int age;
#Min(value = 2000, message = "{invalid.salary}")
float salary;
my jsp layout as follows :
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
<div class="container">
<form:form method="post" action="${contextPath}/?add" modelAttribute="user">
<div class="row">
<div class="col-15">
<tags:message code="field.username"/>
</div>
<div class="col-50">
<form:input cssClass="field" path="name"/>
</div>
<div class="col-25">
<form:errors path="name"/>
</div>
</div>
<div class="row">
<div class="col-15">
<tags:message code="field.age"/>
</div>
<div class="col-50">
<form:input cssClass="field" path="age"/>
</div>
<div class="col-25">
<form:errors path="age"/>
</div>
</div>
<div class="row">
<div class="col-15">
<tags:message code="field.salary"/>
</div>
<div class="col-50">
<form:input cssClass="field" path="salary"/>
</div>
<div class="col-25">
<form:errors path="salary"/>
</div>
</div>
<div class="row">
<input type="submit" value="Submit">
</div>
</form:form>
my Spring mvc Configuration xml file :
<mvc:annotation-driven/>
<bean name="homeController" class="Controllers.HomeController">
<property name="userDao2" ref="userDao2"/>
<property name="userDao3" ref="userDao3"/>
</bean>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>naming</value>
<value>ValidationMessages</value>
</list>
</property>
</bean>
and my pom's dependencies are :
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.5.Final</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
the issue is : that on debugging found that errors are always equal to 0 in the BindingResult Object.
Debugging results:
Please help me understand the issue.

Spring controller not able to resolve Thymeleaf template

The controller class is not able to resolve any path except the root.
I have tried putting simple html code in index.html but controller couldn't resolve it. Contoller is able to resolve only this part
#RequestMapping("/")
public String home() {
return "redirect:/index";
}
Controller code:
package com.controller;
import java.util.HashSet;
import java.util.Set;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.userFront.domain.User;
#Controller
public class HomeController {
#RequestMapping("/")
public String home() {
return "redirect:/index";
}
#RequestMapping("/index")
public String index() {
return "index";
}
#RequestMapping(value = "/index", method = RequestMethod.GET)
public String signup(Model model) {
User user = new User();
model.addAttribute("user", user);
return "signup";
}
//
}
pom.xml code: I hope some dependancies are not missing:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.userFront</groupId>
<artifactId>userFront</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>userFront</name>
<description>User front for online banking app</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Code for index.html:
I have tried putting basic html code but wasn't successful in resolving it
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head th:replace="common/header :: common-header"/>
<body>
<!-- Login Section -->
<img class="img-responsive" src="/images/banner.png" alt="banner"/>
<div class="container">
<div class="row ">
<div class="main-center ">
<div class="bg-danger" th:if="${param.error}">
Invalid username and secret.
</div>
<div class="bg-danger" th:if="${param.logout}">
You have been logged out.
</div>
<form class="form-signin" th:action="#{/index}" method="post">
<h2 class="form-signin-heading">Please sign in</h2>
<div class="form-group">
<label for="username" class="sr-only">Username</label>
<input type="text" roleId="username" class="form-control" placeholder="Username" name="username"
id="username"
required="required" autofocus="autofocus"/>
</div>
<div class="form-group">
<label for="password" class="sr-only">Password</label>
<input type="password" roleId="inputPassword" class="form-control" placeholder="Password"
id="password"
name="password" required="required"/>
</div>
<div class="form-group">
<input type="checkbox" name="remember-me" id="remember-me"/> Remember me
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
<hr />
<div class="form-group ">
<a type="submit" class="btn btn-info btn-lg btn-block login-button" th:href="#{/signup}">Sign up!</a>
</div>
</div>
</div>
</div>
<div th:replace="common/header :: body-bottom-scripts"/>
</body>
</html>
I found some of the configuration missed in your pom.xml and configuration level, follow the below steps hope this will help.
1. pom.xml
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
.....
</plugins>
</build>
2. Templates: resources folder path
src/main/resources/templates/index.html
Controller: Not require to redirect
#GetMapping({"/", "/index"})
public String index() {
return "index";
}

form:checkbox/form:<anything> not rendering/displaying in Spring 4, input type="radio”/input type="checkbox" does

I have been asked to upgrade an application that was using Spring 3 (3.1.4.RELEASE and 3.2.5.RELEASE in POM) and have gone to (4.2.2.RELEASE and 4.3.8.RELEASE) respectively (for numerous dependencies. The application used to render correctly, show the JSP but now using any of the existing form:checkbox/form:radiobutton/form:input/form:errors work as the page is just blank, no errors. When I re-write the code and use input type="checkbox”/input type="radio" etc the page now shows ok.
I have looked around loads of examples/forums but nothing I have tried has helped. Am I missing some configuration change elsewhere that is needed? The server is WildFly too, but the application worked fine on this using Spring 3 dependencies.
Example of the JSP (with form:radiobutton/form:checkbox commented out and the other code below it that displays ok), called manageUser.jsp :-
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%# taglib prefix="c" uri="http://java.sun.com/jstl/core_rt"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<div class="contentWrapper">
<fieldset>
<c:if test="${infoFlag}">
<div id="pageMessage">
<p><spring:message code="${infoMessage}"/></p>
</div>
</c:if>
<c:if test="${successFlag !=null && successFlag}">
<div class='message glbMsg success ajaxMsg'>
<span class="infoicon"> </span><p><spring:message code="${successMessage}"/></p>
</div>
</c:if>
<div>
<h3>Manage Users</h3>
<p id="pageIntro">
This section allows you to manage or create users and assign users to roles.
</p>
<div class="col">
<div id="user-tab-container" class="user-tab-container manage-user-page">
<ul class='etabs'>
<li class='usertab'>Manage User</li>
<li class='usertab'>Create User</li>
<li class='usertab' style="display:none;">User Search</li>
</ul>
<div class='panel-container'>
<div id="manage-user">
<form:form id="searchUser" class="singleColForm" method="POST" action="${pageContext.request.contextPath}/admin/searchUser.do" modelAttribute="user">
<div class="col mrgTop10">
<div class="col w2">
<div class="frmFld">
<label for="lastName">Last Name</label>
<input id="lastName" name="lastName" type="text" class="alphanumeric" maxlength="45" value="${user.lastName}" />
</div>
<div class="frmFld">
<label for="firstName">First Name</label>
<input id="firstName" name="firstName" type="text" class="alphanumeric" maxlength="45" value="${user.firstName}" />
</div>
<div class="frmFld">
<label for="eMail">E-mail</label>
<input id="eMail" name="eMail" type="text" class="email" maxlength="100" value="${user.eMail}" />
</div>
<div class="frmFld multiRadio">
<label>Status</label>
<div class="scrollableUserGroup">
<span class="radio">
<input id="userStatus[All]" name="userStatus" type="radio" value="-1" checked/>
<label for="userStatus[All]">All</label>
</span>
<!-- Original that doesn't work now -->
<%-- <c:forEach var="entry" items="${userStatusList}"> --%>
<%-- <span class="radio"> <form:radiobutton --%>
<%-- id="userStatus[${entry.name}]" name="userStatus" --%>
<%-- path="userStatus" value="${entry.id}" /> <label --%>
<%-- for="userStatus[${entry.name}]"><c:out value="${entry.name}"/></label> --%>
<!-- </span> -->
<%-- </c:forEach> --%>
<c:forEach var="entry" items="${userStatusList}">
<span class="radio">
<input type="radio" id="userStatus[${entry.name}]" name="userStatus" value="${entry.id}">
<label for="userStatus[${entry.name}]"><c:out value="${entry.name}"/></label>
</span>
</c:forEach>
</div>
</div>
</div>
<div class="col w2">
<label>User Groups</label>
<div class="frmFld">
<div class="scrollableUserGroup scrollableUserGroups">
<!-- Original that doesn't work now -->
<%-- <c:forEach items="${userGroup}" var="group"> --%>
<!-- <div class="userCB"> -->
<!-- <span class="customCB checkbox"> -->
<%-- <form:checkbox path="userGroups" value="${group.id}" /> --%>
<!-- <span class="box"> -->
<!-- <span class="tick"> </span> -->
<!-- </span> -->
<!-- </span> -->
<%-- <label class="breakword" style="margin-left: 20px;"><c:out value="${group.name}"/></label> --%>
<!-- </div> -->
<%-- </c:forEach> --%>
<c:forEach items="${userGroup}" var="group">
<div class="userCB">
<span class="customCB checkbox">
<input type="checkbox" value="${group.id}" name="userGroups" id="${lstPermission.id}">
<span class="box">
<span class="tick"> </span>
</span>
</span>
<label class="breakword" style="margin-left: 20px;"><c:out value="${group.name}"/></label>
</div>
</c:forEach>
</div>
</div>
</div>
</div>
<div class="buttons">
<a class="btn Big searchUser" href="${pageContext.request.contextPath}/admin/searchUser.do">Search user <span> </span></a>
<span class="hidden"> </span>
</div>
</form:form>
</div>
<div id="create-user">
<!-- Create user -->
</div>
<div id="search-user">
<!-- search user -->
</div>
</div>
</div>
</div>
</div>
</fieldset>
</div>
In another file called tiles-definition.xml it has the JSP filename:-
<definition name="manageUser" template="/WEB-INF/tiles/layout/user/manageUser.jsp" />
In the Controller, it has (with irrelevant other parts removed):
#Controller
#RequestMapping("/admin")
public class UserControllerImpl extends AbstractCommonController implements UserController {
Below is used in JSP
#ModelAttribute("userStatusList")
public Set<UserStatus> populateUserStatus(){
return userHelper.getUserStatusCollection();
}
#ModelAttribute("userGroup")
public Set<UserGroup> populateUserGroup(){
return userHelper.getUserGroupCollection();
}
…
#RequestMapping("/manageUser.do")
public String manageUser(Map<String, Object> model, HttpServletRequest request){
model.put("user", new UserTo());
return "manageUser";
}
…
}
dispatcher-servlet.xml (has the below in it along with some other parts that are needed):-
…
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
<property name="order" value="1"/>
</bean>
POM.xml has (old version commented out, new added in) :-
…
<!-- Spring web dependency -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<!-- <version>3.1.4.RELEASE</version> -->
<version>4.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<!-- <version>3.1.4.RELEASE</version> -->
<version>4.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<!-- <version>3.1.4.RELEASE</version> -->
<version>4.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<!-- <version>3.1.4.RELEASE</version> -->
<version>4.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<!-- <version>3.2.5.RELEASE</version> -->
<version>4.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<!-- <version>3.2.5.RELEASE</version> -->
<version>4.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<!-- <version>3.2.5.RELEASE</version> -->
<version>4.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<!-- <version>3.2.5.RELEASE</version> -->
<version>4.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<!-- <version>3.2.5.RELEASE</version> -->
<version>4.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<!-- <version>3.2.5.RELEASE</version> -->
<version>4.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<!-- <version>3.2.5.RELEASE</version> -->
<version>4.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<!-- <version>3.2.5.RELEASE</version> -->
<version>4.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<!-- <version>3.2.5.RELEASE</version> -->
<version>4.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<!-- <version>3.2.5.RELEASE</version> -->
<version>4.3.8.RELEASE</version>
</dependency>
Any help is much appreciated as I have been thrown in the deep end not knowing too much about Spring and would like to understand and get the original form:radiobutton/form:checkbox/etc working (displaying) and not use the re-written style. Is anything else required for suggestions?

Spring MVC: Controller function not getting called on form submit

I am new to using Spring MVC framework and have designed a html page which has two forms. One is login(form id: loginform) and other is for signup((form id:signupform). The controller is being called correctly for the login page but for the signup, nothing happens (no controller is called) and the page just refreshes. I am not able to find out the source of the problem. Here is my JSP page:
Login.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%#page session="true"%>
<html>
<head>
<title>Login Page</title>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"
integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp"
crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
crossorigin="anonymous">
</script>
<spring:url value="/resources/css/mylogin.css" var="mainCss" />
<link href="${mainCss}" rel="stylesheet" />
<%-- <link href="<spring:url value='/resources/css/mylogin.css'/>" rel="stylesheet"> --%>
</head>
<body>
<div class="container">
<div id="loginbox" style="margin-top: 50px;"
class="mainbox col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
<div class="panel panel-info">
<div class="panel-heading">
<div class="panel-title">Sign In</div>
</div>
<div style="padding-top: 30px" class="panel-body">
<c:if test="${not empty error}">
<!-- Invalid Username Password -->
<div class="error">${error}</div>
</c:if>
<c:if test="${not empty msg}">
<!-- Logged out successfully -->
<div class="msg">${msg}</div>
</c:if>
<div style="display: none" id="login-alert"
class="alert alert-danger col-sm-12"></div>
<form id="loginform" class="form-horizontal" role="form"
name="loginform"
action="<c:url value='/j_spring_security_check' />" method='POST'>
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i
class="glyphicon glyphicon-user"></i></span> <input id="login-username"
type="text" class="form-control" name="username" value=""
placeholder="username">
</div>
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i
class="glyphicon glyphicon-lock"></i></span> <input id="login-password"
type="password" class="form-control" name="password"
placeholder="password">
</div>
<div style="margin-top: 10px" class="form-group">
<div class="col-sm-12 controls">
<input class="btn btn-success" id="btn-login" name="submit"
type="submit" value="LOG IN" /> <input type="hidden"
name="${_csrf.parameterName}" value="${_csrf.token}" />
</div>
</div>
<div class="form-group">
<div class="col-md-12 control">
<div
style="border-top: 1px solid #888; padding-top: 15px; font-size: 85%">
Don't have an account! <a href="#"
onClick="$('#loginbox').hide(); $('#signupbox').show()">
Sign Up Here </a>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<div id="signupbox" style="display: none; margin-top: 50px"
class="mainbox col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
<div class="panel panel-info">
<div class="panel-heading">
<div class="panel-title">Sign Up</div>
</div>
<div class="panel-body">
<form:form id="signupform" class="form-horizontal" role="form"
method="POST" modelAttribute="userForm"
action="<c:url value='/adduser' />">
<div id="signupalert" style="display: none"
class="alert alert-danger">
<p>Error:</p>
<span></span>
</div>
<form:hidden path="id" />
<spring:bind path="name">
<div class="form-group">
<label for="name" class="col-md-3 control-label">Name</label>
<div class="col-md-9">
<form:input path="name" type="text" class="form-control"
name="name" placeholder="Name" />
</div>
</div>
</spring:bind>
<spring:bind path="email">
<div class="form-group">
<label for="email" class="col-md-3 control-label">Email</label>
<div class="col-md-9">
<form:input path="email" type="text" class="form-control"
name="email" placeholder="Email Address" />
</div>
</div>
</spring:bind>
<spring:bind path="username">
<div class="form-group">
<label for="username" class="col-md-3 control-label">Username</label>
<div class="col-md-9">
<form:input path="username" type="text" class="form-control"
name="username" placeholder="Username" />
</div>
</div>
</spring:bind>
<spring:bind path="password">
<div class="form-group">
<label for="password" class="col-md-3 control-label">Password</label>
<div class="col-md-9">
<form:input path="password" type="password"
class="form-control" name="passwd" placeholder="Password" />
</div>
</div>
</spring:bind>
<spring:bind path="dob">
<div class="form-group">
<label for="date" class="col-md-3 control-label">Date of
Birth</label>
<div class="col-md-9">
<form:input path="dob" type="date" name="bday"
class="form-control" />
</div>
</div>
</spring:bind>
<spring:bind path="image">
<div class="form-group">
<label for="pic" class="col-md-3 control-label">Profile
Picture</label>
<div class="col-md-9">
<form:input path="image" type="file" name="pic"
class="form-control" />
</div>
</div>
</spring:bind>
<spring:bind path="genreName">
<div class="form-group">
<label for="genre" class="col-md-3 control-label">Favorite
Genres</label>
<div class="col-md-9">
<!-- <input type="file" name="pic" class="form-control"> -->
<form:select multiple="" path="genreName" name="genreNames"
class="form-control">
<c:forEach items="${genres}" var="genre" varStatus="ctr">
<option id="${genre.id}" value="${genre.name}">${genre.name}</option>
</c:forEach>
</form:select>
</div>
</div>
</spring:bind>
<div class="form-group">
<!-- Button -->
<div class="col-md-offset-3 col-md-9">
<input class="btn btn-info" id="tn-signup" name="submit"
type="submit" value="Sign Up" />
</div>
</div>
<div class="form-group">
<div class="col-md-12 control">
<div
style="border-top: 1px solid #888; padding-top: 15px; font-size: 85%">
Already have an account? <a id="signinlink" href="#"
onClick="$('#signupbox').hide(); $('#loginbox').show()">
Sign In </a>
</div>
</div>
</div>
</form:form>
</div>
</div>
</div>
</div>
</body>
</html>
Controller:
package com.moviebase.web.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
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 org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.moviebase.web.model.user.UserDao;
import com.moviebase.web.model.genre.Genre;
import com.moviebase.web.model.genre.GenreDao;
import com.moviebase.web.model.user.User;
#Controller
public class MainController {
#Autowired
public UserDao userDao;
#Autowired
public GenreDao genreDao;
#RequestMapping(value = { "/", "/welcome**" }, method = RequestMethod.GET)
public ModelAndView defaultPage() {
ModelAndView model = new ModelAndView();
model.addObject("title", "Moviebase");
model.addObject("message", "This is default page!");
model.setViewName("hello");
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String username = auth.getName(); //get logged in username
User user = userDao.findByUsername(username);
System.out.println(user.toString());
return model;
}
#RequestMapping(value = "/admin**", method = RequestMethod.GET)
public ModelAndView adminPage() {
ModelAndView model = new ModelAndView();
model.addObject("title", "Moviebase");
model.addObject("message", "This page is for ROLE_ADMIN only!");
model.setViewName("admin");
return model;
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login(#RequestParam(value = "error", required = false) String error,
#RequestParam(value = "logout", required = false) String logout) {
ModelAndView model = new ModelAndView();
if (error != null) {
System.out.println(" error:"+error);
model.addObject("error", "Invalid username and password!");
}
if (logout != null) {
model.addObject("msg", "You've been logged out successfully.");
}
List<Genre> genreList = genreDao.getAllGenres();
model.addObject("genres", genreList);
User user = new User();
model.addObject("userForm", user);
model.setViewName("login");
return model;
}
#RequestMapping(value = "/adduser", method = RequestMethod.POST)
public ModelAndView createUser(#ModelAttribute("userForm") User user,
BindingResult result) {
// ModelAndView model = new ModelAndView();
// model.setViewName("redirect:/");
System.out.println("Came here");
userDao.insert(user);
return new ModelAndView("redirect:/admin");
}
//for 403 access denied page
#RequestMapping(value = "/403", method = RequestMethod.GET)
public ModelAndView accesssDenied() {
ModelAndView model = new ModelAndView();
//check if user is login
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!(auth instanceof AnonymousAuthenticationToken)) {
UserDetails userDetail = (UserDetails) auth.getPrincipal();
System.out.println(userDetail);
model.addObject("username", userDetail.getUsername());
}
model.setViewName("403");
return model;
}
}
Web.xml
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>MovieBase</display-name>
<!-- Spring MVC -->
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-security.xml,
/WEB-INF/spring-database.xml
</param-value>
</context-param>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>database</groupId>
<artifactId>moviebase</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>Moviebase</name>
<properties>
<jdk.version>1.7</jdk.version>
<spring.version>3.2.8.RELEASE</spring.version>
<spring.security.version>3.2.3.RELEASE</spring.security.version>
<jstl.version>1.2</jstl.version>
<mysql.connector.version>5.1.30</mysql.connector.version>
</properties>
<dependencies>
<!-- Spring 3 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring.security.version}</version>
</dependency>
<!-- Spring Security JSP Taglib -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${spring.security.version}</version>
</dependency>
<!-- jstl for jsp page -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.connector.version}</version>
</dependency>
</dependencies>
<build>
<finalName>moviebase</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
<configuration>
<downloadSources>true</downloadSources>
<downloadJavadocs>false</downloadJavadocs>
<wtpversion>2.0</wtpversion>
</configuration>
</plugin>
</plugins>
</build>
</project>
mvc-dispatcher-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"
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.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.moviebase.*" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
</beans>
Your singup form has the http method POST but your controller is form http method GET
Your JSP:
<form:form id="signupform" class="form-horizontal" role="form"
method="POST" modelAttribute="userForm"
action="<c:url value='/adduser' />">
Your controller:
#RequestMapping(value = "/adduser", method = RequestMethod.GET)
public ModelAndView createUser(#ModelAttribute("userForm") User user,
BindingResult result) {

Resources