spring-boot simple login failed - spring

I'm a beginner in spring-Boot and i try to do a simple login using a thymeleaf form, it take the input name and password and compare it with the name and the paswword of a the user stored in database where its id is 1.
my controller is this:
#RequestMapping(value="/access", method=RequestMethod.POST)
public String access(#ModelAttribute("user") User user, ModelMap model)
{
Long id=(long) 1;
User u= userServiceImp.finduserById(id);
if(user.getName().equals(u.getName()) && user.getPassword().equals(u.getPassword()))
{
model.put("username", user.getName());
return "index";
}
else
{
model.put("message", "wrong username or password");
return "login";
}
}
and my html form is this:
<form th:action="#{/access}" th:object="${user}" method="POST">
<input type="text" th:field="*{name}" placeholder="Username" required="required" ></input>
<input type="password" th:field="*{password}" placeholder="Password" required="required" ></input>
<button type="submit" class="btn btn-primary btn-block btn-large">Let me in.</button>
<h1>${message}</h1>
</form>
but i alwayes get this error page
what could the problem be
the controller couldn't reconize the object th:object="${user}"
so i change this methode from this:
RequestMapping(value="/login", method = RequestMethod.GET)
public String showLoginPage(ModelMap model){
return "login";
}
to this:
RequestMapping(value="/login", method = RequestMethod.GET)
public String showLoginPage(ModelMap model){
User user = new User();
model.addAttribute("user", user);
return "login";}
now everything went right

Can you try this:
return "redirect:index";
or
return "redirect:/index";

Related

Spring MVC: Required String parameter 'code is not present

I'm getting the following error:
Required String parameter 'code' is not present.
I want to retrieve the person's code when I enter the email and password data, i.e. I have the following query:
SELECT code FROM authentication WHERE email=? AND password=?
Controller:
#RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView customerLogin(#RequestParam("code") String code,#RequestParam("email") String email, #RequestParam("password") String password) {
ModelAndView mv = new ModelAndView();
Customer customer = new Customer();
customer.setCode(code);
customer.setEmail(email);
customer.setPassword(password);
String name = customerDao.loginCustomer(customer);
String cf=customer.getCode();
if (name != null) {
mv.setViewName("redirect:/update/" +cf);
} else {
mv.addObject("msg", "Invalid user id or password.");
mv.setViewName("login");
}
return mv;
}
Dao:
#Override
public String loginCustomer(Customer customer) {
String sql = "SELECT code FROM authentication WHERE email=? AND password=?";
List<String> customers = jdbcTemplate.queryForList(sql, new Object[] {customer.getCode(), customer.getEmail(), customer.getPassword() },String.class);
if (customers.isEmpty()) {
return null;
} else {
return customers.get(0);
}
}
login.jsp
<%# page isELIgnored="false"%>
<html>
<head>
<title></title>
</head>
<body>
<form action="login" method="post">
<pre>
Email: <input type="text" name="email" />
Password: <input type="password" name="password" />
<input type="submit" value="Login" />
</pre>
</form>
${msg}
</body>
</html>
The reason is obvious: you do not pass code parameter into your controller method:
#RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView customerLogin(#RequestParam("code") String code,
#RequestParam("email") String email, #RequestParam("password") String password) {
}
In order to solve this issue, you have two ways:
a. make code not required, thus we need to add required=false in controller method:
#RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView customerLogin(#RequestParam(value = "code", required=false) String code,
#RequestParam("email") String email, #RequestParam("password") String password) {
}
b. add code field in your html form:
<%# page isELIgnored="false"%>
<form action="login" method="post">
<pre>
Code: <input type="text" name="code" />
Email: <input type="text" name="email" />
Password: <input type="password" name="password" />
<input type="submit" value="Login" />
</pre>
</form>
${msg}
That exception happening at controller level. You are not passing the code Param in the URL.

How to get the value of the input username with thymeleaf?

