FreeMarker Form for nested Object - java

I am trying to write freemarker template but could not able to parse with my object class.
My POJO is
public class Metrix {
#Id
String _id;
String loginId;
Date date;
List<MatrixDetail> headers;
//All getters and setters
}
public class MatrixDetail {
String header;
int time;
String detail;
//All getters and setters
}
//Controller after saving form
#RequestMapping(value = "/matrix/save", method = RequestMethod.POST)
public View saveMatrix(#ModelAttribute Metrix matrix, ModelMap model) {
System.out.println("Reachecd in matrix save" );
return new RedirectView("/TrackerApplication/header.html");
}
FTL template form part
<form name="matrix" action="matrix/save.html" method="post">
<table class="datatable" align:"center">
<tr>
<th>Login Id:</th> <th> <input type="text" name="loginId" value= ${matrixList.loginId} required /> </th>
</tr>
<tr> <td></td><td></td><td></td></tr>
<tr>
<th>Header</th> <th>Time</th> <th>Details</th>
</tr>
**// I am not getting how this nested object which is of type List<MatrixDetail>
// will get parse in my form.**
<#list matrixList.headers as header>
<spring:bind path = "MatrixDetail">
<tr>
<td> <input name = "header" value = ${header.header} /> </td>
<td> <input name = "time" value = ${header.time} /> </td>
<td> <input name = "detail" value = ${header.detail} /></td></tr>
</#list>
</table>
<input type="submit" value="Save" />
</form>
How can we write freemarker template for form processing of such kind of nested object?
I am getting issues in form submission.

I would strongly advise against this.
Forms might be displayable in email in some cases, but they may not always work in the email client, not to mention those that only ever read emails in text-only form won't be able to use them whatsoever.
If you need users to enter a form, link to a page on your site and have the form there instead.

Related

why is my form not passing information in spring boot

Hello i am passing information in a form and everything runs fine but when i fill out the form it doesnt not pass the information and i am getting this error.
There was an unexpected error (type=Internal Server Error, status=500).
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
Caused by: java.sql.SQLIntegrityConstraintViolationException: Column 'movie_id' cannot be null
the code i am using is as folow:
#PostMapping("/save")
public String save(Movie movie) {
savedMovie.save(movie);
return "redirect:/LatestMovies";
}
And
<form th:action="#{/save}" method="post" >
<p><input type="text" id="movie_id" name="movie_id" value="" /></p>
<p><input type="text" id="movie_name" name="movie_name" value="" /></p>
<p><input type="submit" value="save" /></p>
</form>
i belive all other code is correct becuase if i try to render the db information i have no problem.
Update
This is the complete html code.
<div class="container">
<table class="table table-hover">
<tr>
<th>Id</th>
<th>Name</th>
</tr>
<tr th:each="LatestMovies : ${latestMovies}">
<td th:text="${LatestMovies.id}"></td>
<td th:text="${LatestMovies.movieName}"></td>
<td>
<form th:action="#{/save}" method="post" th:object="${newMovie}">
<p><input type="text" id="movie_id" th:field="*{movie_Id}"/></p>
<p><input type="text" id="movie_name" th:field="*{movie_Name}"/></p>
<p><input type="submit" value="save" /></p>
</form>
</td>
</tr>
</table>
Your controller is expecting a Movie object, but it is receiving something else, which then produces a null Movie object. You need to use th:object in your form in order to correctly send the respective class. First, let's add a new #ModelAttribute to your controller, so that your form can automatically map your Movie object in your form.
Controller
// In order to use th:object in a form, we must be able to map a new entity to that form.
// In this case we return a Movie entity.
#ModelAttribute(value = "newMovie")
public Movie newMovie() {return new Movie();}
Now, let's change your form, so that it actually sends a Movie object.
<form th:action="#{/save}" method="post" th:object="${newMovie}">
<p><input type="text" id="movie_id" th:field="*{movie_id}"/></p>
<p><input type="text" id="movie_name" th:field="*{movie_name}"/></p>
<p><input type="submit" value="save" /></p>
</form>
Note that I also changed the name attribute in your inputs, for th:field. Have in mind that in order for this to work, the name of each field must match exactly the names in your objects.
Update
In case you want to set a default value to your form, without using js and since you can't combine th:field with th:value, you could set the object's attribute in your controller.
#ModelAttribute(value = "newMovie")
public Movie newMovie() {
Movie movie = new Movie();
movie.setName("Test");
return movie;
}
Update 2
If what you want is to put the current iteration of a Thymeleaf list in your form, you can do the following.
<div class="container">
<table class="table table-hover">
<tr>
<th>Id</th>
<th>Name</th>
</tr>
<tr th:each="LatestMovies : ${latestMovies}">
<td th:text="${LatestMovies.id}"></td>
<td th:text="${LatestMovies.movieName}"></td>
<td>
<form th:action="#{/save}" th:object="${LatestMovies}" method="post">
<p><input type="hidden" th:value="*{id}"/></p>
<p><input type="hidden" th:value="*{movieName}"/></p>
<p><input type="submit" value="Submit"/></p>
</form>
</td>
</tr>
</table>
You forgot to mark method param with #RequestBody annotation.
This happens because the movie object you are trying to send from the form to the controller is not mapped properly. This has as a result the constraint of the movie_id you have in your movies table (PK not null I guess) to be violated by trying to insert a not null value into it. If you want the object formed in the frontend page form to be binded in a java object you could try this
front page form
<form:form action="save" modelAttribute="movie" method="POST">
<form:label path = "movie_id"> Movie id</form:label>
<form:input path="movie_id" name="movie_id">
<form:label path = "movie_name"> Movie name</form:label>
<form:input path="movie_name" name="movie_name">
<button type="submit">save</button>
</form:form>
(you should import on your page the springframework form taglib
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>)
Save controller code
#PostMapping("/save")
public String save(#ModelAttribute("movie") Movie movie) {
savedMovie.save(movie);
return "redirect:/LatestMovies";
}
Of course I am assuming that your object has a similar structure like shown below
Movie class
public class Movie{
private String movie_id; // or int or long
private String movie_name;
//getters setters constructors ommitted
}

