I have checked so many answers here for the same but it seems nothing worked for me. I have spring security with spring mvc. when my user is trying to sign up I am sending post data to my controller. but it is giving me 405 post not supported I have disabled csrf token in security config. please let me know where did I go wrong?
Here's my webSecurityConfigureDapter:
package org.pkb.springlogin.config;
import org.pkb.springlogin.authentication.MyDBAuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#Configuration
// #EnableWebSecurity = #EnableWebMVCSecurity + Extra features
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
MyDBAuthenticationService myDBAauthenticationService;
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// Users in memory.
auth.inMemoryAuthentication().withUser("user1").password("12345").roles("USER");
auth.inMemoryAuthentication().withUser("admin1").password("12345").roles("USER, ADMIN");
// For User in database.
auth.userDetailsService(myDBAauthenticationService);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
// The pages does not require login
http.authorizeRequests().antMatchers("/", "/welcome", "/login", "/logout","/signUp").permitAll();
// /userInfo page requires login as USER or ADMIN.
// If no login, it will redirect to /login page.
http.authorizeRequests().antMatchers("/userInfo").access("hasAnyRole('ROLE_USER', 'ROLE_ADMIN')");
// For ADMIN only.
http.authorizeRequests().antMatchers("/admin").access("hasRole('ROLE_ADMIN')");
// When the user has logged in as XX.
// But access a page that requires role YY,
// AccessDeniedException will throw.
http.authorizeRequests().and().exceptionHandling().accessDeniedPage("/403");
// Config for Login Form
http.authorizeRequests().and().formLogin()//
// Submit URL of login page.
.loginProcessingUrl("/j_spring_security_check") // Submit URL
.loginPage("/login")//
.defaultSuccessUrl("/userInfo")//
.failureUrl("/login?error=true")//
.usernameParameter("username")//
.passwordParameter("password")
// Config for Logout Page
.and().logout().logoutUrl("/logout").logoutSuccessUrl("/logoutSuccessful");
}
}
Here's my sign up page
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# page isELIgnored="false"%>
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
<html lang="en">
<head>
<link rel="stylesheet" href="<c:url value="/resources/css/bootstrap-theme.min.css"/>">
<link rel="stylesheet" href="<c:url value="/resources/css/bootstrap.min.css"/>">
<title>Sign Up Form</title>
<meta http-equiv="Content-Type" content="text/html charset=UTF-8" />
</head>
<body>
<div class="jumbotron page-header">
<h2>Login</h2>
</div>
<form:form class="form-horizontal" method="post"
name="userReg" id="userReg" modelAttribute="userForm" action="${contextPath}/login">
<div class="container">
<label class="col-sm-2 control-label">Name</label>
<div class="col-sm-4">
<input name="userName" type="text" class="form-control" id="userName" placeholder="Name" />
</div>
</div>
<br>
<div class="container">
<label class="col-sm-2 control-label">Email</label>
<div class="col-sm-4">
<input name="email" class="form-control" id="email" placeholder="Email" />
</div>
</div>
<br>
<div class="container">
<label class="col-sm-2 control-label">Date of Birth(dd-mm-yyyy)</label>
<div class="col-sm-4">
<input name="dob" type="text" class="form-control" id="dob" placeholder="Date of birth" />
</div>
</div>
<br>
<div class="container">
<label class="col-sm-2 control-label">Password</label>
<div class="col-sm-4">
<input name="password" type="password" class="form-control" id="password" placeholder="password" />
</div>
</div>
<br>
<div class="container">
<label class="col-sm-2 control-label">Confirm Password</label>
<div class="col-sm-4">
<input name="confirmPassword" type="password" class="form-control" id="cpassword" placeholder="confirm password" />
<span id='message'></span>
</div>
</div>
<br>
<div class="container">
<label class="col-sm-2 control-label">User type</label>
<div class="col-sm-4">
<select class="form-control" name="type" >
<option selected="selected">--select--</option>
<option value="user" >User</option>
<option value="admin">Admin</option>
</select>
</div>
</div>
<br>
<br>
<div class="col-md-6 center-block">
<input type="submit" class="btn-lg btn-primary center-block" value="save">
</div>
</form:form>
</body>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.1/jquery.validate.min.js"></script>
<script src="<c:url value="/resources/js/form-validation.js"/>"></script>
<script src="<c:url value="/resources/js/passwordVerification.js"/>"></script>
</html>
Here's my MainController
package org.pkb.springlogin.controller;
import java.security.Principal;
import org.pkb.springlogin.manager.SignUpHandler;
import org.pkb.springlogin.model.SignUpInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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;
#Controller
public class MainController {
#Autowired
SignUpHandler signupHandler;
private static final Logger logger =LoggerFactory.getLogger(MainController.class);
#RequestMapping(value = { "/", "/welcome" }, method = RequestMethod.GET)
public String welcomePage(Model model) {
model.addAttribute("title", "Welcome");
model.addAttribute("message", "Hello friend!");
return "welcomePage";
}
#RequestMapping(value = "/admin", method = RequestMethod.GET)
public String adminPage(Model model) {
return "adminPage";
}
#RequestMapping(value="/signUp",method=RequestMethod.POST)
public String userLogin(#ModelAttribute("userForm") SignUpInfo user,ModelMap model){
System.out.println(user);
Integer id=signupHandler.process(user);
if(id!=null){
logger.debug("ID in controller:"+id);
return "success";
}
logger.error("error in controller");
return "Failure";
}
#RequestMapping(value="/signUp",method=RequestMethod.GET)
public String register(Model model){
SignUpInfo user=new SignUpInfo();
model.addAttribute("userForm", user);
return "signUp";
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginPage(Model model ) {
return "loginPage";
}
#RequestMapping(value = "/logoutSuccessful", method = RequestMethod.GET)
public String logoutSuccessfulPage(Model model) {
model.addAttribute("title", "Logout");
return "logoutSuccessfulPage";
}
#RequestMapping(value = "/userInfo", method = RequestMethod.GET)
public String userInfo(Model model, Principal principal) {
// After user login successfully.
String userName = principal.getName();
System.out.println("User Name: "+ userName);
return "userInfoPage";
}
#RequestMapping(value = "/403", method = RequestMethod.GET)
public String accessDenied(Model model, Principal principal) {
if (principal != null) {
model.addAttribute("message", "Hi " + principal.getName()
+ "<br> You do not have permission to access this page!");
} else {
model.addAttribute("msg",
"You do not have permission to access this page!");
}
return "403Page";
}
}
Here's my signUpInfo
package org.pkb.springlogin.model;
public class SignUpInfo {
private String userName;
private String password;
private String confirmPassword;
private Type type;
private Byte enabled;
public Byte getEnabled() {
return enabled;
}
public void setEnabled(Byte enabled) {
this.enabled = enabled;
}
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 getConfirmPassword() {
return confirmPassword;
}
public void setConfirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
#Override
public String toString() {
return "SignUpInfo [userName=" + userName + ", password=" + password + ", confirmPassword=" + confirmPassword
+ ", type=" + type + "]";
}
}
Form is POST-ed to /login
action="${contextPath}/login"
but login is annotated to support only GET
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginPage(Model model ) {
return "loginPage";
}
maybe you should post to /signUp
Related
I am writing a page with user registration. Faced a display problem in the form of validation errors
My Controller:
#Controller
public class UIController {
private final Logger log = LoggerFactory.getLogger(getClass());
#Autowired
private UserService service;
#Autowired
private SecurityService securityService;
#Autowired
private UserValidator validator;
#PostMapping(value = "/login")
public String signIn(#ModelAttribute("userForm") UserTo userForm, BindingResult bindingResult, Model model) {
validator.validate(userForm, bindingResult);
User user = service.findByLogin(UserUtil.createNewFromTo(userForm).getLogin());
if (!userForm.getPassword().equals(user.getPassword())) {
log.info("invalid password {}", user);
return "redirect:/login";
}
log.info("signIn {}", user);
securityService.autologin(user.getLogin(), user.getPassword());
return "redirect:/welcome";
}
}
My Validator:
#Component
public class UserValidator implements Validator {
#Autowired
private UserRepositoryImpl userRepository;
#Override
public boolean supports(Class<?> aClass) {
return UserTo.class.equals(aClass);
}
#Override
public void validate(Object o, Errors errors) {
UserTo user = (UserTo) o;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "login", "NotEmpty");
if (user.getLogin().length() < 6 || user.getLogin().length() > 32) {
errors.rejectValue("login", "Size.userForm.login");
}
if (userRepository.findByLogin(user.getLogin()) != null) {
errors.rejectValue("login", "Duplicate.userForm.login");
}
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "NotEmpty");
if (user.getPassword().length() < 8 || user.getPassword().length() > 32) {
errors.rejectValue("password", "Size.userForm.password");
}
}
}
My jsp form :
<div id="wrapper">
<!--SLIDE-IN ICONS-->
<div class="user-icon"></div>
<div class="pass-icon"></div>
<!--END SLIDE-IN ICONS-->
<!--LOGIN FORM-->
<form:form name="login-form" modelAttribute="userForm" class="login-form" method="post" id="form">
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
<!--CONTENT-->
<div class="content">
<!--USERNAME-->
<spring:bind path="login">
<div class="form-group ${status.error ? 'has-error' : ''}">
<form:input name="login" id="login" type="text" path="login" class="input username"
placeholder="Login"></form:input>
<form:errors path="login"></form:errors>
</div>
</spring:bind>
<!--END USERNAME-->
</div>
<!--END CONTENT-->
<!--FOOTER-->
<div class="footer">
<button class="button" type="submit">Login</button>
<button class="register" type="button" name="submit" onclick=" register_url('${contextPath}/registration')">
Register
</button>
</div>
<!--END FOOTER-->
</form:form>
</div>
When debugging in chrome when sending a POST request, a 302 HTTP error appears.
Accordingly, if I set a breakpoint in the controller, then the debug is not processed.
Tell me what could be the problem?
The "form" tag in your jsp does not have "action" attribute.
You should not redirect on errors, because the redirect will erase the binding result. Instead do :
if (!userForm.getPassword().equals(user.getPassword())) {
log.info("invalid password {}", user);
return "login";
}
I'm facing an issue with spring and thymeleaf, i'm trying to fill a form with data from an entity called cliente, but i'm getting a Whitelabel Error Page message in the browser and this message in the console
Neither BindingResult nor plain target object for bean name 'cliente' available as request attribute
this is the Cliente
package com.bolsadeideasspringboot.app.models.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import org.springframework.format.annotation.DateTimeFormat;
#Entity
#Table(name="clientes")
public class Cliente implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotEmpty
private String nombre;
#NotEmpty
private String apellido;
#NotEmpty
#Email
private String email;
#Column(name="create_at")
#Temporal(TemporalType.DATE)
#DateTimeFormat(pattern="dd/MM/yyyy")
private Date createAt;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellido() {
return apellido;
}
public void setApellido(String apellido) {
this.apellido = apellido;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getCreateAt() {
return createAt;
}
public void setCreateAt(Date createAt) {
this.createAt = createAt;
}
}
this is the controller method
#RequestMapping(value="/form/{id}")
public String editar(#ModelAttribute("form") #PathVariable(value="id")Long id, Map<String, Object>model) {
Cliente cliente = null;
if(id > 0) {
clientedao.findOne(id);
model.put("cliente", cliente);
model.put("titulo", "Editar Cliente");
return "form";
}
else {
return "redirect:/listar";
}
}
this is the ClienteDaoImpl.java method
#Override
public Cliente findOne(Long id) {
// TODO Auto-generated method stub
return em.find(Cliente.class, id);
}
this is the Dao interface method
public Cliente findOne(Long id);
and this is the form
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title th:text="${titulo}">Insert title here</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-3">
<h1 class="text-success" th:text="${titulo}"></h1>
<form th:action="#{/form}" th:object="${cliente}" method="post">
<div class="form-group">
<label>Nombre</label>
<input class="form-control" type="text" th:field="*{nombre}" placeholder="Nombre"/>
<small class="form-text text-danger" th:if="${#fields.hasErrors('nombre')}" th:errors="*{nombre}"></small>
</div>
<div class="form-group">
<label>Apellido</label>
<input class="form-control" type="text" th:field="*{apellido}" placeholder="Apellido"/>
<small class="form-text text-danger" th:if="${#fields.hasErrors('apellido')}" th:errors="*{apellido}"></small>
</div>
<div class="form-group">
<label>Email</label>
<input class="form-control" type="text" th:field="*{email}" placeholder="correo#ejemplo.com"/>
<small class="form-text text-danger" th:if="${#fields.hasErrors('email')}" th:errors="*{email}"></small>
</div>
<div class="form-group">
<label>Fecha</label>
<input class="form-control" type="text" th:field="*{createAt}" placeholder="DD/MM/YYYY"/>
<small class="form-text text-danger" th:if="${#fields.hasErrors('createAt')}" th:errors="*{createAt}"></small>
</div>
<div class="form-group">
<input class="btn btn-primary" type="submit" value="Crear Cliente" />
</div>
<input type="hidden" th:field="*{id}" />
</form>
</div>
</div>
</div>
</body>
</html>
i'm setting the cliente in the controller method and i'm using th:object in the form, so i don't know what i'm doing wrong, any help would be helpul, thanks in advice
Instead of put(), try using the recommended approach to adding an object to your model with
model.addAttribute("cliente", clientedao.findOne(id));
You typically want to use #GetMapping as well for your requests to populate the form. And use #PostMapping for submissions.
Aside: also take a look at Project Lombok to make your beans less error-prone and more readable. You could remove all those getters and setters and just annotate the class with #Data.
While not deprecated, you'll also want to move away from using java.util.Date and use the newer date/time classes.
I'm getting a 400 bad request error while submitting my form.
I'm using spring 4.0.6 version. I don't why this is happening. Please see the below error what I'm getting.
Here is my JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# page isELIgnored="false" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<script src="<c:url value='/static/js/jquery-3.3.1.js' />"></script>
<script src="<c:url value='/static/js/bootstrap.min.js' />"></script>
<script src="<c:url value='/static/js/jquery.validate.min.js' />"></script>
<script src="<c:url value='/static/js/additional-methods.min.js' />"></script>
<script src="<c:url value='/static/js/jquery.mask.js' />"></script>
<script src="<c:url value='/static/js/jquery-ui.js' />"></script>
<link href="<c:url value='/static/css/bootstrap.min.css' />" rel="stylesheet"></link>
<link href="<c:url value='/static/css/jquery-ui.css' />" rel="stylesheet"></link>
<style>
.head-color {
background: rgb(243, 246, 234);
color: #800000;
text-align:center;
}
.date-width{
width:25% !important;
}
.error{
color:red;
}
</style>
<script type="text/javascript">
$(function() {
document.getElementById("claimFilingForm").reset();
$('.phone-us').mask('(000) 000-0000');
$('.zip-code').mask('00000-0000');
$( "#phoneAssignedDate" ).datepicker();
jQuery.validator.addMethod("valueNotEquals", function(value, element, arg){
return arg !== value;
}, "This field is required.");
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$( "#claimFilingForm" ).validate({
rules: {
firstName: {
required: true
},
lastName: {
required: true
},
address: {
required: true
},
city: {
required: true
},
state: {
required: true
// valueNotEquals: "default"
},
nickname: {
required: true
},
zip: {
required: true,
zipcodeUS: true
},
phone: {
required: true,
phoneUS: true
},
email: {
required: true,
email: true
},
optradio: {
required: true
},
phoneAssignedDate: {
required: {
depends: function() {
return $('input[name="optradio"]:checked').val() == 'N';
}
}
},
signature: {
required: true
}
},
messages: {
},
errorPlacement: function(error, element) {
var placement = $(element).data('error');
if (placement) {
$(element).css("display","");
$(placement).append(error);
} else {
error.insertAfter(element);
}
},
submitHandler: function(form) {
if ($(form).valid())
{
form.submit();
}
return false; // prevent normal form posting
}
})
});
</script>
</head>
<body>
<div class="container">
<h2 class="well head-color">CLAIM FILING</h2>
<div class="form-group">
<span style="font-weight: bold; color: #875a24;">This is a claim in connection with a class of persons
who were successfully sent unsolicited Pollo Trophical Commercial text messages on
what are commonly called recycled numbers between March 1, 2012 and March 15, 2017</span>
</div>
<div class="col-lg-12 well">
<div class="row">
<form:form id="claimFilingForm" modelAttribute="claimant" method="POST" action="claimFiling">
<div class="col-sm-12">
<div class="form-group">
<span style="font-weight: bold;">1. You Must Provide Your Contact Information, including any nicknames or
aliases or any name you use to obtain mobile telephone service for you or your
family members</span>
</div>
<div class="row">
<div class="col-sm-6 form-group">
<label>First Name</label>
<form:input type="text" id="firstName" name="firstName" path="firstName" placeholder="Enter First Name" class="form-control" autofocus=""/>
</div>
<div class="col-sm-6 form-group">
<label>Last Name</label>
<form:input type="text" id="lastName" name="lastName" path="lastName" placeholder="Enter Last Name" class="form-control"/>
</div>
</div>
<div class="form-group">
<label>Address</label>
<form:textarea placeholder="Enter Address" id="address" name="address" path="address" rows="3" class="form-control"></form:textarea>
</div>
<div class="row">
<div class="col-sm-4 form-group">
<label>City</label>
<form:input type="text" id="city" name="city" path="city" placeholder="Enter City Name" class="form-control"/>
</div>
<div class="col-sm-4 form-group">
<label>State</label>
<form:input type="text" id="state" name="state" path="state" placeholder="Enter State Name" class="form-control"/>
</div>
<div class="col-sm-4 form-group">
<label>Zip</label>
<form:input type="text" id="zip" name="zip" path="zip" placeholder="Enter Zip5-Zip4 Code" class="form-control zip-code"/>
</div>
</div>
<div class="row">
<div class="col-sm-6 form-group">
<label>Company/Nickname/Alias</label>
<form:input type="text" id="nickname" name="nickname" path="nickname" placeholder="Enter Company/Nickname/Alias" class="form-control"/>
</div>
<div class="col-sm-6 form-group">
<label>Phone Number</label>
<form:input type="text" id="phone" name="phone" path="phone" placeholder="Enter Phone Number" class="form-control phone-us"/>
</div>
</div>
<div class="form-group">
<label>Email Address</label>
<form:input type="text" id="email" name="email" path="email" placeholder="Enter Email Address" class="form-control"/>
</div>
<div class="form-group">
<br/><br/>
<span style="font-weight: bold;">2. You Must Verify Ownership of the Number Listed Above please select one</span>
</div>
<div class="form-group radio">
<label><form:radiobutton id="optradio1" name="optradio" path="optradio" value="N" data-error="#optradio-error"/>The telephone number listed above was assigned
to me as of below mentioned date
and I did not consent to receive Pollo Trophical advertising text messages
<form:input type="text" id="phoneAssignedDate" name="phoneAssignedDate" placeholder="Select a Date" path="phoneAssignedDate" class="form-control date-width" style="cursor: pointer;" readonly="true"/></label>
</div>
<br/>
<div class="form-group radio">
<label><form:radiobutton id="optradio2" name="optradio" path="optradio" value="Y" />The number listed above was assigned to me and I consented to receive texts from Pollo Trophical</label>
</div>
<div class="form-group">
<span id="optradio-error" class="text-danger align-middle error">
<!-- Put name validation error messages here -->
</span>
</div>
<div class="form-group">
<label>Signature</label>
<form:input type="text" id="signature" name="signature" path="signature" placeholder="Enter Your Name" class="form-control"/>
</div>
<button type="submit" class="btn btn-lg btn-info">Submit</button>
</div>
</form:form>
</div>
</div>
</div>
</body>
</html>
Here is my Controller
package com.application.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.application.model.Claimant;
import com.application.service.ClaimFilingService;
#Controller
#RequestMapping("/")
public class ClaimFilingController {
#Autowired
private ClaimFilingService claimFilingService;
#RequestMapping(value = { "/" }, method = RequestMethod.GET)
public String home(ModelMap model) {
return "redirect:/claimFiling";
}
/*
* This method will serve as default GET handler.
*/
#RequestMapping(value = { "/claimFiling" }, method = RequestMethod.GET)
public String newRegistration(ModelMap model, HttpServletRequest request) {
Claimant claimant = new Claimant();
model.addAttribute("claimant", claimant);
return "claimFiling";
}
/*
* This method will be called on form submission, handling POST request It
* also validates the user input
*/
#RequestMapping(value = { "/claimFiling" }, method = RequestMethod.POST)
public String saveRegistration(#ModelAttribute("claimant") Claimant claimant, ModelMap model, HttpServletRequest request) {
String result = claimFilingService.insertClaimDetails(claimant, request);
if(!result.equalsIgnoreCase("")) {
model.addAttribute("ClaimId", result);
return "success";
}
model.addAttribute("message","Process Failed");
return "claimFiling";
}
}
Here is my Claimant model class
package com.application.model;
import java.sql.Date;
public class Claimant {
private String firstName;
private String lastName;
private String address;
private String city;
private String state;
private String zip;
private String nickname;
private String phone;
private String email;
private String optradio;
private Date phoneAssignedDate;
private String signature;
public Claimant(String firstName, String lastName, String address, String city, String state, String zip,
String nickname, String phone, String email, String optradio, Date phoneAssignedDate, String signature) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.city = city;
this.state = state;
this.zip = zip;
this.nickname = nickname;
this.phone = phone;
this.email = email;
this.optradio = optradio;
this.phoneAssignedDate = phoneAssignedDate;
this.signature = signature;
}
public Claimant() {
super();
// TODO Auto-generated constructor stub
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getOptradio() {
return optradio;
}
public void setOptradio(String optradio) {
this.optradio = optradio;
}
public Date getPhoneAssignedDate() {
return phoneAssignedDate;
}
public void setPhoneAssignedDate(Date phoneAssignedDate) {
this.phoneAssignedDate = phoneAssignedDate;
}
public String getSignature() {
return signature;
}
public void setSignature(String signature) {
this.signature = signature;
}
}
I'm a beginner to spring so can some body help me to identify the problem.
Yes, I found the mistake. In the POJO class I changed the type of phoneAssignedDate to String. This resolved my problem :-)
In this jsp, I have used 2 form actions, one to save the role(table:defining role), and other to call the drop list from other table(table: solutionList).
After clicking on submit, it is not doing anything.
If i remove this form(solutionMaster.html)
Im getting this error " Invalid property 'sMName' of bean class [com.mode;.definingrole]: Bean property 'sMName' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?.
Yes, I know the reason, Because the column 'sMName' was not the part of defining role table. what to do with this.
The Thing i want to know is,
Can we create form inside form?
2.Without creating another form, How can i get the column values of other table to defining role table?
Please help.
Thanks in advance.!!!
<div class="modal inmodal" id="myModalForRole" tabindex="-1"
role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content animated bounceInRight">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span><span class="sr-only">Close</span>
</button>
<i class="fa fa-laptop modal-icon"></i>
<h4 class="modal-title">Define Role</h4>
</div>
<div class="modal-body">
<form:form action="newRoleDetails.html" method="post"
commandName="deftemp" id="deftemp">
<div class="row">
<div class="form-group">
<form:form action="solutionName.html" method="post"
commandName="soltemp" id="soltemp">
<div class="col-sm-6">
<label>Solutions*</label><br>
<form:select path="sMName" class="form-control"
id="sMName">
<form:option value="" label="--select--"></form:option>
<c:forEach var="solutionList" items="${solutionList}"
varStatus="loop">
<form:option value="${solutionList}"
label="${solutionList}">
</form:option>
</c:forEach>
</form:select>
</div>
</form:form>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-sm-6">
<label>Parent Role*</label><br>
<form:textarea path="ParentRole" id="ParentRole"
class="form-control" placeholder="Enter the Parent Role" />
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-sm-6">
<label>Sub Role*</label><br>
<form:textarea path="SubRole" id="SubRole"
class="form-control" placeholder="Enter the Child role" />
</div>
</div>
</div>
<br>
<br>
<div class="modal-footer">
<button type="button" class="btn btn-white"
data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Submit
</button>
</div>
</form:form>
</div>
Models: (solutionlist.java)
package com.model;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table (name="solutionlist")
public class solutionlist implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="solutionId",nullable = false,columnDefinition = "UNSIGNED INT(4)")
Integer solutionId;
#Column(name="solutionName")
String solutionName;
#Column(name="solutionOwner")
String solutionOwner;
#Column(name="ownerMailId")
String ownerMailId;
#Column(name="additionDate")
String additionDate;
public Integer getSolutionId() {
return solutionId;
}
public void setSolutionId(Integer solutionId) {
this.solutionId = solutionId;
}
public String getSolutionName() {
return solutionName;
}
public void setSolutionName(String solutionName) {
this.solutionName = solutionName;
}
public String getSolutionOwner() {
return solutionOwner;
}
public void setSolutionOwner(String solutionOwner) {
this.solutionOwner = solutionOwner;
}
public String getOwnerMailId() {
return ownerMailId;
}
public void setOwnerMailId(String ownerMailId) {
this.ownerMailId = ownerMailId;
}
public String getAdditionDate() {
return new SimpleDateFormat("yyyy-MM-dd HH-mm-ss.SSS")
.format(new Date());
}
public void setAdditionDate(String additionDate) {
this.additionDate = additionDate;
}
}
definingrole.java
package com.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="definingrole")
public class definingrole implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="SNo")
Integer SNo;
#Column(name="Solutions")
String Solutions;
#Column(name="ParentRole")
String ParentRole;
#Column(name="SubRole")
String SubRole;
public Integer getSNo() {
return SNo;
}
public void setSNo(Integer sNo) {
SNo = sNo;
}
public String getSolutions() {
return Solutions;
}
public void setSolutions(String solutions) {
Solutions = solutions;
}
public String getParentRole() {
return ParentRole;
}
public void setParentRole(String parentRole) {
ParentRole = parentRole;
}
public String getSubRole() {
return SubRole;
}
public void setSubRole(String subRole) {
SubRole = subRole;
}
}
Controller : newRoleDetails.html
#RequestMapping(value=NEWROLEDETAILS_PATH)
public String newRoleDetails(Map<String, Object> model, definingrole value,solutionlist sol) throws Exception {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName();
String nameOfUser=TemplateService.getEmpNameOfUser(name);
model.put("nameOfUser",nameOfUser);
String userid=loginService.getUserId();
String role=loginService.getRole();
TemplateService.newRoleDetails(value);
definingrole deftemp=new definingrole();
model.put("deftemp", deftemp);
solutionlist s = new solutionlist();
ArrayList<templateDetails> listOfTemplate=TemplateService.listTemplateDetails(role,userid);
model.put("listOfTemplate",listOfTemplate);
return TEMPLATESUMMARY;
}
controller : solutionName.html
#RequestMapping("/solutionlist.html")
public String solutionName(Map<String, Object> model,solutionlist sol) throws Exception {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName();
String nameOfUser=TemplateService.getEmpNameOfUser(name);
model.put("nameOfUser",nameOfUser);
solutionlist soltemp = new solutionlist();
model.put("soltemp", soltemp);
ArrayList<String> solutionList=TemplateService.getSolutionListForTemplate();
model.put("solutionList", solutionList);
return REDIRECT_TEMPLATESUMMARY_URL;
}
You are trying to populate list inside form under the tag of form. Which is wrong approach. You won't get the value from /solutionlist.html by your form. You have to call at least a GET if you want to use /solutionlist.html controller.
If i think So then you have to do the following
You don't need the '/solutionlist.html' controller.
Just bind the ArrayList solutionList into model in the controller method where the form page served. I mean the GET method of Controller where the given form is served.
ArrayList<String> solutionList=TemplateService.getSolutionListForTemplate();
model.put("solutionList", solutionList);
You will get that solutionList directly to your form as value. So, modify the select part of your form as follows
<select name="solutions"path="Solutions">
<c:forEach items="${solutionList}" var="solution">
<option value="${solution}">${solution}</option>
</c:forEach>
</select>
I'm using a simple Spring form with mustache. However the data is not received in Spring controller. login.getId(), login.getPass() are always received as null in controller. Any clues if something have to be fixed in template or controller?
My template and controller code as below.
<form class="form-signin" id="loginForm" action="{{{appCtxt}}}/login" method="post">
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" name="{{id}}" id="id" class="form-control" placeholder="Email address" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" name="{{pass}}" id="pass" class="form-control" placeholder="Password" required>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
Controller
#Controller
public class LoginController {
private LoginService loginService;
#Autowired
public void setLoginService(LoginService loginService) {
this.loginService = loginService;
}
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView index(HttpServletRequest request, Model model) {
ModelAndView result = new ModelAndView();
model.addAttribute("login", new Login());
result.addObject("resources", request.getContextPath() + "/resources");
result.addObject("appCtxt", request.getContextPath());
// return "redirect:/users";
result.setViewName("home");
return result;
}
#RequestMapping(value = "login", method = RequestMethod.POST)
public String login(Login login, HttpServletRequest request){
boolean status = loginService.verifyLogin(login.getId(), login.getPass());
if(status == true) {
return "redirect:/users";
}
else
{
return "error";
}
}
}
Instead of the name="{{pass}}" you can use name="pass" assuming you Login class contains a field with the very same name. Another thing is that you need '#ModelAttribute' annotation near the Login parameter.
For easier understanding how it works, please consider following example:
Student.java
package me.disper.model;
public class Student {
private String name;
private String surname;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
}
student.html
<!DOCTYPE html>
<html lang="en" xmlns:form="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<title>Create new student</title>
</head>
<body>
<form name="student" action="add" method="post">
Name: <input type="text" name="name" /><br/>
Surname: <input type="text" name="surname" /><br/>
<input type="submit" value="Save" />
</form>
</body>
</html>
MyMustacheController.java
package me.disper;
import me.disper.model.Student;
import org.springframework.stereotype.Controller;
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.servlet.ModelAndView;
#Controller
public class MyMustacheController {
#GetMapping("/student")
public ModelAndView createStudent(){
ModelAndView modelAndView = new ModelAndView("student", "student", new Student());
return modelAndView;
}
#PostMapping("/add")
public ModelAndView addStudent(#ModelAttribute Student student){
ModelAndView modelAndView = new ModelAndView("created", "student", student);
return modelAndView;
}
}
created.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Student created</title>
</head>
<body>
{{#student}}
Hello {{name}} {{surname}}
{{/student}}
</body>
</html>
Take a look at the following tutorial: A guide to forms in Spring MVC. There are some helpful hints like #ModelAttribute.