How can I get the value of the input username in a login form?
My login form is:
<form th:action="#{/login}" method="post">
<div class="form-group">
<input type="text" name="username" id="username"
class="form-control" th:placeholder="Email" autofocus required/>
</div>
<div class="form-group">
<input type="password" name="password" id="password"
class="form-control" th:placeholder="Password" required/>
</div>
<input type="submit" class="btn btn-lg btn-primary btn-block"
th:value="Login"/>
</form>
And my controller is :
#Controller
public class LoginController {
#GetMapping("/login")
public String login(#RequestParam(value = "error", required = false) String error, Model model,
Principal principal) {
if (principal != null) {
return "redirect:/ccursos";
}
if (error != null) {
model.addAttribute("msg",
"Error al iniciar sesión: Nombre de usuario o contraseña incorrecta, por favor vuelva
a intentarlo!");
}
return "login";
}
#GetMapping("/logout")
public String logoutPage (HttpServletRequest request, HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null){
new SecurityContextLogoutHandler().logout(request, response, auth);
}
return "redirect:/login";
}
}
I was trying to use the #RequestParam to get the value of the variable, but it says the varibale Email doesn't exist. I'm knew to this so any help would be appreciated.
Here is what I'm trying to to:
#GetMapping("/login")
public String login(#RequestParam(value = "error", required = false) String error,#RequestParam("Email") String email,
Model model, Principal principal) {
if (principal != null) {
return "redirect:/ppeliculas";
}
if (error != null) {
model.addAttribute("msg",
"Error al iniciar sesión: Nombre de usuario o contraseña incorrecta, por favor vuelva
a intentarlo!");
}
return "login";
}
You are trying to send form by POST method but your controller is defined only for #GetMapping. Change or add #PostMapping, then add #RequestBody Model model (if class Model describe your form) and all should works.
If you are starting with programing read something about HTTP: https://www.w3schools.com/tags/ref_httpmethods.asp and in this case about #RequestBody: https://www.baeldung.com/spring-request-response-body

form:errors are not displaying errors on JSP in Spring

I can not get the validation error messages to be showed in JSP page. The validation is working but messages are not getting displayed at all.
SystemValidator class :
#Override
public void validate(Object target, Errors errors) {
SystemUser systemUser = (SystemUser) target;
SystemUser user = systemUserRepository.findByUsername(systemUser.getUsername());
if (user != null && !(user.getId() == systemUser.getId()) || superUserName.equalsIgnoreCase(systemUser.getUsername())) {
errors.rejectValue("username", "Duplicate Username");
}
}
the view :
<form:form method="post" modelAttribute="user" action="addUser">
<div class="form-group">
<label for="username" class="col-form-label">User Name</label>
<form:input type="text" required="required" class="form-control" id="username" path="username"/>
<form:errors path = "username" cssClass = "error" />
</div>
<form:input type="hidden" id="id" name="id" path="id"/>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form:form>
the controller class :
#RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String saveUser(Model model, #Validated #ModelAttribute("user") SystemUser user, BindingResult result) {
logger.info("User save/update request received [{}]", user.toString());
if (result.hasErrors()) {
loadData(model);
model.addAttribute("user", user);
return "users";
}
systemUserService.saveSystemUser(user);
loadData(model);
return "users";
}
private void loadData(Model model) {
model.addAttribute("users", systemUserService.getAllUsers());
model.addAttribute("user", new SystemUser());
}
Use #Valid instead of #Validated like below.
#RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String saveUser(#Valid #ModelAttribute("user") SystemUser user, BindingResult result,Model model)
Don't do model.addAttribute("user", new SystemUser()); when validation error occurs.
Change to this:
if (result.hasErrors()) {
loadData(model, user);
return "users";
}
And:
private void loadData(Model model, User user) {
model.addAttribute("users", systemUserService.getAllUsers());
model.addAttribute("user", user);
}

Can't get selected option in controller

