Thymeleaf insert text in html code? - java

I want to insert an Attribute into the html Code.
I tried this, but it's not working:
<div id="${var}"> ... </div>
I think you know what I mean. The attribute 'var' should be the id. I didn't find a solution...

You just need to use the th:attr attribute. It is explained in the reference documentation 5.1:
5.1 Setting the value of any attribute
Enter then the th:attr attribute, and its ability to change the value
of attributes of the tags it is set in:
<form action="subscribe.html" th:attr="action=#{/subscribe}">
<fieldset>
<input type="text" name="email" />
<input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/>
</fieldset>
</form>
The
concept is quite straightforward: th:attr simply takes an expression
that assigns a value to an attribute. Having created the corresponding
controller and messages files, the result of processing this file will
be:
<form action="/gtvg/subscribe">
<fieldset>
<input type="text" name="email" />
<input type="submit" value="¡Suscríbe!"/>
</fieldset>
</form>

Use this
<div th:attr="id=${var}"> ... </div>

Thymeleaf only evaluates attributes that are prefixed with th:. Here is a list of the attributes that are evaluated:
http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#setting-value-to-specific-attributes
In your case, th:id is already built in so you can simply do <div th:id="${var}"> ... </div> and it will work. th:attr, is used to define attributes that thymeleaf doesn't normally support.

Related

JSP FORM POST : empty attributes

I can't find one attribute sent from a JSP form.
<form name="shuntingForm" action="/TCS_FUND/ShuntAction.aen" method="POST">
<div class="field-item clearfix">
<input type="hidden" name="csrfPreventionSalt" value="<%=CsrfPreventionSalt%>" />
<input type="hidden" name="idSession" value="<%=idSession%>">
Funds Trading<br>
</div>
</form>
request.getAttribute("idSession") & request.getParameter("idSession") show NULL.
Any ideas ? thanks
I would simplify this to return a fixed value.
Change:
<input type="hidden" name="idSession" value="<%=idSession%>">
To:
<input type="hidden" name="idSession" value="123456789">
Once that works, figure out the difference.
You also may want to view the source of the web page. If your idSession does not have the value you expect, your input tag will show the wrong value field.

How to pass object from th:each loop to controller

I have form and corresponding controller to which list of objects is passed. After that this list is redirected as an attribute to another method and displayed in a website. After that I would like to pass object from this list via form in a carSearchResult.html file to controller. I was trying to do like it is described here Spring and Thymeleaf: Sending an object to a controller from a th:each table but it does not work properly. It is sending an object to controller but with fields property and model set as blank (but they are not null).
searchCar form
<form action="#" th:action="#{/user/searchCar}" method="post">
<input type="radio" name="type" value="hatch" /> Hatchback <br/>
<input type="radio" name="type" value="sedan" /> Sedan <br/>
<input type="radio" name="type" value="combi" /> Kombi <br/>
<input type="radio" name="type" value="sport" /> Sport <br/>
<input type="radio" name="type" value="cabrio" /> Cabrio <br/>
<input type="text" name="dailyPrice" placeholder="Price" /> <br/>
<input type="date" name="dateOfRent" placeholder="Date of rent" /> <br/>
<input type="date" name="dateOfReturn" placeholder="Date of return" /> <br/>
<input type="submit" value="Show" />
</form>
Controller method for searchCar post request
#PostMapping("/user/searchCar")
public String searchCar(Model model, #RequestParam String type, #RequestParam double dailyPrice,
#RequestParam Date dateOfRent, #RequestParam Date dateOfReturn, RedirectAttributes redirectAttr) {
List<Car> allCarsList = carDao.getAllCars(type, dailyPrice, dateOfRent, dateOfReturn);
redirectAttr.addFlashAttribute("carList", allCarsList);
return "redirect:/user/carSearchResults";
}
Method where list is redirected
#GetMapping("/user/carSearchResults")
public String showCarSearchResults(Model model) {
model.addAttribute("car", new Car());
return "user/carSearchResults";
}
Form where list is displayed
<div th:each="car: ${carList}">
<h3 th:text="${car.producer}"></h3>
<h3 th:text="${car.model}"></h3>
<form action="#" th:action="#{/user/showCarDetails}" method="post" th:object="${car}">
<input type="hidden" th:field="*{producer}" /> <br/>
<input type="hidden" th:field="*{model}" /> <br/>
<input type="submit" value="Show" />
</form>
</div>
Method to which I want to send object from th:each loop
#PostMapping("/user/showCarDetails")
public String showCarDetails(#ModelAttribute Car car) {
System.out.println(car);
return "user/showCarDetails";
}
After printing information about car in console I receive object below. It looks like it is passed but with parameters as a blank space. Can anyone help me? Many thanks.
Car [id=null, producer=, model=, seatsNumber=null, type=null, registrationNumber=null, dailyPrice=null, description=null]
EDIT
I have changed the form. Option with th:attr and th:value works but I do not really understand why th:field does not work and what is the difference between them. As I understand from documentation th:value is some kind of older version of th:field?
<div th:each="car: ${carList}" th:object="${car}">
<h3 th:text="*{producer}"></h3>
<h3 th:text="*{model}"></h3>
<form action="#" th:action="#{/user/showCarDetails}" method="post">
<input type="hidden" th:value="*{producer}" name="producer" /> <br/> <!-- It works -->
<input type="hidden" th:attr="value=*{producer}" name="producer" /> <br/> <!-- It works -->
<input type="hidden" th:field="*{producer}" /> <!-- It does not work -->
<input type="submit" value="Pokaż" />
</form>
</div>
th:object works differently when you use it on a <form>, vs. when you use it other places. When you use it in a form, it expects it to resolve to a single variable on the model. You cannot use it with a temporary variable (like {$car} -- which isn't on the model, it's just a temporary variable created byth:each) because the attribute just isn't built to work like that.
th:field generates both the value and name tags -- but again, it has to work within the same limitations as th:object. The reason manually adding name and value attributes work, is because they happen to line up with what spring is expecting in a post and it's able to create the object based on the names.
As for how to solve the original problem... I think you have two options:
Create a command object which has a List of Cars as a property. That way you can use the th:object and th:field properties. You'll have to have the submit button to supply which car is being edited.
Continue manually creating the name and value fields like you already are.

