How to resolve request methos 'POST' not supported? - spring

I want to design a quick registration page which is placed at the footer when I submit the field, It is showing some error "Request method POST not supported". Someone, please help me to come out of this error.
I have modified the attribute of the form commandName as modelAttribute, but still, the error exists.
This is jsp front end.
<%# tag body-content="empty" trimDirectiveWhitespaces="true"%>
<%# 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/jsp/jstl/core"%>
<c:url value="/setSubscribe" var="subscribe"></c:url>
<form:form action="${subscribe}" method="post" modelAttribute="subscribeForm">
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
<label class="form-check-label radio-inline">
<input type="radio" class="form-check-input" value="gender" name="gender" value="Male"/> Male
</label>
<label class="form-check-label radio-inline">
<input type="radio" class="form-check-input" value="gender" name="gender" value="Female"/> Female
</label>
<br></br>
<div class="row">
<div class="col-sm-3">
<input class="form-control" name="firstName" placeholder="First Name"></input>
</div>
<div class="col-sm-3">
<input class="form-control" name="lastName" placeholder="Last Name"></input>
</div>
<div class="col-sm-3">
<input class="form-control" name="email" placeholder="Your Email Address"></input>
</div>
<div class="col-sm-3">
<button type="submit" class="btn btn-primary">SUBSCRIBE</button>
</div>
</div>
</form:form>
Here is my controller.
#RequestMapping(value = "/setSubscribe", method = RequestMethod.POST)
private String doSubscribe(#ModelAttribute("subscribeForm") final SubscribeForm form)
{
final RegisterData registerData = new RegisterData();
registerData.setFirstName(form.getFirstName());
registerData.setLastName(form.getLastName());
registerData.setSex(form.getGender());
registerData.setLogin(form.getEmail());
final CerCustomerFacadeImpl customerFacadeImpl = new CerCustomerFacadeImpl();
try
{
customerFacadeImpl.newCerRegister(registerData, true);
}
catch (final Exception e)
{
e.printStackTrace();
}
return "";
}
It should have to behave according to the business which has been mentioned in the controller.

Write your controller method with #ResponseBody annotation and consumes property of #RequestMapping annotation, as following:
#RequestMapping(value = "/setSubscribe", method = RequestMethod.POST, consumes = "application/json")
#ResponseBody
private String doSubscribe(#ModelAttribute("subscribeForm") final SubscribeForm form)
{
return "";
}

Related

Property or field 'userName' cannot be found on null

here is the code:-
form.html :
<div class="container">
<div class="row mt-5">
<div class="col-md-6 offset-md-3">
<form th:action="#{/process}" method="post" th:object="${loginData}">
<div class="mb-3">
<label for="exampleInputEmail1" class="form-label">Email address</label>
<input
type="text"
name="userName"
class="form-control"
th:value="${loginData.userName}"
id="exampleInputEmail1"
aria-describedby="emailHelp">
</div>
<div class="mb-3">
<label for="exampleInputPassword1" class="form-label">Password</label>
<input
type="email"
name="email"
th:value="${loginData}"
class="form-control"
id="exampleInputPassword1">
</div>
<div class="mb-3 form-check">
<input
type="checkbox"
class="form-check-input"
id="exampleCheck1">
<label class="form-check-label" for="exampleCheck1">Check me out</label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
MyController :
#GetMapping("/form")
public String formHandler(Model m ) {
System.out.println("opening form");
LoginData loginData = new LoginData();
if(loginData != null ) {
m.addAttribute("login", new LoginData());
System.out.println("YAY");
}else {
System.out.println("Bhag Bh*****ke");
}
return "form1";
}
//handler for process form
#PostMapping("/process")
public String processform(#ModelAttribute("loginData") LoginData loginData) {
System.out.println(loginData);
return"success";
}
success.html :
<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Success</title>
</head>
<body>
<h1>Welcome to this success page</h1>
<h1 th:text="${LoginData.userName}"></h1>
<h1 th:text="${LoginData.email}"></h1>
</body>
</html>
saying error : Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'userName' cannot be found on null
Login page is not ruuning because LoginData is empty at begining
You haven't exactly specified which of the 2 pages are causing the issue, but I'm going to guess that it is the first one.
I would first try replacing the th:value tag with th:field in the username input:
<input
type="text"
name="userName"
class="form-control"
th:field="*{userName}"
id="exampleInputEmail1"
aria-describedby="emailHelp">
Since you have already defined the loginData object within the form tag:
th:object="${loginData}
The next input tag could also cause some issues, I'm guessing that this should accept the user's password:
<input
type="email"
name="email"
th:value="${loginData}"
class="form-control"
id="exampleInputPassword1">
You would want to update it to something like:
<input
type="password"
th:field="*{password}"
class="form-control"
id="exampleInputPassword1">
The exception tells you that there is no model attribute with the name loginData. looking at the controller code after this that can be confirmed as you are adding a model attribute with name login not loginData m.addAttribute("login", new LoginData());
Also I'm not usre why you define a loginData variable in your controller, check if it's non null and than don't use it but create a new one
LoginData loginData = new LoginData();
if(loginData != null ) {
m.addAttribute("login", new LoginData());
System.out.println("YAY");
}

While form submitting using ajax..getting Post not supported error ...don't know what is the error?

I am using form submission using AJAX in Spring MVC and Thymeleaf. When I try to submit it it shows
Post method is not supported
I can't figure out the mistake in my code:
<form class="form-horizontal" action="#" th:action="#{/teacher/teacherProfileUpdation}" th:object="${teacherProfileDetailsList}"
id="saveTeacherForm" method="POST" >
<br />
<div class="row">
<div class="col-lg-14 col-md-12">
<br />
<h5 style="margin-left: 15%;">Personal Details</h5>
<hr />
<div class="form-group">
<label class="col-sm-3 control-label">Name</label>
<div class="col-md-3 col-sm-4 col-xs-4">
<input placeholder="Teacher first name" id="txtTeacherFname" th:field="*{firstName}" type="text" class="form-control" />
</div>
<div class="col-md-3 col-sm-4 col-xs-4">
<input placeholder="Teacher middle name" id="txtTeacherMname" th:field="*{middleName}" type="text" class="form-control" />
</div>
<div class="col-md-3 col-sm-4 col-xs-4">
<input placeholder="Teacher last name" id="txtTeacherLname" th:field="*{lastName}" type="text" class="form-control" />
</div>
</div>
</div>
<div class="col-lg-14 col-md-12">
<div class="form-actions">
<input type="hidden" id="hdnStudentByIdInSchoolAdmin" value="0" />
<input type="button" class="btn btn-info pull-right" id="btnUpdateTeacherProfile" value="Save" />
</div>
</div>
</div>
JS:
saveTeacherProfile :function(){
$("#saveTeacherForm").ajaxForm({
success : function(status) {
alert("success");
},
}).submit();
}
Controller:
#RequestMapping(value = "/updateTeacherProfile", method = RequestMethod.POST)
public String updateTeacherProfile( TeacherProfileDetails teacherProfileDetails){
System.out.println("-----------"+teacherProfileDetails.getFirstName()+"-------------");
System.out.println("-----------"+teacherProfileDetails.getLastName()+"-------------");
System.out.println("-----------"+teacherProfileDetails.getMiddleName()+"-------------");
return "success";
}
You are posting the form, but most likely your Spring controller is not configured to accept POST requests. Try this in your server-side Controller class for this page:
#RequestMapping(..., method = { RequestMethod.GET, RequestMethod.POST }, ...)
public void myControllerMethod()
{
#RequestMapping(..., method = { RequestMethod.GET, RequestMethod.POST }, ...)
public String updateTeacherProfile( TeacherProfileDetails teacherProfileDetails){
//ur Logic
}

Cannot submit a form on SpringMVC

I am fairly new to SpringMVC and have a form that can not submit to the back-end. I created the form as following and when I submit it error 404 will be returned. I changed action to /MyProject/contact but did not work.
<form class="form-horizontal" role="form" method="post"
action="/contact">
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Name
</label> <input type="text" class="form-control" id="name"
name="name" placeholder="Your name" value="">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Email
Address</label> <input type="email" class="form-control" id="email"
name="email" placeholder="Your email" value="">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Phone
Number</label> <input type="number" class="form-control" id="phone"
name="phone" placeholder="Phone number" value="">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Enquiry</label>
<textarea class="form-control" rows="4" name="message"
placeholder="Please enter your enquiry"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-md-2 " style="float: right;">
<input id="submit" name="submit" type="submit" value="Send"
class="btn btn-primary">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<! Will be used to display an alert to the user>
</div>
</div>
</form>
Controller
#Controller
public class ContactController {
#RequestMapping(value="/contact", method=RequestMethod.POST)
public String processForm(Contact contact, Model model){
System.err.println("Contact Name is:" + contact.getName());
return null;
}
}
Error
HTTP Status 404 - /contact
type Status report
message /contact
description The requested resource is not available.
Its beacuse spring does not know how to pass the param Contact contact to your controller method. You need to do couple of things to make it work. Change your form to like below.
<form class="form-horizontal" role="form" method="post" modelAttribute="contact" action="/contact">
Your controller to take contact as model attribute.
#Controller
public class ContactController {
#RequestMapping(value="/contact", method=RequestMethod.POST)
public String processForm(#ModelAttribute Contact contact, Model model){
System.err.println("Contact Name is:" + contact.getName());
return null;
}
}
For a better understanding of what a model attribute does, there are plenty of samples and explanation online. Hope this helps.
I could solve the problem by help of minion's answer, following this tutorial and adding following link
#RequestMapping(value = "/contact", method = RequestMethod.GET)
public ModelAndView contactForm() {
System.err.println("here in GET");
return new ModelAndView("contact", "command", new Contact());
}

Spring MVC with Spring Boot: form tag error - equal symbol expected

I am trying to fill a form with values provided by the controller using tags in an app built with spring boot. But I get an error:
org.apache.jasper.JasperException: /WEB-INF/jsp/index.jsp (line: 52, column: 102) equal symbol expected
related part of index.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%#taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html lang="en">
<head>
<title><spring:message code="title.main" /></title>
</head>
<body>
<%#include file="include/navbar.jsp" %>
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 col-sm-offset-0 col-md-8 col-md-offset-2 main">
<div class="panel panel-default">
<div class="panel-body">
<form:form method="get" id="indexForm" commandName="indexForm" action="<c:url value="index_search" />" role="form">
<div class="row">
<div class="col-xs-6">
<div class="form-group">
<label for="city_out"><spring:message code="label.index.0" /></label>
<input:input type="text" class="form-control" id="city_out" path="city_out" />
</div>
<div class="form-group">
<label for="city_in"><spring:message code="label.index.1" /></label>
<form:input type="text" class="form-control" id="city_in" path="city_in" />
</div>
<div class="form-group">
<label for="company"><spring:message code="label.index.2" /></label>
<form:input type="text" class="form-control" id="company" path="company" />
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
<label for="date0"><spring:message code="label.index.3" /></label>
<form:input type="datetime" class="form-control" placeholder="dd.MM.yyyy [HH:mm]" id="date0" path="date0" />
</div>
<div class="form-group">
<label for="date1"><spring:message code="label.index.4" /></label>
<form:input type="text" class="form-control" placeholder="dd.MM.yyyy [HH:mm]" id="date1" path="date1" />
</div>
<div class="form-group" align="right">
<br />
<button type="submit" id="search_btn" data-loading-text="Loading..." class="btn btn-primary">Search</button>
</div>
</div>
</div>
</form:form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
I have created a class to match form fields:
public class IndexForm {
private String city_out;
private String city_in;
private String company;
private String date0;
private String date1;
// getters, setters
}
And created a bean in main class (I hope so):
#Configuration
#EnableAutoConfiguration
#ComponentScan
public class Application extends SpringBootServletInitializer {
#Bean
public static IndexForm indexForm() {
return new IndexForm();
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
Controller contains this method:
#RequestMapping("/index")
public String index(#RequestParam(value="e", required=false) List<Integer> errors, Map<String, Object> model) {
model.put("indexForm", new IndexForm());
if (errors != null)
model.put("errors", errors);
return "index";
}
I don't see any differences from examples I have seen, so I would be happy if someone pointed at my mistake.
some newbies do a mistake by making the field as required in order to validate the field is filled or not
e.g in normal html -
input type="text" name="name" required
in spring - form:input path="firstName" required .... here required will not work and so same type of error "equal symbol expected".
Oh. It seems, including jsp tags one in another doesn't work. So, I changed
action="<c:url value="index_search" />"
for
action="index_search"
and received my page without errors.

Spring - JSP form:input on jsp page error: jasperexception

When I put the code inside the form:form tag on view cadastro.jsp:
<div class="form-group">
<label for="nome" class="col-sm-2 control-label"> name Project: </ label>
<div class="col-sm-10">
<input for="nome" class="form-control" />
<form:errors path="nome" />
</div>
</div>
Its works
but when i put
<div class="form-group">
<label for="nome" class="col-sm-2 control-label"> Nome do Projeto: </ label>
<div class="col-sm-10">
<form:input cssClass="form-control" path="nome" />
<form:errors path="nome" />
</div>
</div>
not work because the form: input tag
Error:
HTTP Status 500 - An exception occurred processing JSP page /WEB-INF/view/cadastro.jsp at line 34
ProjetroController
#RequestMapping(value = "/novoProjeto", method = RequestMethod.POST)
public String adicionarProjeto(#Valid #ModelAttribute("projeto") Projeto projeto, BindingResult result) {
if(result.hasErrors()) {
return("cadastro");
}
projeto.setStatus("NOVO");
this.pc.salvar(projeto);
return "redirect:/listar";
}
I think you need to add a <form:form> tag around your form, as follows:
<form:form>
<div class="form-group">
<label for="nome" class="col-sm-2 control-label"> Nome do Projeto: </ label>
<div class="col-sm-10">
<form:input cssClass="form-control" path="nome" />
<form:errors path="nome" />
</div>
</div>
</form:form>
In Spring official documentation, it states that:
All the other tags in this library are nested tags of the form tag.
you have to import spring form taglib inorder to use elemnets of spring form like:
add this in top of your jsp
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
then, you can use like:
<form:form id="myForm" method="post" action="/someAction" modelAttribute="formBean">
<form:label path="name"/>
<form:input path="name"/>
<form:form>
and you have add modelAttribute/command object in controller like:
#RequestMapping(value="/someUrl", method=RequestMethod.GET)
public String showForm(Model model){
model.addAttribute("formBean", new FormBean());
return "someViewName";
}
and FormBean class looks like:
public class FormBean {
private String name;
public FormBean(){} //default constructor
//getter and setter for name
}

Resources