Form Sumbit action resulting into get request - spring

I have simple form where on click of accpet button which of type resulting into GET requet rather than POST request. This is causing display of page twice and weired thing is form does generates POST request when you click on accept button again. This is mostly happening on IE8 and Chrome.
Current configuration :
<%#taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%#taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="c" uri="http://java.sun.com/jstl/core_rt"%>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<title><spring:theme code="company"/><spring:theme code="title.companySetup.terms&conditions"></spring:theme></title>
<%-- <title><spring:message code="userRegistration.addNewEmployer.title"></spring:message></title> --%>
<!-- CONTENT START -->
<div class="canvasWrapper">
<div class="canvas" role="main">
<div class="contentWrapper clearfix">
<c:choose>
<c:when test="${whitelabellingfolder == 'ABC'}">
<h1>Welcome to </h1>
</c:when>
<c:when test="${whitelabellingfolder == 'PQR'}">
<h1 style="color:#6a2c91">Welcome to <i style="color:#6a2c91">BOND</i></h1>
</c:when>
<c:when test="${whitelabellingfolder == 'XYZ'}">
<h1>Welcome to </h1>
</c:when>
<c:when test="${whitelabellingfolder == 'LMN'}">
<h1>Welcome to </h1>
</c:when>
<c:when test="${whitelabellingfolder == 'QWE'}">
<h1>Welcome to </h1>
</c:when>
<c:when test="${whitelabellingfolder == 'POI'}">
<h1>Welcome to </h1>
</c:when>
<c:otherwise>
<h1>Welcome to Nothing</h1>
</c:otherwise>
</c:choose>
<h2>Terms and Conditions</h2>
<spring:message code="${whitelabellingfolder}.termsAndContion.body"></spring:message>
<form:form method="Post" commandName="userForm" >
<form:errors path="*" cssClass="formError" element="div" />
<div class="ruler"></div>
<div class="navHolder clearfix">
<!-- <script type="text/javascript">
document.write('<div class="floatLeft"><input type="button" class="btnBlue" value="Print this page" onClick="window.print()"></div>');
</script> -->
<div class="floatRight"><input class="btnBlue" name="accpet" type="submit" value="Accept" /></div>
<div class="floatRight"><input class="btnBlue" name="decline" type="submit" value="Decline" /></div>
</div>
</form:form>
</div>
</div>
</div>
<!-- CONTENT END -->
<!-- FOOTER START -->
<div class="footerWrapper2">
<div class="footerCanvasWrapper">
<div class="footerCanvas">
</div>
<div class="footerLinks">
</div>
</div>
</div>
<!-- FOOTER END -->
Controller----
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.theme.SessionThemeResolver;
import org.springframework.web.util.WebUtils;
#Controller
#RequestMapping("/TNC.html")
public class TNCControllerAnn {
private String className = "TNCControllerAnn";
#Autowired
private AppService appService;
#RequestMapping(method = RequestMethod.GET)
public String formbacking(#RequestHeader(value="Accept") String accept,
#RequestHeader(value="Accept-Language") String acceptLanguage,
#RequestHeader(value="User-Agent", defaultValue="foo") String userAgent,HttpServletRequest request,
HttpServletResponse response) {
CMULogger.enter(className, "formBackingObject >> In the get method");
String employerID = request.getHeader(UIConstant.EMP_ID);
CMULogger.debug(className, " ** employerID: " + employerID);
request.getSession().setAttribute(UIConstant.SELECTED_MODULE, "tnc");
String requestURL = request.getRequestURL().toString();
if (!requestURL.endsWith("/")) {
requestURL = requestURL.concat("/");
}
request.getSession().setAttribute(GlobalConstants.REQUEST_URL, requestURL);
CMULogger.debug(className, " ** Request_URL: " + request.getSession().getAttribute(GlobalConstants.REQUEST_URL));
ServiceContext serviceContext = new ServiceContext();
UserContext userContext = new UserContext(employerID, "", "", "", "", "", "", "", "");
serviceContext.setUserContext(userContext);
RegistrationSetupAppResponse appResponse = null;
try {
appResponse = registrationAppService.getThemeChange(serviceContext);
} catch (ApplicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
AdviserDTO adviserDTO = appResponse.getAdviserDTO();
String companyAgencyCode = adviserDTO.getCoLegalAgencyCode();
Boolean isBranded = adviserDTO.isBrandedAccessRequired();
String requestURI = "/";
if (!isBranded) {
companyAgencyCode = "sam";
} else {
requestURI = "/" + adviserDTO.getBrandingURL() + "/";
}
request.getSession().setAttribute(GlobalConstants.REQUEST_URI, requestURI);
request.getSession().setAttribute("whitelabellingfolder", companyAgencyCode);
WebUtils.setSessionAttribute(request, SessionThemeResolver.THEME_SESSION_ATTRIBUTE_NAME, companyAgencyCode);
CMULogger.exit(className, "formBackingObject");
return "termsnCondition";
}
#RequestMapping(method = RequestMethod.POST)
public String onSumbit(HttpServletRequest request, HttpServletResponse response){
CMULogger.enter(className, "onSubmit >> In the post method");
String redirectTo = GlobalConstants.REDIRECT;
if (request.getParameter("accpet") != null) {
String cnUserID = request.getHeader(UIConstant.CNUSER_ID);
String email = request.getHeader(UIConstant.EMAIL);
if ((email == null) || (cnUserID == null)) {
String message = "Mandatory Field email or cnUserID is missing";
CMULogger.error(className, "Exception in creating context", message);
// throw new ApplicationException(message);
}
ServiceContext conext = new ServiceContext();
UpdateTNCDTO updateTNCDTO = new UpdateTNCDTO();
UpdateTNCRequest updateTNCRequest = new UpdateTNCRequest();
updateTNCDTO.setCnUserID(cnUserID);
updateTNCDTO.setEmail(email);
updateTNCRequest.setUpdateTNCDTO(updateTNCDTO);
try {
CMULogger.error(className, "Error******Error**** Before updating DB");
registrationAppService.updateTNC(conext, updateTNCRequest);
CMULogger.error(className, "Error******Error**** AFter updating DB");
} catch (ApplicationException ae) {
CMULogger.error(className, "Error******Error**** Ocuured during updating DB");
/*errors.reject("", ae.getMessage());
try {
return showForm(request, errors, this.getFormView());
} catch (Exception e) {
CMULogger.error(className, e.getMessage());
}*/
}
CMULogger.debug(className, "******" + PropertyReader.getEnvBasedProperty(GlobalConstants.TNC_ACCEPTED_URL));
String requestURI = (String) request.getSession().getAttribute(GlobalConstants.REQUEST_URI);
redirectTo =
PropertyReader.getEnvBasedProperty(GlobalConstants.TNC_ACCEPTED_URL)
+ ((requestURI.equals("/")) ? "" : requestURI.substring(0, (requestURI.length() - 1)));
} else if (request.getParameter("decline") != null) {
CMULogger.debug(className, "User declined T&C");
StringBuilder strbuilder = new StringBuilder();
strbuilder.append(redirectTo);
strbuilder.append(PropertyReader.getEnvBasedProperty(GlobalConstants.LOGOFF_URL));
String requestURI = (String) request.getSession().getAttribute(GlobalConstants.REQUEST_URI);
strbuilder.append("?advisor=" + ((requestURI.equals("/")) ? "" : requestURI.substring(1, (requestURI.length() - 1))));
redirectTo = strbuilder.toString();
}
CMULogger.debug(className, "User is redirected to following url:" + redirectTo);
CMULogger.exit(className, "onSubmit");
//return "redirect:" + redirectTo;`enter code here`
return redirectTo;
}
public AppService getAppService() {
return appService;
}
public void setAppService(
AppService appService) {
this.appService = appService;
}
}

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.

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

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

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

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

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

How to Integrate phonegap(client) with servlet(server)

using ajax how I integrate phonegap with servlet,if it is possible means what I have mentioned in URL
already I try this but server error is occured
Thanks very much for your reply,i find solution here I post my code it may useful for others
Servlet(server side):
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Connection con = null;
ResultSet resultSet = null;
String uname = request.getParameter("uname");
String pwd = request.getParameter("pwd");
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://localhost/ROSE";
final String USER = "root";
final String PASS = "root";
con = DriverManager.getConnection(url,USER,PASS);
String query = null;
query = "SELECT uname,pwd from roobi";
PreparedStatement statement = con.prepareStatement(query);
resultSet = statement.executeQuery();
String db_uname="";
String db_pwd="";
while (resultSet.next()) {
db_uname = resultSet.getString("uname")
db_pwd = resultSet.getString("pwd");
if( (uname.equals(db_uname)) && (pwd.equals(db_pwd))){
out.write("SUCCESS");
} }
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
} } }
Phonegap(client side)
<script type="text/javascript" charset="utf-8" src="cordova-2.5.0.js"></script>
<script>
function verifyLogin(){
var uname=document.getElementById("txt_username").value;
var pwd=document.getElementById("txt_pwd").value;
$.support.cors = true;
$.ajax({
type : 'POST',
url : 'http://10.0.2.2:8080/sam/Jdbc', // Servlet URL
data:{
uname:uname,
pwd:pwd,
},
success : function(data) {
if("SUCCESS"==data){
alert("Login Success!!");
} else {
alert("Invalid Login!!");
}
},
error: function (xhr, ajaxOptions, thrownError)
{
alert("errorstatus: " + xhr.status + " ajaxoptions: " + ajaxOptions + " throwError: " + thrownError);
}
});
}
</script>
</head>
<body>
<div data-role="page" id="page1">
<div data-role="content" id="input_login">
<ul data-role="listview" data-divider-theme="b" data-inset="true">
<li data-role="list-divider" role="heading">User Name</li>
<li data-role="list-divider" >
<input type="text" id="txt_username"/></li>
<li data-role="list-divider" role="heading">
Password
</li>
<li data-role="list-divider" >
<input type="password" id="txt_pwd"/>
</li>
<li data-role="list-divider" >
<input type="button" id="btn_login" value="Login" onclick="verifyLogin()"/>
</li>
</ul>
</div>
</div>
</body>

Resources