input value text field in jsp error

My index.jsp is as following:
<form action="FileUploadServlet" id="formSubmit" method="post" enctype="multipart/form-data">
<input type="text" id="txtFileName" value="${fname}"/>
<input type="file" name="fileName" id="selectedFile" style="display: none;">
<input type="button" id="btnBrowse" value="Browse..." onclick="document.getElementById('selectedFile').click();" />
<input type="submit" value="Upload" id="btnUpload">
</form>
with value=${fname} is get from dopost method in servlet when form summited
request.setAttribute("fname", fileName);
getServletContext().getRequestDispatcher("/index.jsp").forward(
request, response);
But it's weird that when I deployed index.jsp
My text field always show ${fname} in text area, even after form submitted, its still get that value (correctly it must show 'filename')
Does anyone meet this problem like me?
First thing is that, you are using wrong syntax to display value in JSP.
Below syntax is wrong.
value="${fname}"
We use expression tag fordisplaying value in JSP page. Expression tag convert into Java statement.
<%=request.getAttribute("fname")%>
When you first time open your index.jsp page, it will show you blank value and when request will come back from server side, then it will show you correct result.
Use below code.
<%if(request.getAttribute("fname")!=null){%>
<input type="text" value ="<%=request.getAttribute("fname") %>"/>
<%}else
{ %>
<input type="text"/>
<%} %>
In JSP, the correct syntax to retrieve the values is
<%=request.getAttribute("fname")%>
This is known as assignment OR expression tag (<%=%>).
Try this ...
<form action="FileUploadServlet" id="formSubmit" method="post" enctype="multipart/form-data">
<input type="text" id="txtFileName" value="<%=request.getAttribute("fname")%>"/>
<input type="file" name="fileName" id="selectedFile" style="display: none;">
<input type="button" id="btnBrowse" value="Browse..." onclick="document.getElementById('selectedFile').click();" />
<input type="submit" value="Upload" id="btnUpload">
</form>
More related to this, here.

Getting Null from post data from jsp

<center>
<form class="form-horizontal" action="${pageContext.servletContext.contextPath}/LargeLandmarkListGet" method="post">
<div class="form-group">
<label class="control-label col-sm-2" for="SLLRID">SLLRID:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="SLLRID" placeholder="Enter SLLRID...">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
</center>
That is the particular definition of the action in the JSP.
String SLLRID = request.getParameter("SLLRID");
This is how I am trying to get it in the servlet, within the doPost method. However, SLLRID is always null. I've tried everything I can think of but I cannot get it to return the inputted value. However, if I hardcode the value, everything works perfectly, so I think there is something wrong when communicating between the JSP and the servlet.
What I Have Tried:
Changing the name in for in the label definition, so that id and for are named differently
Adding an id value to the button
Hardcoding the value to verify the servlet
Trying a get rather than a post (though that seemed wildly inappropriate)
Testing other servlets with the same JSP (this worked, though not with this particular submission id)
Ensuring that everything that needed entries in web.xml had said entries made
The form sends the data based on the name attribute. So instead put: <input type="text" class="form-control" id="SLLRID" name="SLLRID" placeholder="Enter SLLRID...">

navigating through tab key not working properly

in my jsp, when i navigate through tab key it skips my Save and Reset button. and move to next component in my page. even though i have not used tabindex in my jsp files. please suggest what could be the reason. thanks
code is like:
<div>
<input type="hidden" name="_flowExecutionKey" value="${flowExecutionKey}"/>
<input type="submit" class="button" name="_eventId_search" value="Search"/>
<span class="save_button_common" onClick="submitForm('save')">Save</span>
<span class="reset_button_common" onClick="submitForm('reset')">Reset</span>
</div>
May be because it is not input type , you can explicitly try setting tabIndex
Try:
<div>
<input type="hidden" name="_flowExecutionKey" value="${flowExecutionKey}"/>
<input type="submit" class="button" name="_eventId_search" value="Search"/>
<input type="button" class="save_button_common" onClick="submitForm('save')">Save</input>
<input type="button" class="reset_button_common" onClick="submitForm('reset')">Reset></input>
</div>
Note if it's a form you need input type="button" rather than just using <button> which you can otherwise just for straight links that don't submit a form. This is particularly relevant with Internet Explorer that treats the button tag somewhat differently to other browsers (submitting the "value=" rather than the enclosed text or something like that)

Categories