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

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;
}

Related

Error resolving template [create], template might not exist or might not be accessible by any of the configured Template Resolvers

I can't figure out why I keep getting this status = 500 template error.
''There was an unexpected error (type=Internal Server Error, status=500).
Error resolving template [create], template might not exist or might not be accessible by any of the configured Template Resolvers
org.thymeleaf.exceptions.TemplateInputException: Error resolving template [create], template might not exist or might not be accessible by any of the configured Template Resolvers''
I tried looking up resources and I coundn't resolve it.
This is what IntelliJ is saying:
This is my create.html template:
<html lang="en" xmlns:th="https://www.thymeleaf.org/">
<head th:replace="fragments :: head"></head>
<head>
<link th:href="#{/css/meetups.css}" rel="stylesheet" />
</head>
<body class="create-meetup-body">
<header th:replace="fragments :: header"></header>
<div class="navbar">
<div class="container">
<nav>
<ul class="meetup-nav">
<li>All Meetups
Create a Meetup
Delete a Meetup</li>
</ul>
</nav>
</div>
</div>
<section class="create-meetup-section">
<form method="post">
<div class="form-group">
<div class="form-wrapper">
<label class="form-name">Meetup Name:
<input th:field="${meetup.meetupName}" class="form-control">
</label>
<p class="error" th:errors="${meetup.meetupName}"></p>
<label class="form-email">Contact Email:
<input th:field="${meetup.meetupContactEmail}" class="form-control">
</label>
<p class="error" th:errors="${meetup.meetupContactEmail}"></p>
<!--label class="form-date">Date:
<input type="date" class="form-control">
</label-->
<label class="form-date">Date (mm/dd/yyy):
<input th:field="${meetup.meetupDate}" class="form-control">
</label>
<p class="error" th:errors="${meetup.meetupDate}"></p>
<label class="form-description">Description:
<textarea th:field="${meetup.meetupDescription}" class="form-control"></textarea>
</label>
<p class="error" th:errors="${meetup.meetupDescription}"></p>
<label class="form-category" th:for="category">Category:</label>
<select id="meetupCategory" name="meetupCategory">
<option value="Nature Walk">Nature Walk</option>
<option value="Cycling">Cycling</option>
<option value="Family Activity">Family Activity</option>
<option value="Athletic">Athletic</option>
</select>
<label class="form-trail" th:for="trail">Trail:</label>
<select name="trailId">
<option th:each="trail : ${trails}"
th:text="${trail.name}"
th:value="${trail.id}"></option>
</select>
</div>
</div>
<input type="submit" value="Create Meetup">
</div>
</form>
</section>
</body>
</html>
I believe create.html it's in the correct directory:
This is my controller class:
#RequestMapping("meetups")
public class MeetupController {
#Autowired
private MeetupRepository meetupRepository;
#Autowired
private TrailRepository trailRepository;
#Autowired
private AuthenticationController authenticationController;
#GetMapping
public String displayMeetups(Model model, HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session != null) {
User theUser = authenticationController.getUserFromSession(session);
model.addAttribute("theUser", theUser);
}
model.addAttribute("title", "Trail Meetups");
model.addAttribute("meetups", meetupRepository.findAll());
model.addAttribute("trails", trailRepository.findAll());
return "meetups/index";
}
#GetMapping("create")
public String displayCreateMeetupsForm(Model model) {
model.addAttribute("title", "Create A New Meetup");
model.addAttribute("trails", trailRepository.findAll());
model.addAttribute(new Meetup());
return "meetups/create";
}
#PostMapping("create")
public String processCreateMeetupsForm(#ModelAttribute #Valid Meetup newMeetup,
Errors errors, Model model, #RequestParam int trailId) {
if (errors.hasErrors()) {
model.addAttribute("title", "Create A New Meetup");
return "create";
}
Optional<Trail> trailObjs = trailRepository.findById(trailId);
if (trailObjs.isPresent()) {
Trail trail = trailObjs.get();
model.addAttribute("trail", trail);
model.addAttribute("trailId", trailId);
newMeetup.setTrail(trail);
meetupRepository.save(newMeetup);
model.addAttribute("meetups", meetupRepository.findAll());
return "meetups/index";
} else {
return "redirect:";
}
}
#GetMapping("delete")
public String displayDeleteMeetupsForm(Model model, HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session != null) {
User theUser = authenticationController.getUserFromSession(session);
model.addAttribute("theUser", theUser);
}
model.addAttribute("title", "Delete A Meetup");
model.addAttribute("meetups", meetupRepository.findAll());
return "meetups/delete";
}
#PostMapping("delete")
public String processDeleteMeetupsForm(#RequestParam(required = false) int[] meetupIds, Model model, HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session != null) {
User theUser = authenticationController.getUserFromSession(session);
model.addAttribute("theUser", theUser);
}
if (meetupIds != null) {
for (int id : meetupIds) {
meetupRepository.deleteById(id);
}
}
return "redirect:";
}
#GetMapping("details")
public String displayMeetupDetails(#RequestParam Integer meetupId, Model model, HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session != null) {
User theUser = authenticationController.getUserFromSession(session);
model.addAttribute("theUser", theUser);
}
Optional<Meetup> result = meetupRepository.findById(meetupId);
if (result.isEmpty()) {
model.addAttribute("title", "Invalid: A meetup with ID " + meetupId + "does not seem to exist.");
} else {
Meetup meetup = result.get();
model.addAttribute("title", meetup.getMeetupName() + " Details");
model.addAttribute("meetups", meetup);
model.addAttribute("trails", trailRepository.findAll());
}
return "meetups/details";
}

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

