Bad request error while submitting a form in Spring 4 - spring

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 :-)

Related

Thymeleaf not loading content when I add validation in Spring Boot

Intro:
My app works in the general sense. All as I want. But when I set up validation (and it does work), it won't load all my hidden content. I moved it all to its own page, and it still did not work. So I am asking here with my original set up. I understand it is messy, but I will clean it up once I figure this out.
I can't find anything related to my problem, which makes me think, the way that I am doing it might not be the best approach. So pointers are more than welcome.
Problem:
Adding Validation to my forms breaks my Thymeleaf template. Unable to hide and unhide elements. It looks stuck. But on the terminal, the program does run fine.
My controller
(it's big... I still need to learn how to break it in smaller chunks.)
#Controller
#SessionAttributes({"guess", "word", "result", "level", "attempt", "message", "credits", "name", "gameScore"})
public class GameController {
private static final String WORD_TO_GUESS_CONSTANT = "WORD_TO_GUESS";
private static final String GUESSED_WORD_CONSTANT = "GUESSED_WORD";
private static final String RESULT_CONSTANT = "RESULT_WORD";
private static final String ATTEMPTS_CONSTANT = "ATTEMPTS";
private static final String TOTAL_ATTEMPTS_CONSTANT = "TOTAL_ATTEMPTS";
private static final String MESSAGE_CONSTANT = "MESSAGE";
private static final String CREDITS_CONSTANT = "CREDITS";
private static final String SELECTED_LEVEL_CONSTANT = "SELECTED_LEVEL";
private static final String NAME_CONSTANT = "NAME";
private static final String GAME_SCORE_CONSTANT = "GAME_SCORE";
private static final String SCORE_MULTIPLIER_CONSTANT = "SCORE_MULTIPLIER";
#Autowired
private RandomWordService randomWord;
#Autowired
private WordCheckService checkGuess;
#Autowired
private IsWordCorrectService isWordCorrectService;
#Autowired
private ScoreSavingService scoreSavingService;
#ModelAttribute("gameDto")
public GameDTO guessDTOForm() {
return new GameDTO();
}
#ModelAttribute("score")
public Score score() {
return new Score();
}
// GAME METHODS
#GetMapping(value = "/index")
public String home(Model model,
final HttpServletRequest request,
final HttpSession session,
GameDTO gameDTO,
Score score) {
model.addAttribute("name", session.getAttribute(NAME_CONSTANT));
model.addAttribute("levelSelected", session.getAttribute(SELECTED_LEVEL_CONSTANT));
model.addAttribute("attempt", session.getAttribute(ATTEMPTS_CONSTANT));
model.addAttribute("credits", session.getAttribute(CREDITS_CONSTANT));
model.addAttribute("attemptStart", session.getAttribute(TOTAL_ATTEMPTS_CONSTANT));
model.addAttribute("guess", session.getAttribute(GUESSED_WORD_CONSTANT));
model.addAttribute("result", session.getAttribute(RESULT_CONSTANT));
model.addAttribute("message", session.getAttribute(MESSAGE_CONSTANT));
model.addAttribute("gameScore", session.getAttribute(GAME_SCORE_CONSTANT));
model.addAttribute("lvlName", Level.values());
return "index";
}
#PostMapping(value = "/loadgame")
public String loadWord(
final HttpSession session, final HttpServletRequest request,
#ModelAttribute("score") Score score,
#Valid GameDTO gameDTO, BindingResult bindingResult,
Model model
) throws IOException {
if (bindingResult.hasErrors()) {
model.addAttribute("lvlName", Level.values());
model.addAttribute("name", session.getAttribute(NAME_CONSTANT));
model.addAttribute("levelSelected", session.getAttribute(SELECTED_LEVEL_CONSTANT));
model.addAttribute("attempt", session.getAttribute(ATTEMPTS_CONSTANT));
model.addAttribute("credits", session.getAttribute(CREDITS_CONSTANT));
model.addAttribute("attemptStart", session.getAttribute(TOTAL_ATTEMPTS_CONSTANT));
model.addAttribute("guess", session.getAttribute(GUESSED_WORD_CONSTANT));
model.addAttribute("result", session.getAttribute(RESULT_CONSTANT));
model.addAttribute("message", session.getAttribute(MESSAGE_CONSTANT));
model.addAttribute("gameScore", session.getAttribute(GAME_SCORE_CONSTANT));
return "index";
}
// NEW GAME
String word = (String) request.getSession().getAttribute(WORD_TO_GUESS_CONSTANT);
if (word == null) {
request.getSession().setAttribute(NAME_CONSTANT, gameDTO.getPlayerName());
request.getSession().setAttribute(ATTEMPTS_CONSTANT, gameDTO.getLvlName().getAttempts());
request.getSession().setAttribute(WORD_TO_GUESS_CONSTANT, randomWord.selectRandomWord());
request.getSession().setAttribute(CREDITS_CONSTANT, gameDTO.getCredit());
request.getSession().setAttribute(SELECTED_LEVEL_CONSTANT, gameDTO.getLvlName().getLvlName());
request.getSession().setAttribute(TOTAL_ATTEMPTS_CONSTANT, gameDTO.getLvlName().getAttempts());
request.getSession().setAttribute(GAME_SCORE_CONSTANT, gameDTO.getScore());
request.getSession().setAttribute(SCORE_MULTIPLIER_CONSTANT, gameDTO.getLvlName().getMultiplier());
gameDTO.setWord((String) session.getAttribute(WORD_TO_GUESS_CONSTANT));
}
model.addAttribute("message", "");
return "redirect:/index";
}
#PostMapping(value = "/guess")
public String guessWord(
final HttpSession session,
final HttpServletRequest request,
#ModelAttribute("score") Score score,
#Valid GameDTO gameDTO, BindingResult bindingResult) throws IOException {
if (bindingResult.hasErrors()) {
return "index";
}
// variables
int attempts = (int) session.getAttribute(ATTEMPTS_CONSTANT);
int credits = (int) session.getAttribute(CREDITS_CONSTANT);
int startAttempts = (int) session.getAttribute(TOTAL_ATTEMPTS_CONSTANT);
String name = (String) session.getAttribute(NAME_CONSTANT);
// check word
String wordToGuess = (String) session.getAttribute(WORD_TO_GUESS_CONSTANT);
String guess = gameDTO.getGuess();
String result = checkGuess.resultWord(wordToGuess, guess);
String lvl = (String) session.getAttribute(SELECTED_LEVEL_CONSTANT);
// adjust score according to result
boolean wordIsCorrect = isWordCorrectService.isTheWordCorrect(result, wordToGuess);
int gameScore = (int) session.getAttribute(GAME_SCORE_CONSTANT);
int scoreMultiplier = (int) request.getSession().getAttribute(SCORE_MULTIPLIER_CONSTANT);
int wrongWord = gameDTO.getWrongWord();
int initialScore = gameDTO.getStartScore();
int finalScorePerWord = initialScore * scoreMultiplier;
// GAME LOGIC
if (!wordIsCorrect) {
String message = "";
message = "Wrong! Try again!";
request.getSession().setAttribute(MESSAGE_CONSTANT, message);
request.getSession().setAttribute(ATTEMPTS_CONSTANT, --attempts);
request.getSession().setAttribute(GAME_SCORE_CONSTANT, gameScore - wrongWord);
log(GameController.class, "Updated score: " + session.getAttribute(GAME_SCORE_CONSTANT));
if (attempts == 0) {
request.getSession().setAttribute(CREDITS_CONSTANT, --credits);
message = "Sorry, the word was: [ " + session.getAttribute(WORD_TO_GUESS_CONSTANT) + " ]";
request.getSession().setAttribute(MESSAGE_CONSTANT, message);
request.getSession().setAttribute(ATTEMPTS_CONSTANT, startAttempts);
request.getSession().setAttribute(WORD_TO_GUESS_CONSTANT, randomWord.selectRandomWord());
}
if (credits == 0) {
message = "Game over!";
request.getSession().setAttribute(MESSAGE_CONSTANT, message);
request.getSession().setAttribute(GAME_SCORE_CONSTANT, gameScore);
// SAVE SCORE
score.setGameScore(gameScore);
score.setName(name);
score.setSelectedLevelName(lvl);
scoreSavingService.saveScore(score);
log(GameController.class, "Final score: " + session.getAttribute(GAME_SCORE_CONSTANT));
}
} else {
String message = "Correct! Guess another word!";
wordToGuess = randomWord.selectRandomWord();
gameDTO.setWord(wordToGuess);
request.getSession().setAttribute(MESSAGE_CONSTANT, message);
request.getSession().setAttribute(WORD_TO_GUESS_CONSTANT, wordToGuess);
request.getSession().setAttribute(ATTEMPTS_CONSTANT, startAttempts);
request.getSession().setAttribute(GAME_SCORE_CONSTANT, gameScore + finalScorePerWord);
log(GameController.class, "Current score 2: " + session.getAttribute(GAME_SCORE_CONSTANT));
}
request.getSession().setAttribute(GUESSED_WORD_CONSTANT, guess);
request.getSession().setAttribute(RESULT_CONSTANT, result);
log(GameController.class, "Attempts are now: " + session.getAttribute(ATTEMPTS_CONSTANT));
return "redirect:/index";
}
// BUTTONS
#PostMapping(value = "/save")
public String giveUpAndSaveScore(final HttpSession session,
final HttpServletRequest request,
#ModelAttribute("score") Score score) {
score.setGameScore((Integer) session.getAttribute(GAME_SCORE_CONSTANT));
score.setName((String) session.getAttribute(NAME_CONSTANT));
score.setSelectedLevelName((String) session.getAttribute(SELECTED_LEVEL_CONSTANT));
scoreSavingService.saveScore(score);
request.getSession().invalidate();
return "index";
}
#GetMapping(value = "/scores")
public String seeScores(final HttpServletRequest request, Model model) {
List<Score> scoreList = scoreSavingService.getScore(5, 1);
model.addAttribute("score", scoreList);
return "scores";
}
// CLOSE SESSION
#PostMapping(value = "/destroy")
public String restartGame(final HttpServletRequest request) {
log(GameController.class, " Session closing. Removing the data.");
request.getSession().invalidate();
return "redirect:/index";
}
// EXCEPTION HANDLERS
#ExceptionHandler(value = ArrayIndexOutOfBoundsException.class)
public String handleArrayIndexOutOfBoundsException(final Model model) {
String text = "ERROR: Could not check empty <<guess>>.";
model.addAttribute("text", text);
return "ExceptionPage";
}
#ExceptionHandler(value = NullPointerException.class)
public String handleNullPointerException(final Model model) {
String text = "ERROR: Cannot compare words because <<word to guess>> is null";
model.addAttribute("text", text);
return "ExceptionPage";
}
}
Thymeleaf template for index.html
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">
<html lang="en" xmlns:th="www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>5Letters</title>
<link th:href="#{/bootstrap.min.css}" rel="stylesheet" />
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Quicksand&display=swap" rel="stylesheet">
</head>
<body>
<div class="container-sm">
<div class="col-xs-12" align="center">
<!-- HEADER -->
<img src="https://marisabel.nl/wp-content/uploads/2020/11/avatar-e1606738130828-150x150.png"
style="margin-top:2vh;">
<h1 style="margin-top:1vh; color:hotpink;"><b>5Letter Word Game</b></h1>
<h5>AKA: Lingo.</h5>
<hr>
</div>
<form method="get" th:action="#{/scores}">
<input type="submit" value="scores" class="btn btn-primary" />
</form>
<!-- Set Up Game Form -->
<div class="col-xs-12" align="center" th:hidden="${credits} != null">
<form th:action="#{/loadgame}" th:object="${gameDTO}" method="post">
<p>
<select class="form-group" th:field="*{lvlName}" id="dropDownList">
<option th:each="lvl : ${lvlName}" th:text="${lvl.lvlName}" th:value="${lvl.lvlName}">
</option>
</select>
</p>
<p><input type="text" class="form-group mx-sm-3 mb-2" id="name" th:field="*{playerName}"
th:placeholder="name" th:value="anonymous" /></p>
<p class="alert alert-danger" th:if="${#fields.hasErrors('playerName')}" th:errors="*{playerName}">
</p>
<p><input type="submit" value="start" class="btn btn-primary" /></p>
</form>
<p></p>
</div>
<!-- This whole session will load after name and level are chosen. Credits will be set to 3, triggering them to unhide -->
<div class="row">
<div class="col-xs-12 col-md-6" align="center" th:hidden="${credits} == null">
<!-- game information : always show after game setup -->
<h3 th:text="'Hello ' + ${name} + '!'"></h3>
<h3 th:text="'Level: '+ ${levelSelected}"></h3>
<h2 th:text="'Credits : '+ ${credits} + ' | Score: '+ ${gameScore}"></h2>
<h2 th:text="${attempt} + ' / ' + ${attemptStart}"></h2>
</div>
<div class="col-md-6" align="center">
<p>
<!-- Result messages and word after guessing -->
<h4 th:text="${message}"></h4>
<h2 id="result" th:text="${result}" th:hidden="${credits} == 0"></h2>
<!-- GUESS FORM -->
<form th:action="#{/guess}" th:object="${gameDTO}" method="post" th:hidden="${credits} == null">
<input id="guessField" type="text" th:field="*{guess}" placeholder="5letters" />
<p></p>
<p class="alert alert-danger" th:if="${#fields.hasErrors('guess')}" th:errors="*{guess}"></p>
<input type="submit" value="guess" th:disabled="${credits} == 0" class="btn btn-primary" />
</form>
</p>
</div>
</div>
<div class="row" style="margin-top:10vh;">
<div class="row justify-content-center" th:hidden="${credits} == null">
<div class="col col-lg-2 align-items-center">
<!-- Destroy session data and go to index -->
<form method="post" th:action="#{/destroy}">
<input type="submit" value="play again" class="btn btn-danger" />
</form>
<p></p>
</div>
<div class="col-md-auto align-items-center" width="50%">
<!-- Display last typed word -->
<h4 th:text="'Your guess was:'" th:hidden="${attempt} == ${attemptStart}"></h4>
<h2 id="guess" th:text="${guess}" th:hidden="${attempt} == ${attemptStart}"></h2>
<p></p>
</div>
<div class="col col-lg-2 align-items-center">
<!-- Stops the game if you are bored. Usually needed with EASY mode. -->
<form method="post" th:action="#{/save}">
<input type="submit" value="i'm tired" class="btn btn-danger" />
<p></p>
</form>
</div>
</div>
</div>
</body>
</html>
I moved the content I was hiding to its own page. It loads the page, but the content remains hidden. Even after taking a break I am still unable to find what is wrong. Specially when it works 100% without validation.

Cant get view of the form in thymeleaf after put to it list of object

I have a big problem to solve and I don`t see the sollution of this, because IntelliJ not given me any log. Here is the point:
When I try to open the page with form where I put data od employee and address, address form is invisible.
My code:
View:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Dodaj nową firmę</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" th:href="#{/webjars/bootstrap/4.4.1-1/css/bootstrap.min.css}" />
<script th:src="#{/webjars/jquery/3.5.1/jquery.min.js}"></script>
<script th:src="#{/webjars/bootstrap/4.4.1-1/js/bootstrap.min.js}"></script>
</head>
<body>
<div style = "text-align: center;">
<h1>Dodaj nowego pracownika do bazy danych</h1>
</div>
<form class="form-horizontal" th:object="${employee}" th:action="#{/employees}" th:method="post">
<div class="container" style="margin-top:10mm;">
<div class="row">
<div class="col-sm">
<div style = "text-align: center;">
<h5>Dane osobowe</h5>
</div>
<div class="form-group">
<input type="text" class="form-control" th:field="*{name}"/>
<label class="control-label">Imię</label>
<div class="text-danger"><p th:if="${#fields.hasErrors('name')}" th:errors="*{name}"/></div>
</div>
<div class="form-group">
<input type="text" class="form-control" th:field="*{surname}"/>
<label class="control-label">Nazwisko</label>
<div class="text-danger"><p th:if="${#fields.hasErrors('surname')}" th:errors="*{surname}"/></div>
</div>
<div class="form-group">
<input type="text" class="form-control" th:field="*{position}"/>
<label class="control-label">Stanowisko</label>
<div class="text-danger"><p th:if="${#fields.hasErrors('position')}" th:errors="*{position}"/></div>
</div>
<div class="form-group">
<input type="number" class="form-control" th:field="*{age}"/>
<label class="control-label">Wiek</label>
<div class="text-danger"><p th:if="${#fields.hasErrors('age')}" th:errors="*{age}"/></div>
</div>
<div class="form-group">
<input type="text" class="form-control" th:field="*{nationality}"/>
<label class="control-label">Obywatelstwo</label>
<div class="text-danger"><p th:if="${#fields.hasErrors('nationality')}" th:errors="*{nationality}"/></div>
</div>
</div>
<div class="col-sm">
<div th:object="${listAddress}">
<div style = "text-align: center;">
<h5>Dane adresowe</h5>
</div>
<div style = "text-align: center;">
<h6>Adres stały</h6>
</div>
<div th:each="row, stat : ${listAddress.addresses}">
<div class="form-group">
<input type="text" class="form-control" th:field="*{addresses[__${stat.index}__].type}"/>
<label class="control-label">Typ adresu</label>
<!-- <div class="text-danger"><p th:if="${#fields.hasErrors('type')}" th:errors="*{type}"/></div>-->
</div>
<div class="form-group">
<input type="text" class="form-control" th:field="*{addresses[__${stat.index}__].street}"/>
<label class="control-label">Ulica</label>
<!-- <div class="text-danger"><p th:if="${#fields.hasErrors('street')}" th:errors="*{street}"/></div>-->
</div>
<div class="form-group">
<input type="number" class="form-control" th:field="*{addresses[__${stat.index}__].streetNr}"/>
<label class="control-label">Numer domu</label>
<!-- <div class="text-danger"><p th:if="${#fields.hasErrors('streetNr')}" th:errors="*{streetNr}"/></div>-->
</div>
<div class="form-group">
<input type="text" class="form-control" th:field="*{addresses[__${stat.index}__].flatNr}"/>
<label class="control-label">Numer mieszkania</label>
<!-- <div class="text-danger"><p th:if="${#fields.hasErrors('flatNr')}" th:errors="*{flatNr}"/></div>-->
</div>
<div class="form-group">
<input type="text" class="form-control" th:field="*{addresses[__${stat.index}__].postalCode}"/>
<label class="control-label">Kod pocztowy</label>
<!-- <div class="text-danger"><p th:if="${#fields.hasErrors('postalCode')}" th:errors="*{postalCode}"/></div>-->
</div>
<div class="form-group">
<input type="text" class="form-control" th:field="*{addresses[__${stat.index}__].city}"/>
<label class="control-label">Miasto</label>
<!-- <div class="text-danger"><p th:if="${#fields.hasErrors('city')}" th:errors="*{city}"/></div>-->
</div>
<div class="form-group">
<input type="text" class="form-control" th:field="*{addresses[__${stat.index}__].country}"/>
<label class="control-label">Kraj</label>
<!-- <div class="text-danger"><p th:if="${#fields.hasErrors('country')}" th:errors="*{country}"/></div>-->
</div>
</div>
</div>
<div style = "text-align: right;">
<button type="submit" class="btn btn-primary btn-lg active center-block">ZAPISZ</button>
</div>
</div>
</div>
</div>
</form>
</body>
</html>
Controller:
#RequestMapping("/new")
public String addNewEmployee(Model model) {
AddressesList listOfAddress = new AddressesList();
ArrayList<Address> addressesArray = new ArrayList<>();
listOfAddress.setAddresses(addressesArray);
model.addAttribute("employee", new Employee()).addAttribute("listAddress", listOfAddress);
return "new_employee_form";
}
AddressList class
public class AddressesList {
private List<Address> addresses;
public AddressesList() {
}
public AddressesList(List<Address> addresses) {
this.addresses = addresses;
}
public List<Address> getAddresses() {
return addresses;
}
public void setAddresses(List<Address> addresses) {
this.addresses = addresses;
}
}
Address class
public class Address {
public Long idAddress;
public Long idEmployee;
public String type;
public String street;
public String streetNr;
public Integer flatNr;
public String postalCode;
public String city;
public String country;
public Address() {
}
private Address(Long idEmployee, String type, String street, Integer flatNr, String streetNr, String postalCode, String city, String country) {
this.idEmployee = idEmployee;
this.type = type;
this.street = street;
this.streetNr = streetNr;
this.flatNr = flatNr;
this.postalCode = postalCode;
this.city = city;
this.country = country;
}
public static class AddressBuilder{
private Long idAddress;
private Long idEmployee;
private String type;
private String street;
private String streetNumber;
private Integer flatNr;
private String postalCode;
private String city;
private String country;
public AddressBuilder setIdEmployee(Long idEmployee) {
this.idEmployee = idEmployee;
return this;
}
public AddressBuilder setType(String type) {
this.type = type;
return this;
}
public AddressBuilder setStreet(String street) {
this.street = street;
return this;
}
public AddressBuilder setFlatNr(Integer flatNr) {
this.flatNr = flatNr;
return this;
}
public AddressBuilder setStreetNumber(String streetNumber) {
this.streetNumber = streetNumber;
return this;
}
public AddressBuilder setPostalCode(String postalCode) {
this.postalCode = postalCode;
return this;
}
public AddressBuilder setCity(String city) {
this.city = city;
return this;
}
public AddressBuilder setCountry(String country) {
this.country = country;
return this;
}
public Address build(){
return new Address(idEmployee, type, street, flatNr, streetNumber, postalCode, city, country);
}
}
public void setIdAddress(Long idAddress) {
this.idAddress = idAddress;
}
public void setIdEmployee(Long idEmployee) {
this.idEmployee = idEmployee;
}
public void setType(String type) {
this.type = type;
}
public void setStreet(String street) {
this.street = street;
}
public void setFlatNr(Integer flatNr) {
this.flatNr = flatNr;
}
public void setStreetNr(String streetNr) {
this.streetNr = streetNr;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public void setCity(String city) {
this.city = city;
}
public void setCountry(String country) {
this.country = country;
}
public Long getIdAddress() {
return idAddress;
}
public Long getIdEmployee() {
return idEmployee;
}
public String getType() {
return type;
}
public String getStreet() {
return street;
}
public Integer getFlatNr() {
return flatNr;
}
public String getStreetNr() {
return streetNr;
}
public String getPostalCode() {
return postalCode;
}
public String getCity() {
return city;
}
public String getCountry() {
return country;
}
#Override
public String toString() {
return "Address{" +
"idAddress=" + idAddress +
", idEmployee=" + idEmployee +
", type='" + type + '\'' +
", street='" + street + '\'' +
", flattNr=" + flatNr +
", streetNumber='" + streetNr + '\'' +
", postalCode='" + postalCode + '\'' +
", city='" + city + '\'' +
", country='" + country + '\'' +
'}';
}
}
I get the page like this with no errors
with no address form on the right side od page.
Please help to solve this problem.
You are adding an empty list of addresses to your backing object:
ArrayList<Address> addressesArray = new ArrayList<>();
listOfAddress.setAddresses(addressesArray);
If you want the form to show up, you need to add at least one address so it has something to loop over.
ArrayList<Address> addressesArray = new ArrayList<>();
addressesArray.add(new Address());
listOfAddress.setAddresses(addressesArray);
I think I do this wrong.
When I add index to ArrayList form showed up.
#RequestMapping("/new")
public String addNewEmployee(Model model) {
AddressesList listOfAddress = new AddressesList();
ArrayList<Address> addressesArray = new ArrayList<Address>(2);
addressesArray.add(0, new Address());
addressesArray.add(1, new Address());
listOfAddress.setAddresses(addressesArray);
model.addAttribute("employee", new Employee()).addAttribute("listAddress", listOfAddress);
return "new_employee_form";
}
I want to enter a permanent and correspondence address in the form, accept the form (POST) and save it to class objects. How to do it?

Image uploading and displaying from database H2 error spring boot thymleaf

I am trying to build a Book shop website using Springboot,thymleaf,H2 embedded. When I try to upload the picture of new book category it gives me a null pointer error
this is my Category.class
#Entity
#Table(name="category")
public class Category implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
#Column(name="ID")
private Long id;
#Size(min=1, max=90)
#Column(name="CATEGORY_NAME")
private String CategoryName;
#Lob
#Column(name="CATEGORY_PHOTO")
private byte[] CategoryPhoto;
public Category(Long id, #Size(min = 1, max = 90) String categoryName, byte[] categoryPhoto) {
super();
this.id = id;
CategoryName = categoryName;
CategoryPhoto = categoryPhoto;
}
public byte[] getCategoryPhoto() {
return CategoryPhoto;
}
public void setCategoryPhoto(byte[] categoryPhoto) {
CategoryPhoto = categoryPhoto;
}
public Category() {}
#OneToMany(mappedBy = "category", cascade=CascadeType.ALL, orphanRemoval=true)
private Set<Book> Books = new HashSet<>();
public Set<Book> getBooks() {
return Books;
}
CategoryController:
#Controller
#RequestMapping(value="/categories")
public class CategoryController {
private final Logger logger = LoggerFactory.getLogger(BookController.class);
private MessageSource messageSource;
#Autowired
private CategoryService categoryService;
#GetMapping
public String list(Model uiModel) {
logger.info("Listing categories:");
List<Category> categories = categoryService.findALL();
uiModel.addAttribute("categories", categories);
logger.info("No. of categories: " + categories.size());
return "categories";
}
#GetMapping(value = "/{id}")
public String show(#PathVariable Long id, Model model) {
Category category = categoryService.findbyID(id);
if(category.getCategoryPhoto() == null) {
logger.debug("Downloading photo for id: {} with size{}",
category.getId(), category.getCategoryPhoto().length);
}
model.addAttribute("category", category);
return "showCategory";
}
#GetMapping(value = "/new")
public String create(Model uiModel) {
logger.info("creating Category ...");
Category category = new Category();
uiModel.addAttribute("category", category);
return "updateCategory";
}
#PostMapping
public String saveCategory(#Valid Category category, BindingResult bindingResult,
Model uiModel, HttpServletRequest httpServletRequest, RedirectAttributes redirectAttributes,
Locale locale, #RequestParam(value="file", required=false) Part file) {
logger.info("Creating Category....");
if(bindingResult.hasErrors())
{
uiModel.addAttribute("message", new Message("error", messageSource.getMessage("category_save_fail", new Object[] {}, locale)));
uiModel.addAttribute("Category", category);
return "categories/new";
}
uiModel.asMap().clear();
redirectAttributes.addFlashAttribute("message", new Message("success", messageSource.getMessage("Category_save_success", new Object[] {}, locale)));
logger.info("Category ID" + category.getId());
//process upload file
if(file != null) {
logger.info("File name:" + file.getName());
logger.info("File size:" + file.getSize());
logger.info("File content type:" + file.getContentType());
byte[] filecontent = null;
try
{
InputStream inputStream = file.getInputStream();
if(inputStream == null)
logger.info("File InputStream is null");
filecontent = IOUtils.toByteArray(inputStream);
category.setCategoryPhoto(filecontent);
}catch(IOException ex) {
logger.error("Error Saving uploaded file");
}
category.setCategoryPhoto(filecontent);
}
categoryService.save(category);
return "redirect:/categories/" + category.getId();
}
}
updatecategories.html page :: used for creating a new category and updating category with Name and Categoryphoto
<form class="form-horizontal" th:object="${category}" th:action="#{/categories}" method="post" enctype="multipart/form-data">
<input type="hidden" th:field="*{id}"/>
<div class="form-group">
<label class="col-sm-2 control-label">Category Name</label>
<div class="col-sm-10">
<input class="form-control" th:field="*{CategoryName}"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Category Photo</label>
<div class="col-sm-10">
<input name="file" type="file" value="upload" class="form-control" th:field="*{CategoryPhoto}"/>
</div>
</div>
<div class="row">
<button class="btn btn-default">Save</button>
</div>
</form>
show Categories.html page for showing the category name and photo after creating or updating
<form class="form-horizontal" th:object="${category}" th:action="#{/categories}" method="post" enctype="multipart/form-data">
<input type="hidden" th:field="*{id}"/>
<div class="form-group">
<label class="col-sm-2 control-label">Category Name</label>
<div class="col-sm-10">
<input class="form-control" th:field="*{CategoryName}"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Category Photo</label>
<div class="col-sm-10">
<input name="file" type="file" value="upload" class="form-control" th:field="*{CategoryPhoto}"/>
</div>
</div>
<div class="row">
<button class="btn btn-default">Save</button>
</div>
</form>
here is a image when I create a new category
error Image:
sorry for Long Question description but I want to clarify the details. Help would be appreciated.
I got the mistake I am using MessageSource without autowiring it Done that. And Adding Messages to my properties file.

Spring #ModelAttributes auto binding

Hi i am tring to use #ModelAttributes for auto binding from view to controller.
this jsp page should send all elements which is Personal Schedule VO.
<form name="insertFrm" action="myScheduleInsert" method="POST">
<ul>
<input type="hidden" class="form-control" name="perschd_num" >
<li>
<label class='control-label'>title</label>
<input type="text" class="form-control" name="perschd_title" >
</li>
<li>
<input type="hidden" class="form-control" name="perschd_writer" >
<li>
<label class='control-label'>start date</label>
<input type="date" id="fullYear" class="form-control" name="perschd_start_date" value="">
</li>
<li>
<label class='control-label'>end date</label>
<input type="date" class="form-control" name="perschd_end_date" >
</li>
<li>
<label class='control-label'>content</label>
<input type="text" class="form-control" name="perschd_cont" >
</li>
</ul>
</div>
<!-- button-->
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-primary">
</form>
and this is my controller for insert feature by using #ModelAttributes PerschdVO perschd and when i try print all out, all is null.
//insertSchedule
#RequestMapping("/myScheduleInsert")
public String myScheduleInsert(#ModelAttribute PerschdVO perschdVO ){
String view="redirect:/professor/mypage/mySchedule";
*System.out.println(perschdVO);*
try {
proService.insertPerschd(perschdVO);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return view;
}
and this is PerschdVO
public class PerschdVO {
private int perschd_num;
private String perschd_title;
private String perschd_cont;
private Date perschd_date;
private String perschd_start_date;
private String perschd_end_date;
private String perschd_writer; //id
public String getPerschd_writer() {
return perschd_writer;
}
public void setPerschd_writer(String perschd_writer) {
this.perschd_writer = perschd_writer;
}
public int getPerschd_num() {
return perschd_num;
}
public void setPerschd_num(int perschd_num) {
this.perschd_num = perschd_num;
}
public String getPerschd_title() {
return perschd_title;
}
public void setPerschd_title(String perschd_title) {
this.perschd_title = perschd_title;
}
public String getPerschd_cont() {
return perschd_cont;
}
public void setPerschd_cont(String perschd_cont) {
this.perschd_cont = perschd_cont;
}
public Date getPerschd_date() {
return perschd_date;
}
public void setPerschd_date(Date perschd_date) {
this.perschd_date = perschd_date;
}
public String getPerschd_start_date() {
return perschd_start_date;
}
public void setPerschd_start_date(String perschd_start_date) {
this.perschd_start_date = perschd_start_date;
}
public String getPerschd_end_date() {
return perschd_end_date;
}
public void setPerschd_end_date(String perschd_end_date) {
this.perschd_end_date = perschd_end_date;
}
why this elements from jsp does not match with this? Eventhough i matched all name in jsp file to PerschdVO's get() names.
and if i fix like this
public String myScheduleInsert(
Principal who,
#RequestParam("perschd_start_date")String perschd_start_date,
#RequestParam("perschd_end_date")String perschd_end_date,
#RequestParam("perschd_title")String perschd_title,
#RequestParam("perschd_cont")String perschd_cont
){
PerschdVO perschdVO = new PerschdVO();
...}
than the data from jsp could be sent to #Controller, but still can't get informations about using #ModelAttributes. cos if i use that always 400 bad request happened.

spring-security:HTTP Status 405 - Request method 'POST' not supported

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

Resources