How to submit table data in Spring Thymeleaf

I am following given link to submit table data to be saved in database
http://viralpatel.net/blogs/spring-mvc-multi-row-submit-java-list/
But the difference between given link and my implementation is that the front-end of link uses JSTL (JSP) while i am using Thymeleaf (HTML)
Below are the files being used
HTML Form :
<form method="POST" th:action="#{/updateAllRules}" th:field="${ruleForm}">
<table>
<thead>
<tr>
<th>S No</th>
<th>Title</th>
<th>Body</th>
</tr>
</thead>
<tbody>
<tr th:each="ruleModel,iteration : ${allRules}">
<td th:text="${ruleModel.id}"></td>
<td><input type="text" th:name="${'rule'+iteration.index+'.title'}" th:value="${ruleModel.title}"></td>
<td><input type="text" th:name="${'rule'+iteration.index+'.body'}" th:value="${ruleModel.body}"></td>
</tr>
</tbody>
</table>
<br>
<input type="submit" value="Update All">
</form>
Model Class :
public class Rule {
private Integer id;
private Date timestamp;
private String title;
private String body;
// constructor and Getter/Setters
}
Form Class :
public class RuleForm {
private List<Rule> rule;
public List<Rule> getRule() {
return rule;
}
public void setRule(List<Rule> rule) {
this.rule = rule;
}
}
Controller Method :
#RequestMapping(value = "/updateAllRules", method = RequestMethod.POST)
public String updateAllRules(#ModelAttribute("ruleForm") RuleForm ruleForm) throws IOException
{
System.out.println(ruleForm); // this prints com.web.model.RuleForm#235f9fcb
System.out.println(ruleForm.getRule()); //this prints null
return "redirect:/admin";
}
Please let me know what i am missing.
UPDATE 1:
Made changes as suggested. My new HTML form is as below
<form method="POST" th:action="#{/updateAllRules}" th:object="${ruleForm}">
<table>
<thead>
<tr>
<th>S No</th>
<th>Title</th>
<th>Body</th>
</tr>
</thead>
<tbody>
<tr th:each="rule,iteration : ${ruleForm}">
<td th:field="*{rule[__${iteration.index}__].id}"></td>
<td><input type="text" th:field="*{rule[__${iteration.index}__].title}"></td>
<td><input type="text" th:field="*{rule[__${iteration.index}__].body}"></td>
</tr>
</tbody>
</table>
<br>
<input type="submit" value="Update All">
</form>
On making these changes following exception is being received when the page loads.
org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'rule' cannot be found on object of type 'java.util.ArrayList' - maybe not public?
Please see that i am sending original list in model attribute "ruleForm" on page load. Once page loads the data and user make changes , i want to POST complete table back to controller.
Forms should have a th:object, rather than a th:field:
<form method="POST" th:action="#{/updateAllRules}" th:object="${ruleForm}">
Instead of using th:name and th:value, you should instead be using th:field which does both of those for you. Fields also should be specified using the *{...} syntax, which assumes the th:object automatically.
<input type="text" th:field="*{rule[__${iteration.index}__].title}" />
Everything else looks correct to me.

Passing parameters from JSP to Controller in URL issue

I want to update some user’s data and have issue with receiving parameters from JSP dropdown menu. I want to receive entered compId from “Enter PC” block and pass it as a PathVariable. But it is not seen. If I hardcode action="${app}/adminEdit.do/${user.userId}/${any number}" it works. So, question is – now to get this parameter from dropdown and set it to path? Thanks in advance.
Update.jsp snippet
<c:set var="app" value="${pageContext.request.contextPath}"/>
............
<DIV class="admin_redaction_block">
<sf:form name="adminUserUpdate"
method="POST"
modelAttribute="userForm"
action="${app}/adminEdit.do/${user.userId}/${comp.compId}"
enctype="application/x-www-form-urlencoded">
<c:if test="${not empty errorMsg}">
<div class="error">
<c:out value="${errorMsg}"/>
</div>
</c:if>
<sf:label path="password"><strong>Enter new password:</strong></sf:label> <br>
<sf:input path="password" type="text" size="20"/><br>
<sf:errors path="password" cssClass="error"/>
<br>
<sf:label path="email"><strong>Enter new Email:</strong></sf:label> <br>
<sf:input path="email" type="text" size="20"/><br>
<sf:errors path="email" cssClass="error"/>
<strong>PC Assigned:</strong>
<h3 class="h3">
<td>
<c:choose>
<c:when test="${user.computers!= null && !user.computers['empty']}">
<c:forEach items="${user.computers}" var="comp">
<c:out value="${comp.pcName}"/>
</c:forEach>
</c:when>
<c:otherwise>
<p class="h3_error">No PC Assigned</p>
</c:otherwise>
</c:choose>
</td>
</h3>
<sf:label path="computers">Enter PC:</sf:label> <br>
<sf:select path="computers" size="3">
<c:forEach items="${computers}" var="comp">
<sf:option value="${comp.compId}">
<c:out value="${comp.compId}"/>
</sf:option>
</c:forEach>
</sf:select>
<br> <br>
<input type="SUBMIT" name="SUBMIT" value="Update User"/>
</sf:form>
Controller
#RequestMapping(value = "/adminEdit.do/{userId}/{compId}", method = RequestMethod.POST)
public ModelAndView updateUserProcess(#ModelAttribute(value = "userForm")
UserForm userForm,
#PathVariable("userId") Integer userId,
#PathVariable("compId") Integer compId,
BindingResult result, Model model,
HttpSession session,
HttpServletRequest request) {
User user = userService.getUserById(userId);
model.addAttribute("computers", computerService.getAllComputers());
............
model.addAttribute("userForm", userForm);
return updatingUser(user, model, userForm);
}
You cannot.
You simply forgot that thing are written at different time.
<sf:form name="adminUserUpdate" ...
action="${app}/adminEdit.do/${user.userId}/${comp.compId}" ...>
is written at the time of answering the request that generates the form. At that time, your app (server side) is simply generating a HTML page, and the $comp.compid} does not exist. You can verify it by looking at the HTML source code of the page in your browser.
Later, when you click on the submitbutton, the browser gather data from input fields encode all and send it via a POST request to the action URL without changing it. Browser does not even know that you wrote ${app}/adminEdit.do/${user.userId}/${comp.compId} in your jsp : it only recieved a plain text string localhost:8080/adminEdit.do/2/
So ... try to get comp.compid from an input field of your form using a <sf:select> or <sf:checkboxes> tag.
Well, after long time of searching I've found now I can pass parameters from JSP to Controller. There are special class CustomCollectionEditor which helps pass even multiple select values.
Here is good example https://blog.codecentric.de/en/2009/07/multiple-selects-mit-spring-mvc-2/
And my snippet:
#InitBinder("userForm")
private void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Set.class, "computers", new CustomCollectionEditor(Set.class) {
#Override
protected Object convertElement(Object element) {
String pcName = null;
Set<Computer> computerSet = new LinkedHashSet<>();
if (element instanceof String && !((String) element).equals("")) {
pcName = (String) element;
}
return pcName != null ? computerService.getComputerByName(pcName) : null;
}
});
}

