Why can't I go to other Controller rather than HomeController in Spring framework? - spring

I created a Spring project with STS, using MySql with MyBatis.
I'm trying to make a function for Members to Sign up, but it only keep visiting Homecontroller.java instead of MemberController, when I click the submit button.
This is the arrangement of my files and codes.
This is from index.jsp
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page session="false" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<P> The time on the server is ${serverTime}. </P>
<h1> This is the first page to Log In</h1>
<form id="form1" action="members/logIn">
LogIn <p>
ID: <input type="text" name="id" id="id">
Password: <input type="password" name="pwd" id="pwd">
<input type="button" onclick="logIn()" value="press to LogIn">
</form>
<p><br><br><h3>Move to SignUp page</h3>
<input type="button" onclick="window.location='views/signUp.jsp'" value="Move to Sign Up page">
<h1> This is to Sign Up </h1>
<form id="form2" action="members/join">
ID:
<input type="text" placeholder="Insert ID">
Name:
<input type="text" placeholder="Insert Name"> <p>
PWD:
<input type="text" placeholder="Insert your PWD"> <p>
PWD Check:
<input type="text" placeholder="Confirm your PWD"><p>
Address:
<input type="text" placeholder="Insert Address."> <p>
<input type="submit" value="Sign Up">
</form>
</body>
</html>
and HomeController.java
package kr.co.promptech.controller;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Handles requests for the application home page.
*/
#Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
#RequestMapping(value = "", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate );
System.out.println("Arrived at HomeController.");
return "index";
}
}
MemberController.java
package kr.co.promptech.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import kr.co.promptech.model.Members;
import kr.co.promptech.service.MemberService;
#Controller
#RequestMapping(value="/members")
public class MemberController {
#Autowired
private MemberService memberService;
#RequestMapping(value="join")
public String memberJoin(#RequestParam("id") String id, #RequestParam("pwd") String pwd,
#RequestParam("name") String name, #RequestParam("address") String address){
System.out.println("We have arrived at MemberController");
memberService.memberJoin(new Members(id, pwd, name, address));
return "main";
}
}
Why the Sign Up button keep brings me to HomeController instead MemberController?
also, can anyone help me how to make a button that brings me to main.jsp from index.jsp?
this is not working...
Hope someone can help me here...

OMG, I just found out that all the tags of index.jsp did not have name properties.
It was all my faults... sorry, and Thanks for your answer,

Related

How Spring Boot understand on what exactly custom object is need to map fields from html?

