Request method 'POST' not supported | SPRING BOOT - spring

I'm trying to mount a simple start menu and I get an error in the POST method when I press the submit button.
My controller with the post method called by the submit in html with value "login"
#Controller
#RequestMapping("usuario")
public class UsuarioControlador {
#Autowired
private UsuarioServicio usuarios;
#RequestMapping(method=RequestMethod.GET )
public String index(ModelMap modelMap){
modelMap.put("usuario",new Usuario());
return "usuario/index";
}
//#PostMapping("/login")
#RequestMapping(value="login",method=RequestMethod.POST)
public String login(#ModelAttribute("usuario")Usuario usuario,HttpSession session,ModelMap modelMap){
if(usuarios.findByUserId(usuario.getIdUsuario())!=null){
session.setAttribute("informacion", usuario.getInformacion());
return "usuario/welcome";
}else{
modelMap.put("error", "Usuario no valido");
return "usuario/index";
}
}
}
My index.html with the submit call "login"
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form th:action="#{/usuario/login}"
th:objects="${usuario}" method="post">
<table cellpading="2" cellspacing="2">
<tr>
<td>Usuario</td>
<td><input type="text" th:field="*{idUsuario}" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="login" /></td>
</tr>
</table>
<br/>
<span th:text="${error}"></span>
</form>
</body>
</html>

You have to configure the #RequestMapping tag, to match with the form action /usuario/login, the slash sign its missing.
Replace
#RequestMapping("usuario")
with
#RequestMapping("/usuario")
And Replace
#RequestMapping(value="login",method=RequestMethod.POST)
with
#RequestMapping(value="/login",method=RequestMethod.POST)

Related

Why is the string not added to the property via Model.addObject?

I created #ControllerAdvice to handle BindException:
#ControllerAdvice
class globalControllerAdvice {
#ExceptionHandler(BindException.class)
public ModelAndView handleMyException(HttpServletRequest req, Exception e) {
ModelAndView model = new ModelAndView();
model.addObject("myerror",e.getErrCode());
model.addObject("message",e.getMessage());
model.addObject("exception","bind exception");
model.setViewName("error");
return model;
}
}
And created error.html :
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Handing Form Submission</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style>
table td{
vertical-align:top;
border:solid 1px #888;
padding:10px;
}
</style>
</head>
<body>
<h1>Error Page</h1>
<table>
<tr>
<td>Error</td>
<td th:text="${myerror}"/>
</tr>
<tr>
<td>Message</td>
<td th:text="${message}"/>
</tr>
<tr>
<td>Exception</td>
<td th:text="${exception}"/>
</tr>
</table>
</body>
</html>
And when executing, when I make a mistake on purpose, the page appears normally,but the properties are not filled in .That is, a table is created, but the text "${myerror}" , "${message}" , "${exception}" are not filled in with e.getErrCode() , e.getMessage() ,
"bind exception". Can anyone tell me what the problem is? thanks

Thymeleaf can't see For-each variable

Here is my Service ( It just gets a list of entities )
#Service
public class ProcedureService {
#Autowired
ProcedureRepository procedureRepository;
public List getProceduresList() {
List<Procedure> procedureList;
procedureList = procedureRepository.findAll();
return procedureList;
}
}
Here is my Controller. It just puts list he gets to view.
#Controller
public class ServicesController {
#Autowired
ProcedureService procedureService;
#GetMapping("/services")
public String getCustomer(Model model) {
List<Procedure> procedures = procedureService.getProceduresList();
model.addAttribute("procedures", procedures);
return "services";
}
}
And here is my real problem. Thyme leaf just doesn't see the entity in a List ( it sees the list though ). Here is my screen and full code of View
<!DOCTYPE html>
<html lang="en">
<head>
<title>SpringMVC + Thymeleaf + Bootstrap 4 Table Example</title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h1>Customer Table</h1>
<div class="row col-md-7 table-responsive">
<table id="customerTable" class="table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Age</th>
<th>Street</th>
<th>Postcode</th>
</tr>
</thead>
<tbody>
<tr th:each="procedure: ${procedures}">
<td th:text="${procedure.}" />
<td th:text="${procedure.getId}" />
</tr>
</tr>
</tbody>
</table>
</div>
</div>
I forgot about html lang="en" xmlns:th="http://www.thymeleaf.org" in html so th wasn't really working.