Login Logout Session in spring mvc

I am trying to implement Login Logout functionality for my project website. I'm making SPA. what is the best way to make login/logout global i.e. if I click on any other link like contact us or about us after logging in logout remains till clicked? Where I'm going wrong How to correct it?
What logic shall I apply so that logout remains till the end?
I have used javascript to change login button to logout
What I want to know is how do I get a login/logout button to display across the entire portal and our unauthenticated site based on if the user is logged in or out? Is it possible for me to execute my code on the header somehow? Or do you have any other suggestions? Currently when I click on signin button then value of temp is passed true and logout button is displayed but now when I click on any other page like about us value of temp hasn't been passed true ..so how to do this across complete portal?
UserController.java
#RequestMapping("/login")
public ModelAndView loginHere() {
log.debug("Starting of the method loginHere");
System.out.println("loginHere");
ModelAndView mv = new ModelAndView("/home");
mv.addObject("user", user);
mv.addObject("isUserClickedLoginHere", "true");
mv.addObject("message", "Welcome to login page");
log.debug("Ending of the method loginHere");
System.out.println("Ending login here");
return mv;
}
#RequestMapping(value = "/validate", method = RequestMethod.GET)
public ModelAndView validate(#RequestParam(value = "username") String userID,
#RequestParam(value = "password") String password) {
log.debug("Starting of the method validate");
System.out.println("validate");
ModelAndView mv = new ModelAndView("/home");
user = userDAO.validate(userID, password);
// if the record exist with this userID and password it will return user
// details else will return null
if (user != null) {
log.debug("Valid Credentials");
session = req.getSession();
/* session.setMaxInactiveInterval(1*10);
*/
session.setAttribute("loggedInUser", user.getName());
session.setAttribute("loggedInUserID", user.getUsername());
session.setAttribute("user", user);
mv.addObject("homePagee", "true");
mv.addObject("temp", "true");
if (user.getRole().equals("ROLE_ADMIN")) {
log.debug("Logged in as Admin");
mv.addObject("isAdmin", "true");
/*
* session.setAttribute("supplier", supplier);
* session.setAttribute("supplierList", supplierDAO.list());
*
* session.setAttribute("category", category);
* session.setAttribute("categoryList", categoryDAO.list());
*/
} else {
log.debug("Logged in as User");
mv.addObject("isAdmin", "false");
// myCart = cartDAO.list(userID);
/*
* mv.addObject("myCart", myCart); // Fetch the myCart list
* based on user ID List<MyCart> cartList =
* cartDAO.list(userID); mv.addObject("cartList", cartList);
* mv.addObject("cartSize", cartList.size());
*/
}
} else {
log.debug("Invalid Credentials");
mv.addObject("invalidCredentials", "true");
mv.addObject("errorMessage", "Invalid Credentials");
}
log.debug("Ending of the method validate");
return mv;
}
#RequestMapping("/logout")
public ModelAndView logout(HttpServletRequest request, HttpServletResponse response) {
log.debug("Starting of the method logout");
System.out.println("Starting of the method logout");
ModelAndView mv = new ModelAndView("/home");
session.invalidate();
session = request.getSession(true);
mv.addObject("homePagee", "true");
mv.addObject("temp1", "true");
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
new SecurityContextLogoutHandler().logout(request, response, auth);
}
System.out.println("Ending of the method logout");
log.debug("Ending of the method logout");
return mv;
// return "redirect:/login?logout";
}
Logout.JSP
<c:if test="${temp}">
<script type="text/javascript">
/* var loginbtn = document.getElementById("login-btn");
var signupbtn = document.getElementById("signup-btn");
var myaccountbtn = document.getElementById("logout-btn");
signupbtn.innerHTML = "";
loginbtn.innerHTML = "";
myaccountbtn.style.display = "block";
*/
/* loginbtn.href = "logout";
*/
</script>
</c:if>
<c:if test="${temp1}">
<script>
var loginbtn = document.getElementById("login-btn")
var signupbtn = document.getElementById("signup-btn")
var myaccountbtn = document.getElementById("logout-btn");
loginbtn.innerhtml = "Login";
signupbtn.innerHTML = "Signup";
loginbtn.href = "login";
myaccountbtn.style.display = "none";
</script>
</c:if>
Login.jsp
<div class="container">
<div class="card card-container">
<!-- <img class="profile-img-card" src="//lh3.googleusercontent.com/-6V8xOA6M7BA/AAAAAAAAAAI/AAAAAAAAAAA/rzlHcD0KYwo/photo.jpg?sz=120" alt="" /> -->
<img id="profile-img" class="profile-img-card"
src="//ssl.gstatic.com/accounts/ui/avatar_2x.png" />
<p id="profile-name" class="profile-name-card"></p>
<form class="form-signin" action="validate">
<span id="reauth-email" class="reauth-email"></span> <input
type="username" name="username" id="inputEmail"
class="form-control" placeholder="Username" required autofocus>
<input type="password" name="password" id="inputPassword"
class="form-control" placeholder="Password" required> <input
type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
<div id="remember" class="checkbox">
<label> <input type="checkbox" value="remember-me">
Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block btn-signin"
type="submit">Sign in</button>
</form>
<!-- /form -->
Forgot the password?
</div>
<!-- /card-container -->
</div>
<!-- /container -->
</div>
Header.jsp
<li class="upper-links"><a class="links" id="signup-btn"
href="register">Signup</a></li>
<li class="upper-links"><a class="links" id="login-btn"
href="login">Login</a></li>
<li class="upper-links dropdown"><a
class="dropdown-toggle links" data-toggle="dropdown" role="button"
aria-haspopup="true" aria-expanded="false" id="logout-btn"
href="loginHere" style="display: none;">My Account<span class="caret"></span></a>
<ul class="dropdown-menu" style="width: 40%;">
<li>Account</li>
<li>Orders</li>
<li>Wishlist</li>
<li role="separator" class="divider"></li>
<li>Logout</li>
</ul></li>
You can user Http Session for track user and handle user login/ logout to your project, Base on session you can implement other business logic to your project.
Simple Login/ Logout In controller :
#PostMapping("/dologin")
public String userLogin(HttpSession session, #ModelAttribute("user") User
user, Model model) {
if (user.getEmail().equals("imranmadbar#gmail.com") &&
user.getPassword().equals("12345")) {
user.setFname("MD IMRAN");
user.setMname("HOSSAIN");
user.setLname("BABU");
user.setAge(28);
session.setAttribute("user", user);
} else {
model.addAttribute("message", "Login failed. Try again.");
return "login";
}
return "redirect:/user/info";
}
#GetMapping("/logout")
public String logout(HttpSession session ) {
session.invalidate();
return "redirect:/login";
}
#GetMapping("/info")
public String userInfo(HttpSession session) {
return "user";
}
After Login user and set user data on session scope you can access those data from any in the project.
Access data from user.jsp File:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page isELIgnored = "false" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>BORAJI.COM</title>
</head>
<body>
<h4>User name: ${user.fname} ${user.mname} ${user.mname}</h4>
<h4>User Age: ${user.age}</h4>
<h4>User Email: ${user.email}</h4>
Log out<br>
</body>
</html>
In my project i track user using spring interceptor.
You can check out my project use this link
https://github.com/imrangthub/LoginRegUsingSession/tree/master/LoginRegUsingSession

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

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

Form Sumbit action resulting into get request

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;
}
}

Resources