In Spring boot application:
Here repo:
import org.springframework.data.repository.CrudRepository;
import myproject.eshop.model.User;
// Use JPQL
public interface UserRepository extends CrudRepository<User, Long> {
User findByUsername(String username);
}
Here controller:
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import myproject.eshop.model.Role;
import myproject.eshop.model.User;
import myproject.eshop.repo.UserRepository;
import java.util.Collections;
#Controller
public class RegistrationController {
#Autowired
private UserRepository userRepository;
#GetMapping("/registration.html")
public String registration(Model model) {
logger.info("open_registration.html");
model.addAttribute("appName", appName);
return "registration.html";
}
#PostMapping("/registration.html")
public String registartionNewUser(User user, Model model, #RequestParam(name = "retypePassword", required = true) String retypePassword) {
logger.info("retypePassword = " + retypePassword + ", user = " + user);
if (user.getUsername().trim().isEmpty()
|| user.getPassword().trim().isEmpty()
) {
model.addAttribute("registrationError", "Аll fields are required!");
return "registration.html";
}
user.setActive(true);
user.setRoles(Collections.singleton(Role.USER));
User userFromDb = userRepository.findByUsername(user.getUsername());
if (userFromDb != null) {
model.addAttribute("registrationError", "User already exist!");
return "registration.html";
}
userRepository.save(user);
return "redirect:/login.html";
}
}
here template:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:text="${appName}">Template title</title>
<link th:href="#{/public/style.css}" rel="stylesheet"/>
</head>
<body>
<div id="container">
<h2 align="center">Registration new user</h2>
<form th:action="#{/registration.html}" method="post">
<label for="username">Username</label>
<input type="text" id="username" name="username" autofocus="autofocus"/>
<label for="password">Password</label>
<input type="password" id="password" name="password"/>
<label for="retypePassword">Retype password</label>
<input type="password" id="retypePassword" name="retypePassword"/>
<input id="submit" type="submit" value="Registration"/>
</form>
<p th:if="${registrationError}" th:text="${registrationError}" class="error"></p>
</div>
</body>
</html>
Here my custom object User:
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.Set;
#Entity
#Table(name = "usr") // PostgreSQL not work with table "user"
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#NotNull
private String username;
#NotNull
private String password;
#NotNull
private boolean active;
#NotNull
#ElementCollection(targetClass = Role.class, fetch = FetchType.EAGER)
#CollectionTable(name = "user_role", joinColumns = #JoinColumn(name = "user_id"))
#Enumerated(EnumType.STRING)
private Set<Role> roles;
When open registration.html filled all fields and click submit button then call method registartionNewUser
And param user is correct filled (from form registration.html).
How Spring Boot link form registration.html with my customer object User ?
In registration.html no link to my customer object User
Basically you're implemented hibernate or jpa in backend which handle this things for you.
Notice that you column names are same as your name which you pass by html.
So that they accept the requested object get individual variable and create empty object of User class and place on exect match in User entity class and this way create User object.
For cross verification change it to capital or something it gives an 400 error.
This process is not that much easy as we discuss. You modify this as your way using javax library annotations.
For more detail this link,
https://howtodoinjava.com/hibernate-tutorials/
Have you tried make use of #ModelAttribute annotation which will map your custom made
object User to a model attribute and then exposes it to a web view.
<form th:action="#{/registration.html}" modelAttribute= "user" method="post">
<label for="username">Username</label>
<input type="text" id="username" name="username" path = "username"
autofocus="autofocus"/>
<label for="password">Password</label>
<input type="password" id="password" name="password" path = "password"/>
<label for="retypePassword">Retype password</label>
<input type="password" id="retypePassword" name="retypePassword"/>
<input id="submit" type="submit" value="Registration"/>
</form>
And then you bind it in the controller class:
#GetMapping( "/registration.html")
public String registration( #ModelAttribute("user") User user, Model model) {
logger.info("open_registration.html");
model.addAttribute("appName", appName);
return "registration.html";
}

Spring: Error Button Action on Form after add registration (Spring Security)