I have a form to list up buckets in select options, it uploads file to bucket after select bucket and file, but I can't get selected bucket in my controller, The folder alwsy return empty string, though mutipartFile is no problem, I really want to know why!
I googled for all this week but no result what I need!
I am very new in thymeleaf even in spring framework:(
Pls help me to solve this simple problem to you:)
part of html file as below:
<form role="form" enctype="multipart/form-data" action="#" th:object="${folder}" th:action="#{'/drill/skin/upload'}" method="POST">
<div class="form-group">
<label class="form-control-static">Select Bucket</label>
<select class="form-control" th:field="${folder}">
<option th:each="bucket : ${buckets}" th:value="${bucket.name}" th:text="${bucket.name}">bucket</option>
</select>
</div>
<label class="form-control-static" for="inputSuccess">Select Upload File</label>
<div class="form-group">
<input type="file" class="form-control" name="uploadFile"/>
</div>
<div class="form-group">
<button class="btn btn-primary center-block" type="submit">Upload</button>
</div>
</form>
controller as below:
#RequestMapping(value="/", method=RequestMethod.GET)
public String provideUploadInfo(Model model) {
List<Bucket> buckets = s3Service.listBuckets();
model.addAttribute("buckets", buckets);
model.addAttribute("folder", "com.smartstudy");
return "index";
}
#RequestMapping(value="/upload", method=RequestMethod.POST)
public String handleFileUpload(
#ModelAttribute("folder") String folder,
#RequestParam("uploadFile") MultipartFile uploadFile, Model model) {
log.info("Bucket: " + folder + ", uploadFile: " + uploadFile.getOriginalFilename());
if (!uploadFile.isEmpty() && !folder.isEmpty()) {
return s3Service.upload(uploadFile, folder);
}
return "index";
}
There are couple of issues in your code.
Ideally, the whole form should be encapsulated in one form-backing object. In your case, create a Java object that wraps the folder and the file together.
class BucketFileForm{
private MultipartFile uploadFile;
private String folder;
public String getFolder() {
return folder;
}
public void setFolder(String folder) {
this.folder = folder;
}
public MultipartFile getUploadFile() {
return uploadFile;
}
public void setUploadFile(MultipartFile uploadFile) {
this.uploadFile = uploadFile;
}
}
Make this object available in the model so that you can access it in the view
#RequestMapping(value="/", method=RequestMethod.GET)
public String provideUploadInfo(Model model) {
List<Bucket> buckets = s3Service.listBuckets();
model.addAttribute("buckets", buckets);
//replace this
//model.addAttribute("folder", "com.smartstudy");
//with
BucketFileForm bucketFileForm = new BucketFileForm();
bucketFileForm.setFolder("com.smartstudy");
model.addAttribute("bucketFileForm", bucketFileForm);
return "index";
}
Now, use this form-backing object in the form
<form role="form" enctype="multipart/form-data" action="#" th:object="${bucketFileForm}" th:action="#{'/drill/skin/upload'}" method="POST">
<div class="form-group">
<label class="form-control-static">Select Bucket</label>
<select class="form-control" th:field="*{folder}">
<option th:each="bucket : ${buckets}" th:value="${bucket.name}" th:text="${bucket.name}">bucket</option>
</select>
</div>
<label class="form-control-static" for="inputSuccess">Select Upload File</label>
<div class="form-group">
<input type="file" th:field="*{uploadFile}" class="form-control" name="uploadFile"/>
</div>
<div class="form-group">
<button class="btn btn-primary center-block" type="submit">Upload</button>
</div>
</form>
Then modify your POST endpoint to accomodate these changes.
#RequestMapping(value="/upload", method=RequestMethod.POST)
public String handleFileUpload(#ModelAttribute("bucketFileForm") final BucketFileForm form, final BindingResult bindingResult, Model model) {
log.info("Bucket: " + form.getFolder() + ", uploadFile: " + form.getUploadFile().getOriginalFilename());
if (!form.getUploadFile().isEmpty() && !form.getFolder().isEmpty()) {
return s3Service.upload(uploadFile, folder);
}
return "index";
}

Spring Boot multiple controllers with same mapping