use Thymleaf and spring met org.springframework.web.method.annotation.MethodArgumentTypeMismatchException

I am running a springboot demo,integrated with Thymleaf.But it keep throwing the following exeption:
WARN 25302 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved
[org.springframework.web.method.annotation.MethodArgumentTypeMismatchException:
Failed to convert value of type 'java.lang.String' to required type
'java.lang.Long'; nested exception is java.lang.NumberFormatException:
For input string: "form.html"]**
controller:
#RestController
#RequestMapping("/users")
public class UserController {
#Autowired
private UserRepository userRepository;
private List<User> getUserlist() {
return userRepository.listUser();
}
#GetMapping
public ModelAndView list(Model model) {
model.addAttribute("userList", getUserlist());
model.addAttribute("title", "user management");
return new ModelAndView("users/list", "userModel", model);
}
#GetMapping("/form")
public ModelAndView createForm(Model model) {
User user=new User();
user=userRepository.saveOrUpateUser(user);
model.addAttribute("user", user);
model.addAttribute("title", "create user");
return new ModelAndView("users/form", "userModel", model);
}
list.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="UTF-8">
<title th:text="${userModel.title}">welcome</title>
</head>
<body>
<div th:replace="~{fragments/header :: header}">...</div>
<h3 th:text="${userModel.title}">Welcome to baidu.com</h3>
<div>
create user
</div>
<table border="1">
<thead>
<tr>
<td>ID</td>
<td>Age</td>
<td>Name</td>
</tr>
</thead>
<tbody>
<tr th:if="${userModel.userList.size()} eq 0">
<td colspan="3">no user info!!</td>
</tr>
<tr th:each="user : ${userModel.userList}">
<td th:text="${user.id}">1</td>
<td th:text="${user.age}">11</td>
<td><a href="view.html" th:href="#{'/users/' + ${user.id}}"
th:text="${user.name}">waylau</a></td>
</tr>
</tbody>
</table>
<div th:replace="~{fragments/footer :: footer}">...</div>
</body>
</html>
form.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="UTF-8">
<title th:text="${userModel.title}">users : View</title>
</head>s
<body>
<div th:replace="~{fragments/header :: header}">...</div>
<h3 th:text="${userModel.title}">Welcome to baidu.com</h3>
<div>
back to home
</div>
<form action="/users" method="POST" th:object="${userModel.user}">
<input type="hidden" name="id" th:value="*{id}">
名称:<br>
<input type="text" name="name" th:value="*{name}">
<br>
年龄:<br>
<input type="text" name="age" th:value="*{age}">
<input type="submit" value="提交">
</form>
<div th:replace="~{fragments/footer :: footer}">...</div>
</body>
</html>
User.java
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement // mediatype 转为xml
public class User {
private long id; // 用户的唯一标识
private String name;
private int age;
public User() {
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
....getter and setter
}
on the home page,everything goes fine,except the create user anchor which should return a form to fill.
any idea?

Spring MVC Thymeleaf binding List with check boxes

I am trying to create a form using thymeleaf that contains a series of checkboxes. The object source that I am passing through to the thymeleaf template contains a String and a List.
package com.controller;
import java.util.List;
public class Source {
private String sourceName;
private List<String> testList;
public String getSourceName()
{
return sourceName;
}
public void setSourceName(String name)
{
this.sourceName = name;
}
public List<String> getTestList()
{
return testList;
}
public void setTestList(List<String> list)
{
this.testList = list;
}
}
I pass an object of type source into the template using this MVC controller.
package com.controller;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.View;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import com.web_application.AllEnvironmentsFromFile;
import com.web_application.AllTestsAndPaths;
import com.web_application.RunDao;
import com.web_application.TestAndPath;
#RestController
public class ManualTestController {
#Autowired
private ThymeleafViewResolver resolver;
#Autowired
RunDao rDao;
#Autowired
AllEnvironmentsFromFile environments;
#RequestMapping(value="/manualTest", method=RequestMethod.GET)
public View greetingForm(Model model) throws Exception {
AllTestsAndPaths a = new AllTestsAndPaths();
List<TestAndPath> testList = a.testsAndPaths();
String[] environmentList = new String[environments.getEnvironments().size()];
for(int i = 0; i < environments.getEnvironments().size(); i++)
{
environmentList[i] = environments.getEnvironments().get(i).getName();
}
model.addAttribute("testList", testList);
model.addAttribute("source", new Source());
model.addAttribute("environmentList", environmentList);
return resolver.resolveViewName("manualTest", Locale.US); }
#RequestMapping(value="/manualTest", method=RequestMethod.POST)
public String greetingSubmit(#ModelAttribute Source source, Model model) {
System.out.println(source.getSourceName());
for(String hello : source.getTestList())
{
System.out.println(hello);
}
model.addAttribute("source", source);
return "result";
}
}
The manualTest template looks like this
<!DOCTYPE html>
<html>
<head>
<title>Insert title here</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<form action="#" th:action="#{/manualTest}" th:object="${source}" method="post">
<p>Source: <input type="text" th:field="*{sourceName}" /></p>
<table border="1">
<tr>
<td>Test Name</td>
<td th:each="environment : ${environmentList}"
th:text="${environment}">Tests</td>
</tr>
<th:block th:each="test : ${testList}">
<tr>
<td th:text="${test.name}">A Test'</td>
<th:block th:each="enviro : ${environmentList}">
<td><input type="checkbox" path="${testList}" value="hello" /></td>
</th:block>
</tr>
</th:block>
</table>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>
My problem is that the values of the checkbox are not being stored in the array. When i run this code and click submit i get a null pointer exception because the list in the source object is empty. The sourceName works perfectly but the checkboxes are not actually adding anything.
THis code ended up working, You need to pass in an object containing an arrayList. Also it helped that I combined two variables into one string and i later separated them by -.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Insert title here</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<form action="#" th:action="#{/manualTest}" th:object="${source}" method="post">
<table border="1">
<tr>
<td>Test Name</td>
<td th:each="environment : ${environmentList}"
th:text="${environment}">Tests</td>
</tr>
<th:block th:each="test : ${testList}">
<tr>
<td th:text="${test.name}">A Test'</td>
<th:block th:each="enviro : ${environmentList}">
<td><input type="checkbox" th:field="*{testList}" th:value="|${test.name}-${enviro}|" /></td>
</th:block>
</tr>
</th:block>
</table>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>

Issue in Spring MVC serving static resources

I am running the Spring application with JQuery. But the application is not running. After the JQuery function is called the application is not working. For example please refer the below image, the alert('name') after the $('#name').val(); is not working.
Can any one please tell why it is not working?
I have added the JQuery file in js folder in WebContent.
And for importing the jquery i used the
<script src="/AjaxWithSpringMVC2Annotation/js/jquery.js"></script>
in JSP page.
Here's the full JSP source:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add Users using ajax</title>
<script src="/AjaxWithSpringMVC2Annotation/js/jquery.js"></script>
<script type="text/javascript">
function doAjaxPost() {
// get the form values
alert('doAjaxPost ');
var name = $('#name').val();
alert('name ');
var education = $('#education').val();
alert('education ');
$.ajax({
type : "POST",
url : "/AjaxWithSpringMVC2Annotation/AddUser.htm",
data : "name=" + name + "&education=" + education,
success : function(response) {
// we have the response
$('#info').html(response);
$('#name').val('');
$('#education').val('');
},
error : function(e) {
alert('Error: ' + e);
}
});
}
</script>
</head>
<body>
<h1>Add Users using Ajax ........</h1>
<table>
<tr>
<td>Enter your name :</td>
<td><input type="text" id="name"><br /></td>
</tr>
<tr>
<td>Education :</td>
<td><input type="text" id="education"><br /></td>
</tr>
<tr>
<td colspan="2"><input type="button" value="Add Users"
onclick="doAjaxPost()"><br /></td>
</tr>
<tr>
<td colspan="2"><div id="info" style="color: green;"></div></td>
</tr>
</table>
<a href="/AjaxWithSpringMVC2Annotation/showUsers.htm">Show All
Users</a>
</body>
</html>
You might want to add a resource handler for the path js/**. See 17.15.6 Configuring Serving of Resources.
#Configuration
#EnableWebMvc
public class SpringConfiguration extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
}
}
or in XML:
<mvc:resources mapping="/js/**" location="/js/"/>

Resources