I do an example with login page - Spring Security.
Shortly:
There's root page ("localhost:8080/") - here's a link on the main page.
Click a link on the main page go to main.html(localhost:8080/main/
If User doesn't authorize he is redirected to login page
When the user authorizes the main page is opened
The main page show messages and filter by tag
I enter a tag in input and push the button Search(Найти), messages are filtered by tag
When I have added authorization filter has stopped work.
This is my source code:
root page - have link on Main page
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Gretting start: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<div>Hello, user</div>
<a th:href="#{/main}">Main page</a>
</body>
</html>
Main page
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<div>
<form method="post">
<input type="text" name="text" placeholder="Введите сообщение" />
<input type="text" name="tag" placeholder="Тэг">
<button type="submit">Добавить</button>
</form>
</div>
<div>Список сообщений</div>
<form method="post" action="filter">
<input type="text" name="filter">
<button type="submit">Найти</button>
</form>
<div th:each = "message : ${messages}">
<b th:text = "${message.id}"></b>
<span th:text = "${message.text}"></span>
<i th:text = "${message.tag}"></i>
</div>
</body>
</html>
Controller processes all mapping
package com.example.sweater;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.example.sweater.domain.Message;
import com.example.sweater.repos.MessageRepo;
#Controller
public class GreetingController {
#Autowired
private MessageRepo messageRepo;
#GetMapping("/")
public String greeting(Model model) {
return "greeting";
}
#GetMapping("/main")
public String main(Model model) {
Iterable<Message> messages = messageRepo.findAll();
model.addAttribute("messages", messages);
return "main";
}
#PostMapping("/main")
public String add(#RequestParam String text, #RequestParam String tag, Model model) {
Message message = new Message(text, tag);
messageRepo.save(message);
Iterable<Message> messages = messageRepo.findAll();
model.addAttribute("messages", messages);
return "main";
}
#PostMapping("/filter")
public String filter(#RequestParam String filter, Model model) {
Iterable<Message> messages;
if (filter != null && !filter.isEmpty()) {
messages = messageRepo.findByTag(filter);
} else {
messages = messageRepo.findAll();
}
model.addAttribute("messages", messages);
return "main";
}
}
WebSecurityConfig have one In Memory User. antMathcers("/") permitAll and anyRequest authenticated
package com.example.sweater.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
#Bean
#Override
public UserDetailsService userDetailsService() {
UserDetails user =
User.withDefaultPasswordEncoder()
.username("u")
.password("p")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
}
My screenshots
root page
Main page
When I enter filter tag and push Button "Найти"(= Search), I've got an error:
#PostMapping("/filter") doesn't catch the action in the form. I checked in the debugger. I can't catch an error and don't know why does this happen.
I have GitHub repository: https://github.com/aalopatin/sweater
Commit with the comment "Add messages" - filter work
Commit with the comment "Add remote repository and Login" - filter doesn't work and add login
I found solving. In a form on the main page need to add 'th' attribute because I use Thymeleaf so template engine. It's needed for _csrf defending which auto insert token in a form if you use Thymeleaf:
<form method="post" th:action="filter">
<input type="text" name="filter">
<button type="submit">Найти</button>
</form>

Unable to Run the following Spring Boot Application that uses JDBC Template

I have created a simple Spring Boot Application that adds Dog information into the MySql database.
The controller class for this Application is DogController.java
package com.dog.resue.controller;
import com.dog.resue.dao.DodRepository;
import com.dog.resue.service.DogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.Date;
#Controller
#RequestMapping(path="/")
public class DogController {
#Autowired
private DodRepository dodRepository;
#Autowired
private DogService dogService;
#RequestMapping(value ="/home",method = {RequestMethod.POST,RequestMethod.GET})
public String adddog(#RequestParam("name") String name,
#RequestParam("rescued") #DateTimeFormat(pattern = "yyyy-MM-dd") Date rescued,
#RequestParam("vaccinated") Boolean vaccinated, Model model)
{
dogService.addADog(name, rescued, vaccinated);
System.out.println("name = " + name + ",rescued = " + rescued + ", vaccinated = " + vaccinated);
return "index";
}
}
and the corresponding Service class is
package com.dog.resue.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import javax.sql.DataSource;
import java.util.Date;
#Service
public class DogServiceImpl implements DogService {
#Autowired
private DataSource dataSource;
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplate=new JdbcTemplate(dataSource);
}
#Override
public void addADog(String name, Date rescued, Boolean vaccinated) {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.update("INSERT INTO dog(name,rescued,vaccinated) VALUES(?,?,?)",name,rescued,vaccinated );
}
}
And the thymeleaf HTML File is
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<!-- META SECTION -->
<title>Dog Rescue</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- END META SECTION -->
<!-- BEGIN STYLE -->
<style>
table, th, td {
border: 1px solid black;
padding: 1px;
}
</style>
<!-- END STYLE -->
</head>
<body>
<h2>Current Dogs In Rescue</h2>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Rescue Date</th>
<th>Vaccinated</th>
</tr>
</thead>
<tbody>
<tr th:each="dogs : ${dogs}">
<td th:text="${dogs.id}">Text ...</td>
<td th:text="${dogs.name}">Text ...</td>
<td th:text="${dogs.rescued}">Text ...</td>
<td th:text="${dogs.vaccinated}">Text...</td>
</tr>
</tbody>
</table>
</div>
<h2>Add A Dog</h2>
<form action="#" th:action="#{/home}" >
<label>Name<input type="text" name="name" id="name"></input></label>
<label>Vaccinated<input type="text" name="vaccinated" id="vaccinated"></input></label>
<label>Rescued<input type="text" name="rescued" id="rescued"></input></label>
<input type="submit" value="Submit"></input>
</form>
</body>
</html>
While running this code i am getting following Error
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sun Jul 22 21:50:32 IST 2018
There was an unexpected error (type=Bad Request, status=400).
Required String parameter 'name' is not present
url is http://localhost:8080/home
Kindly help me to solve this issues
Your Request parameters are missing in URL( name,rescued,vaccinated)
Your url should be
http://localhost:8080/home?name=ARULSUJU&rescued=2012-12-12&vaccinated=true
because all the parameters are required
Looking at your controller
Why you have rescued as Date Type you can change it as String.
So your controller will be
#RequestMapping(value ="/home",method = {RequestMethod.POST,RequestMethod.GET})
public String adddog(#RequestParam("name") String name,
#RequestParam("rescued") String rescued,
#RequestParam("vaccinated") Boolean vaccinated, Model model)
{
dogService.addADog(name, rescued, vaccinated);
System.out.println("name = " + name + ",rescued = " + rescued + ", vaccinated = " + vaccinated);
return "index";
}
Now try this URL
http://localhost:8080/home?name=test&rescued=2014-12-12&vaccinated=true
in your thymeleaf html file add this xmlns :
xmlns:th="http://www.thymeleaf.org"

How to POST data using API in Postman

I am creating an API by using spring boot. Basically, this API does CRUD operations. And also I created a client that consumes my own API. At first I use Postman to POST data, it successfully insert data to the database and gives me 200 OK code. Then I created web page and I use my API as form action. Then I tried to insert data using the API. But, couldn't. Then I removed #RequestBody from the method and after that I was able to insert data. But the thing is now I can't insert data using Postman. When I try to insert data using Postman, it gives me 200 OK, but nothing insert to the database.
How can I Fix this ??
package com.kisalka.pacrestapi.controller;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.kisalka.pacrestapi.repository.ImRepository;
import com.kisalka.pacrestapi.model.ImModel;
#RestController
#RequestMapping("/api")
public class ImController {
#Autowired
private ImRepository TaskRepository;
#RequestMapping(method=RequestMethod.POST, value="/tasks")
public ImModel createNote(ImModel note) {
return TaskRepository.save(note);
}
}
My web page.
<form class="form-horizontal" method="POST" action="">
<div class="form-group">
<label class="control-label col-md-3">Project Name</label>
<div class="col-md-7">
<input type="text" class="form-control" name="pname" id="txtPname"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Developer Name</label>
<div class="col-md-7">
<input type="text" class="form-control" name="devname" id="txtDevname"/>
</div>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Save" id="btnRegister"/>
</div>
</form>
In one of your #Configuration classes or #EnableAutoConfiguration class create a bean of CommonsRequestLoggingFilter, paste the code. This will log every incoming request
#Bean
public CommonsRequestLoggingFilter logFilter() {
CommonsRequestLoggingFilter filter
= new CommonsRequestLoggingFilter();
filter.setIncludeQueryString(true);
filter.setIncludePayload(true);
filter.setMaxPayloadLength(10000);
filter.setIncludeHeaders(false);
filter.setAfterMessagePrefix("REQUEST DATA : ");
return filter;
}
And in your application.properties file set logging level to DEBUG using logging.level.org.springframework.web.filter.CommonsRequestLoggingFilter=
DEBUG
All set! now call your endpoint from the WEB/Postman and check if you find the missing piece.
You need to use #RequestBody :
#RequestMapping(method=RequestMethod.POST, value="/tasks")
public ImModel createNote(#RequestBody ImModel note) {
return TaskRepository.save(note);
}
use the code written below.You need to add #RequestBody before ImModel note
#RequestMapping(method=RequestMethod.POST, value="/tasks")
public ImModel createNote(#RequestBody ImModel note) {
return TaskRepository.save(note);
}

Spring Security 4 : Request method 'POST' not supported

The issue is that when I click on submit I get
Etat HTTP 405 - Request method 'POST' not supported
Here is the controller :
#RequestMapping(value = "/admin/login", method = RequestMethod.GET)
public ModelAndView login(
#RequestParam(value = "error", required = false) String error,
#RequestParam(value = "logout", required = false) String logout) {
LOGGER.debug("admin login page");
ModelAndView model = new ModelAndView();
if (error != null) {
model.addObject("error", "Invalid username and password!");
}
if (logout != null) {
model.addObject("msg", "You've been logged out successfully.");
}
model.setViewName("/admin/index");
LOGGER.debug("returning admin login page");
return model;
}
And the form :
<form class="m-t" role="form" th:action="#{/admin/login}" method="POST" autocomplete="off">
<div th:if="${param.error}" class="alert alert-danger">Invalid username and password.</div>
<div th:if="${param.logout}" class="alert alert-success">You have been logged out.</div>
<div class="form-group">
<input type="text" class="form-control" id="username" name="username" placeholder="Username" required="" />
</div>
<div class="form-group">
<input type="password" class="form-control" id="username" name="username" placeholder="Username" required="" />
</div>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
<button type="submit" class="btn btn-primary block full-width m-b">Login</button>
<small>Forgot password?</small>
<p class="text-muted text-center">
<small>Do not have an account?</small>
</p>
<a class="btn btn-sm btn-white btn-block" href="register.html">Create an account</a>
</form>
It seems like csrf field not working.
I explain, I have normal users website which I refer here by and admin part which is /admin
The login form is correctly displayed. But I when I click submit I get Etat HTTP 405 - Request method 'POST' not supported
Any idea please ?
Here is my security configuration class :
package com.mintad.spring.security;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.ComponentScan;
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;
import org.springframework.security.core.userdetails.UserDetailsService;
/**
* #author Sofiane HAMMAMI
*/
#Configuration
#EnableWebSecurity
#ComponentScan
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
DataSource dataSource;
#Autowired
#Qualifier("customUserDetailsService")
UserDetailsService userDetailsService;
#Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.antMatchers("/admin/**").permitAll()
// .antMatchers("/admin/**").access("hasRole('ADMIN')")
.and().formLogin().loginPage("/login")
.defaultSuccessUrl("/welcome").usernameParameter("username").passwordParameter("password")
.and().exceptionHandling().accessDeniedPage("/404");
}
}
In controller , you defined the form as GET:
#RequestMapping(value = "/admin/login", method = RequestMethod.GET)
and in the form, you are calling it as POST:
form class="m-t" role="form" th:action="#{/admin/login}" method="POST"
change one of these, either at controller or in the form.
If you want to change at controller, replace existing line with:
#RequestMapping(value = "/admin/login", method = RequestMethod.POST)
or you can do it by modifying call from form like
form class="m-t" role="form" th:action="#{/admin/login}" method="GET"
Change your security config to use /admin/login as your login page:
...
.formLogin().loginPage("/admin/login")
Reason you get 405 is, you are trying to submit your form with http post method and defined the end point with http get method.
You need to change your request mapping to method as POST like:
#RequestMapping(value = "/admin/login", method = RequestMethod.POST)
OR you could do vice versa (which is not recommend by security reasons) in your form like:
<form class="m-t" role="form" th:action="#{/admin/login}" method="GET" autocomplete="off">

Resources