How to get checked boxes in a Controller

I have got a html page (with Thymeleaf):
<form action="#" th:action="#{/changeme}">
<fieldset>
<table style="width: 500px">
<tr th:each="esfield : ${esfields}">
<td>
<div>
<div class="checkbox">
<input type="checkbox" name="optionsMulti"
th:text="${esfield}" />
</div>
</div>
</td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td>
<button type="submit"
class="btn btn-xs btn-primary margin10-right paddingNew"
name="save">Calculate!</button>
</td>
<td></td>
</tr>
</table>
</fieldset>
</form>
When I click Calculate! it goes to my controller
#RequestMapping(value = "/changeme", params = { "save" })
public String save(final ModelMap m) {
m.addAttribute("centers", /*params*/);
return "clustering";
}
I would like to get information about checked boxes in my controller?
How can I do that?
Thank you in advance
You have basically two options :
either you use a different name for each checkbox
or you use spring tag <form:checkbox> instead of native <checkbox>
If you don't posted data will not allow you to know exactly what boxes were actually checked (excepted in cases all and none)
With the approach, you should use in your controller a #ModelAttribute annotated object containing a List<Boolean> and spring will automagically populate it with the values of your checkboxes.
#RequestMapping(value = "/changeme", params = { "save" })
public String save(#ModelAttribute BoxesForm form, final ModelMap m) {
// do what you need with form.getCheckboxes() ...
m.addAttribute("centers", /*params*/);
return "clustering";
}
public class BoxesForm {
List<Boolean> checkboxes;
// getter and setter omitted ...
}