My problem is very similar with this one: Spring MVC Multiple Controllers with same #RequestMapping
I'm building simple Human Resources web application with Spring Boot. I have a list of jobs and individual url for each job:
localhost:8080/jobs/1
This page contains job posting details and a form which unauthenticated users -applicants, in this case- can use to apply this job. Authenticated users -HR Manager-, can see only posting details, not the form. I have trouble with validating form inputs.
What I tried first:
#Controller
public class ApplicationController {
private final AppService appService;
#Autowired
public ApplicationController(AppService appService) {
this.appService = appService;
}
#RequestMapping(value = "/jobs/{id}", method = RequestMethod.POST)
public String handleApplyForm(#PathVariable Long id, #Valid #ModelAttribute("form") ApplyForm form, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "job_detail"; //HTML page which contains job details and the application form
}
appService.apply(form, id);
return "redirect:/jobs";
}
#RequestMapping(value = "/applications/{id}", method = RequestMethod.GET)
public ModelAndView getApplicationPage(#PathVariable Long id) {
if (null == appService.getAppById(id)) {
throw new NoSuchElementException(String.format("Application=%s not found", id));
} else {
return new ModelAndView("application_detail", "app", appService.getAppById(id));
}
}
}
As you guess this didn't work because I couldn't get the models. So I put handleApplyForm() to JobController and changed a little bit:
#Controller
public class JobController {
private final JobService jobService;
private final AppService appService;
#Autowired
public JobController(JobService jobService, AppService appService) {
this.jobService = jobService;
this.appService = appService;
}
#RequestMapping(value = "/jobs/{id}", method = RequestMethod.POST)
public ModelAndView handleApplyForm(#PathVariable Long id, #Valid #ModelAttribute("form") ApplyForm form, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return getJobPage(id);
}
appService.apply(form, id);
return new ModelAndView("redirect:/jobs");
}
#RequestMapping(value = "/jobs/{id}", method = RequestMethod.GET)
public ModelAndView getJobPage(#PathVariable Long id) {
Map<String, Object> model = new HashMap<String, Object>();
if (null == jobService.getJobById(id)) {
throw new NoSuchElementException(String.format("Job=%s not found", id));
} else {
model.put("job", jobService.getJobById(id));
model.put("form", new ApplyForm());
}
return new ModelAndView("job_detail", model);
}
}
With this way, validations works but I still can't get the same effect here as it refreshes the page so that all valid inputs disappear and error messages don't appear.
By the way, job_detail.html is like this:
<h1>Job Details</h1>
<p th:inline="text"><strong>Title:</strong> [[${job.title}]]</p>
<p th:inline="text"><strong>Description:</strong> [[${job.description}]]</p>
<p th:inline="text"><strong>Number of people to hire:</strong> [[${job.numPeopleToHire}]]</p>
<p th:inline="text"><strong>Last application date:</strong> [[${job.lastDate}]]</p>
<div sec:authorize="isAuthenticated()">
<form th:action="#{/jobs/} + ${job.id}" method="post">
<input type="submit" value="Delete this posting" name="delete" />
</form>
</div>
<div sec:authorize="isAnonymous()">
<h1>Application Form</h1>
<form action="#" th:action="#{/jobs/} + ${job.id}" method="post">
<div>
<label>First name</label>
<input type="text" name="firstName" th:value="${form.firstName}" />
<td th:if="${#fields.hasErrors('form.firstName')}" th:errors="${form.firstName}"></td>
</div>
<!-- and other input fields -->
<input type="submit" value="Submit" name="apply" /> <input type="reset" value="Reset" />
</form>
</div>
Check thymeleaf documentation here
Values for th:field attributes must be selection expressions (*{...}),
Also ApplyForm is exposed then you can catch it in the form.
Then your form should looks like this:
<form action="#" th:action="#{/jobs/} + ${job.id}" th:object="${applyForm}" method="post">
<div>
<label>First name</label>
<input type="text" name="firstName" th:value="*{firstName}" />
<td th:if="${#fields.hasErrors('firstName')}" th:errors="*{firstName}"></td>
</div>
<!-- and other input fields -->
<input type="submit" value="Submit" name="apply" /> <input type="reset" value="Reset" />
</form>

Resources