I'm trying to create an update page for my spring project, When I try to open my edit page using localhost:8080/edit/1 I get
There was an unexpected error (type=Internal Server Error, status=500).
Could not parse as expression: "/edit/{stockNumber}" (editItem:78)
What can I do to solve this issue?
#GetMapping(path="edit/{stockNumber}")
public String editItemForm(#PathVariable Long stockNumber, Model model){
model.addAttribute("item",itemRepository.findOne(stockNumber));
return "editItem";
}
#PostMapping(path="edit/{stockNumber}")
public String editItem(#ModelAttribute Item item){
itemRepository.save(item);
return "redirect:/item";
}
<form action="#" th:object="${item}" th:action="/edit/{stockNumber}" method="post">
<div class="form-group">
<label for="txtItemDesc">Item Description</label>
<input type="text" th:field="*{itemDesc}" class="form-control" id="txtItemDesc" placeholder="item Description" />
</div>
<div class="form-group">
<label for="txtUnit">Unit</label>
<input type="text" th:field="*{unit}" class="form-control" id="txtUnit" placeholder="Unit" />
</div>
<div class="form-group">
<label for="txtAbc">ABC</label>
<input type="text" th:field="*{abc}" class="form-control" id="txtAbc" placeholder="ABC" />
</div>
<button type="submit" value="Submit" class="btn btn-default">Submit</button>
</form>
Your expression in th:action is incorrect. It should be
th:action="'/edit/'+ ${stockNumber}"
Related
have two controllers, that should give Form (html +Thymeleaf) to Update entity and post new data, after redirect to List Entities;
My Controllers
#GetMapping ("/fromUpdate")
public String updateInstructor (Model model, Long instructorId) {
Instructor instructor = instructorService.loadInstructorById(instructorId);
model.addAttribute("instructor", instructor);
return "views/updateInstructor";
}
#PostMapping ("/update")
public String update (Instructor instructor) {
instructorService.updateInstructor(instructor);
return "redirect:/instructors/index";
}
Html form + Thymeleaf
<div class="col-md-6 offset-3 mt-3">
<form class="form-control" method="post"
th:action="#{/instructors/update}" th:object="${instructor}">
<div class="mb-3 mt-3">
<label class="form-label"> Instructor Id :</label>
<input type="number" name="instructorId" class="form-control"
th:value="${instructor.getInstructorId()}">
</div>
<div class="mb-3 mt-3">
<label for="firstName" class="form-label"> First Name :</label>
<input id="firstName" type="text" name="firstName" class="form-control"
th:value="${instructor.getInstructorFirstName()}">
</div>
<div class="mb-3 mt-3">
<label for ="lastName" class="form-label"> Last Name :</label>
<input id="lastName" type="text" name="lastName" class="form-control"
th:value="${instructor.getInstructorLastName()}">
</div>
<div class="mb-3 mt-3">
<label for="instructorSummary" class="form-label"> Summary :</label>
<input id="instructorSummary" type="text" name="instructorSummary" class="form-control"
th:value="${instructor.getInstructorSummary()}">
</div>
<div class="mb-3 mt-3" th:each ="course: ${instructor.getCourses()}">
<input name="courses" class="form-control"
th:value="${instructor.courses[courseStat.index].getCourseId()}">
</div>
<div class ="mb-3 mt-3">
<input name ="user" class="form-control" th:field="${instructor.user}">
</div>
<button type ="submit" class ="btn btn-primary"> Update </button>
</form>
</div>
When i load update form i give next exception
80 --- [nio-8071-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' is not supported]
Must say, when i set in first controller #GetMapping (value =/update) analogical Url with Post my form load with all data.
If you know where my problem, please say me, tnx!!!
It contains a line error: "An error happened during template parsing (template: "class path resource [templates//register.html]")".
I can't open register html page to add new object into db. why?
<form th:action="#{/register-user}" th:object="user" method="post">
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control" id="password" placeholder="Enter password" name="pswd">
</div>
<div class="form-group form-check">
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
My controller
#RequestMapping(path="/register-user", method = RequestMethod.POST)
public String registerNewUser(#Valid #ModelAttribute("user") User user){
userService.register(user);
return "redirect:/login";
}
Your "user" is a model attribute, hence, to access it (and use it as the th:object) you gotta use the ${...} syntax. The result would look like this:
<form th:action="#{/register-user}" th:object="${user}" method="post">
I have a spring-Boot application, and
I am trying to send an object using post method to the below controller:
#PostMapping("/suggestevent")
public String receiveSuggestedEvent(#ModelAttribute SuggestedEvent event) {
return "redirect:/suggestEvent";
}
but it complains with:
There was an unexpected error (type=Method Not Allowed, status=405).
Request method 'POST' not supported
So, what is wrong?
Update:
I have tried this and it also did not work
#RequestMapping(value = "/suggestevent", method = RequestMethod.POST)
The form contains some simple inputes, and a select, which works based on Thyemeleaf. Here is my form:
<form th:action="#{/suggestevent}" method="post">
<div class="form-group">
<label for="title">Title</label>
<input type="text"
class="form-control" id="title" placeholder="Event title"
th:value="${event.title}"
name="title" required="required"/>
</div>
<div class="form-group">
<label for="mainFouce">Main Focus</label>
<input type="text"
class="form-control" id="Focus" placeholder="Focus"
th:value="${event.mainFouce}"
name="Focus" required="required"/>
</div>
Event Type
<div class="form-group">
<select class="form-control" name="type" th:value="${event.type}">
<option value="volvo">Party</option>
<option value="saab">Workshop</option>
<option value="fiat">Friendship</option>
</select>
</div>
<div class="form-group">
<label for="city">Area</label>
<input type="text"
class="form-control" id="area"
th:value="${event.area}"
placeholder="Berlin, Estonia ,or even Asia" name="area"
required="required"/>
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea name="description" class="form-control"
th:value="${event.description}"
required="required" form="usrform"
placeholder="What makes it an special event?"></textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
The sent object is:
#Entity
#Data
public class SuggestedEvent {
#Id
#GeneratedValue
Long id;
String title;
String mainFouce;
EventType type;
String area;
String description;
}
The postman can successfully reach the controller, but the thyemeleaf complains!!!
What happens when you try to add an empty SuggestedEvent object inside the form and try to populate that object like so:
<form th:action="#{/suggestevent}" th:object="${event}" method="post">
<div class="form-group">
<label for="title">Title</label>
<input type="text"
class="form-control" id="title" placeholder="Event title"
th:value="*{title}"
name="title" required="required"/>
</div>
<div class="form-group">
<label for="mainFouce">Main Focus</label>
<input type="text"
class="form-control" id="Focus" placeholder="Focus"
th:value="*{mainFouce}"
name="Focus" required="required"/>
</div>
Event Type
<div class="form-group">
<select class="form-control" name="type" th:value="*{type}">
<option value="volvo">Party</option>
<option value="saab">Workshop</option>
<option value="fiat">Friendship</option>
</select>
</div>
<div class="form-group">
<label for="city">Area</label>
<input type="text"
class="form-control" id="area"
th:value="*{area}"
placeholder="Berlin, Estonia ,or even Asia" name="area"
required="required"/>
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea name="description" class="form-control"
th:value="*{description}"
required="required" form="usrform"
placeholder="What makes it an special event?"></textarea>
</div>
<button class="btn btn-default">Submit</button>
</form>
And in the #GetMapping("/suggestEvent"):
#GetMapping("/suggestEvent")
public String getSuggestEventPage(Model model) {
model.addAttribute("event", new SuggestEvent());
return "suggestEventPage";
}
Check out the official Thymeleaf doc otherwise. This shouldn't really be a problem, since I am doing the exact same thing in my project.
http://www.thymeleaf.org/doc/articles/standarddialect5minutes.html
http://www.thymeleaf.org/doc/articles/springmvcaccessdata.html
http://www.thymeleaf.org/documentation.html
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());
}
I have form and I want to grab the data inserted by users and then convert them json format.
So first here is my form—
<form id="patient_form" action="#" class="form-horizontal">
<div class="control-group">
<label class="control-label" for="firstName"> First Name<em>*</em></label>
<div class="controls">
<input type="text" id="firstName" class="required" maxlength="100"
placeholder="First Name" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="middleNameInitial">
Middle Name Initial</label>
<div class="controls">
<input type="text" id="middleNameInitial"
placeholder="Middle Name Initial" class="input-small"
maxlength="1" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="lastName"> Last Name <em>*</em></label>
<div class="controls">
<input type="text" id="lastName" placeholder="Last Name"
class="required" maxlength="100" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="dateOfBirth"> Date Of
Birth</label>
<div class="controls">
<input type="text" id="dateOfBirth" class="required" />
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="button" class="btn btn-primary"
onclick="savePatientInfo()">Save Changes</button>
<button type="button" class="btn"
onclick="cancelPatientInfoForm()">Cancel</button>
</div>
</div>
</form>
And then I want to send back them to server. And for server side code, I’m using spring mvc and client side I’m using JQuery.
Now how can I do it? I need two things basically,
Ajax call (JavaScript function to which will basically do 3 things, one- grab the form data and convert them into json and then ajax call)
Sever side method to consume ajax call (Controller method as I’m
suing spring mvc.)
Any help is much appreciated.
First of all you need to perform ajax call from the JSP as below:
$.post("${pageContext.servletContext.contextPath}/ajaxTestData",
{
firstName:$("#firstName").val(),
middleNameInitial:$("#middleNameInitial").val(),
<other form data>
},
function(j)
{
<j is the string you will return from the controller function.>
});
Now in the controller you need to map the ajax request as below:
#RequestMapping(value="/ajaxTestData", method=RequestMethod.POST)
#ResponseBody
public String calculateTestData(#RequestParam("firstName") String firstName, #RequestParam("middleNameInitial") String middleNameInitial, HttpServletRequest request, HttpServletResponse response){
<perform the task here and return the String result.>
return "xyz";
}
I have not used the JSON input and result in this way but I think if you return the Pojo then it might converts the same in the json format automatically. Just check that.
Hope this helps you. Cheers.