How to call a function with parameters in a java file from a jsp file?

i have the emp.java file with method as
boolean create(int empid,String empname,int supid );
i have the register.jsp page as
<form name="register" action="#" method="post">
<table>
<tr>
<td>Employee Id</td>
<td><input type="text" name="empid"
placeholder="Enter Employee Id " size="30"></td>
</tr>
<tr>
<td>Employee Name</td>
<td><input type="text" name="empname"
placeholder="Enter Employee Name " size="30"></td>
</tr>
<tr>
<td>Supervisor Id</td>
<td><input type="text" name="sup_id"
placeholder="Enter Supervisor Id" size="30"></td>
</tr>
<tr>
<td colspan="2" align="justify"><input type="submit"
value="Submit"></td>
</tr>
</table>
</form>
My requirement is as i click the submit button the emp.create() must be called with the parameters entered in the register.jsp page.... Is there any way to solve this?
What are the necessary things which i have to change so that i can reach my requirement!
or is there any way that i can pass my values to the employee-->create(employee e)
....
{
callableStatement = openConnection().prepareCall("{call insert_employee(?,?,?)}");
callableStatement.setInt(1,employee.getempid());
callableStatement.setString(2,employee.getempname());
callableStatement.setInt(3,employee.getsupid());
}
...
as a object(*) all values when i click submit?
You need a servlet class which will call your emp.java classes' method. The servlet class should work as your action for register.jsp. In the servlet you can do request.getparameter/attribute()and collect the values of input types using their name/id.
Pass these values to either a method or callable anywhere you want to use. If you want to stay on the same jsp after your processing then you need to use ajax.
Add This into the RegisterDao.jsp file
<% Object function_name(call the function of the callable stmt) = new Object();
int empid = Integer.parseInt(request.getParameter("empid"));
String empname = request.getParameter("empname");
int supid = Integer.parseInt(request.getParameter("supid"));
int status = function_name.method(empid, empname, supid);
if (status > 0) {
//out.println("Employee is created");
%>//jsp code to display if he is te employee
<%
session.setAttribute("session", "TRUE");
} else {
out.println("Creation failed");
}
%>
create a bean which should have getter and setter methods of the fields that accepts inputs in the register page
and also inside the bean create your method
boolean create(int empid,String empname,int supid );
now you form action should call a another jsp and it should have these methods in the head
<jsp:useBean id="" class=""></jsp:useBean>

Categories