How to get variable value with thymeleaf - java

I am trying to get make an url to finish on a variable
my template is:
<div th:if="${!user.isEmailValidated()}" class="div-block-13">
<div class="email_confirmed">
Your email is not confirmed!
</div>
</div>
my controller is:
#GetMapping(value = "/email/send/{token}")
public String sendEmail(#PathVariable(value = "token") String token, Model model) {
return "sent-email";
}
I expect url .../email/send/{value of variable} but I get - email/send/$%7Buser.getToken()%7D

The expression ${user.getToken()} is not evaluated by thymeleaf because it's inside a plain href attribute. Use th:href to be able to use thymeleaf expressions: <a th:href="#{'/email/send/' + ${user.getToken()}}">

Related

Thymleaf Spring MVC Button executes Java method

So this is what I have in my HTML file:
<ul>
<th:block th:object="${Post}">
<li class="post" th:each="Post : ${Posts}">
<p th:text ="${Post.getPostText()}"></p>
<button th:onclick = "${Post.upvote()}">Upvote</button>
<button th:onclick = "${Post.downvote()}">Downvote</button>
<p th:text = "${Post.getPostVotes()}"></p>
</li>
</th:block>
</ul>
I want the button to execute a method within the Post class. I'm not sure if I'm using the correct Thymeleaf 'tag'. Right now, when the page loads, it executes the post upvote and downvote methods.
Can anyone help out? I have a feeling I'm using the wrong Thymeleaf Tag.
You need to do a post or get request to invoke those methods. That will only work in JSF, but you can execute the method before de page is rendered as html.
for example this line
<p th:text ="${post.getPostText()}"></p>
will be executed before the page is rendered .
What I do here is to hide a form for both action, two buttons with a name attributes and pass some sort of identifier to know witch entity I'm updating.
In my controller would have two methods that responds to each parameter and return a view or JSON.
So they reason I couldn't do what I wanted to do was because Thymeleaf generates HTML as before the pages loads. It doesn't sit in the HTML waiting to be triggered. I ended up changing the HTML to go to a different URL that would be unique to the post.
<ul>
<th:block th:object="${Post}">
<li class="post" th:each="Post : ${Posts}">
<p th:text ="${Post.getPostText()}"></p>
<a th:href = "#{/post?id={id}&vote=1(id=${Post.getPostId()})}">Upvote</a>
<a th:href = "#{/post?id={id}&vote=0(id=${Post.getPostId()})}">Downvote</a>
<p th:text = "${Post.getPostVotes()}"></p>
</li>
</th:block>
</ul>
And this was the corresponding java code in my controller that would update the object:
#RequestMapping(value = "/post", params = {"id", "vote"})
public String PostVoting(#RequestParam("id") Long id, #RequestParam("vote") int vote)
{
if (currentUser.voteOnPost(id.toString())){
return "redirect:/home";
}
if(vote == 1){
int votes = thePostRepository.findById(id).get().getPostVotes() + 1;
thePostRepository.updateVotes(votes, id);
}
else{
int votes = thePostRepository.findById(id).get().getPostVotes() - 1;
thePostRepository.updateVotes(votes, id);
}
return "redirect:/home";
}
Also, this next part is important if you want to update things like I did:
#Transactional
#Modifying
#Query("UPDATE Post SET votes = :votes WHERE id = :id")
void updateVotes(#Param("votes") int votes, #Param("id") Long id);

how to get some value from url using jstl

I have two forms those have same-url for action, the following form is on page http://www.domain.com/pre-foo-url, which is
<form:form commandName="some" class="form" action="/app/same-url">
<form:input path="title"/>
<input type="hidden" name="redirect" value="foo"/>
<button>OK</button>
</form:form>
and the other form is on http://www.domain.com/bar/{id}
<form:form commandName="some" class="form" action="/app/same-url">
<form:input path="tile"/>
<input type="hidden" name="redirect" value="bar"/>
<button>OK</button>
</form:form>
two methods in my controller, one for deciding to redirect to
#RequestMapping(value = "/same-url", method = RequestMethod.POST)
public String handleRedirect(#RequestParam("redirect") String redirect) {
if (redirect.equals("foo")) {
return "redirect:/foo";
} else {
return "redirect:/bar/{id}"; // this {id} must get the value from http://www.domain.com/bar/{id}<-- Here
}
}
other method for getting the value of id from return "redirect:/bar/{id}"; and goto /bar/{id} request mapping
#RequestMapping(value = "/bar/{id}", method = RequestMethod.GET)
public String handleBar(#PathVariable Integer id) {
// some logic here
return "go-any-where";
}
Now how can I get value from http://www.domain.com/bar/{id} and set that when I redirect it to redirect:/bar/{id},
I have a solution for your need, first I must point out your need then I will write my answer.
First:
-You need to get the /{id} from http://www.domain.com/bar/{id}, it means you want to get the value of last part of url.
you can get that value adding following code on page http://www.domain.com/bar/{id}
<c:set var="currentPage" value="${requestScope['javax.servlet.forward.request_uri']}"/> <!--This will give you the path to current page eg- http://www.domain.com/bar/360 -->
<c:set var="splitURI" value="${fn:split(currentPage, '/')}"/> <!--This will split the path of current page -->
<c:set var="lastValue" value="${splitURI[fn:length(splitURI)-1]}"/><!--This will give you the last value of url "360" in this case -->
<c:out value="${lastValue}"></c:out> <!--use this to make sure you are getting correct value(for testing only) -->
Scond:
-You have to pass value of /{id} which is got from http://www.domain.com/bar/{id}.
pass this using the form as.
<form:form commandName="some" class="form" action="/app/same-url">
<form:input path="title"/>
<input type="hidden" name="redirect" value="bar"/>
<input type="hidden" name="path-var" value="${lastValue}"/>
<button>OK</button>
<form:form>
At Last:
-You want to be redirected to redirect:/bar/{id}".
this could be done using the method below.
#RequestMapping(value = "/add-category", method = RequestMethod.POST)
public String handleRedirect(#RequestParam("redirect") String redirect, #RequestParam("path-var") String pathVar) {
if (redirect.equals("foo")) {
return "redirect:/foo";
} else {
return "redirect:/bar/" + pathVar;
}
}
Important
This is not the Last/Best solution for the problem above.
there may be other/better solutions to this one.
Add this tag lib <%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>, when using any jstl function just as fn:length().
Hope this will work for you.

I am not able to get the value form JSP page to Controller Class on Submit

This code is wriiten in Liferay 6.1 platform.
Description: I have one drop down menu by name "Store Name". I will select any one of the value from drop down and pass that value to javascript function "getStoreDetails" onchange. The sent value from this function will be checked in the javascript array "lNames", If value is present in this array then index will be obtained and using index we obtain value from "fNames" array and add to span class "FirstName". I am able to do this and code is working fine.
Problem:I am not able to get FirstName value from jsp file to Controller Class of submitIssue method.
This is my Controller class
public class IssueController{
public String handleRenderRequest(RenderRequest request, RenderResponse response, Model model) throws Exception {
HttpServletRequest httpRequest = PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(request));
User user = PortalUtil.getUser(httpRequest);
model.addAttribute("my_user", user);
/*Some code goes here to set user attributes like department and organization using model object */
return "issue"; /*This is my jsp file mentioned below*/
}
#ActionMapping
public void submitIssue(#ModelAttribute IssueForm submitIssueForm, ActionRequest request, ActionResponse response) throws PortalException, SystemException, IOException, PortletException {
String First_Name=request.getParameter("FirstName");
System.out.println("First Name while submitting is :\t"+First_Name);
/* here i am not able to obtain value of First_Name */
}
}
The below code is my issue.jsp file
<div class="large-4 medium-8 small-12 columns">
Store Name <select
class="no-highlight" id="StoreName_dropdown"
name="storeName"
onchange="getStoreDetails(this.value);"
<%
String stores[] = new String[] {"1021","1022","1023","1024","1025","1026","1027","1028","1029","1030"};
for(int i=0;i<stores.length;i++){%>
<option value="<%=stores[i]%>"><%=stores[i]%></option>
<%}%>
</select>
</div>
<%
String fNames[] = new String[] {"John1021","wilson1022","test1023","test1024","test1025","test1026","test1027","test1028","test1029","test1030"};
StringBuffer bufferfNames = new StringBuffer();
bufferfNames.append("[");
for(int i=0; i<fNames.length; i++){
bufferfNames.append("\"").append(fNames[i]).append("\"");
if(i+1 < fNames.length){
bufferfNames.append(",");
}
}
bufferfNames.append("]");
String First_Name=bufferfNames.toString();
String lNames[] = new String[] {"1021","1022","1023","1024","1025","1026","1027","1028","1029","1030"};
StringBuffer bufferlNames = new StringBuffer();
bufferlNames.append("[");
for(int i=0; i<lNames.length; i++){
bufferlNames.append("\"").append(lNames[i]).append("\"");
if(i+1 < lNames.length){
bufferlNames.append(",");
}
}
bufferlNames.append("]");
String Last_Name=bufferlNames.toString();
%>
<div class="row ">
<div class="large-3 medium-4 columns">
<span class="firstName">First Name : <span
class="hide-for-medium-up"><b>"dynamically name added"</b></span></span>
<div class="hide-for-small" id="FirstName" >
<b>"dynamically name added"</b>
</div>
</div>
</div>
<div class="row ">
<div class="large-2 medium-3 columns">
<button class="submitIssue submit_button"
id="submitIssue" tabIndex=9>
Submit
</button>
</div>
</div>
<script>
function getStoreDetails(store) {
var fNames=<%=First_Name%>;
var lNames=<%=Last_Name%>;
var index;
index=lNames.indexOf(store);
if (index > -1) {
document.getElementById("FirstName").innerHTML = fNames[index];
}
else{
alert("Store is not present in lNames !!");
}
}
</script>
My javascript program in separate file submitIssue.js
$( document ).ready(function() {
$('button.submitIssue').click(function(){
$('#submitIssueForm').submit();
});
});
Can anyone suggest me to get this value. Please comment in case if you have not understood my problem statement. thanks in advance.
Are you able to see "FirstName" printed in your jsp? If yes, you need to pass this value in input tag, so that you can expect this value to come in your controller. Hope this helps!!

Passing servlet values into <div>

on my Java Servlet I have something like this,
request.setAttribute("InfoLog", info);
RequestDispatcher rd = request.getRequestDispatcher("gc.jsp");
and on my jsp page I have a <div>
<div id="box"></div>
Now using Javascript I want to get the servlet values InfoLog and populate that into my div tag, the purpose of this is that I am verifying some conditions in my Javascript function.
How do I get servlet values in Javascript?
In the jsp, you get the value from Servlet as below,
<% String infoLog = (String)request.getAttribute("InfoLog"); %>
and use this infoLog variable in the div as
<div id="box"><%=infoLog%></div>
and in the javascript function particulary in that if condition you can have below code
if(val == "InfoLog")
{
var infoLog = '<%=infoLog%>';
}
Thanks,
Balaji
You can simply get your attribute in your gc.jsp
<div id="box"> <%=request.getAttribute("InfoLog")%> </div>
Then, if you want to get this value in javascript you can write -
var val = document.getElementById("box").innerHTML;

Insert comma between Anchor widgets

I have this template and code below to generate a "tags" in my web application as inidicated in the sample output:
Template:
<p class="tag" data-field="tags">Tags:
</p>
Java code:
#DataField
DivElement tags = DOM.createElement("p").cast();
#Override
public void setModel(MyModel model) {
binder.setModel(model, InitialState.FROM_MODEL);
for (String tag : model.getTags()){
Anchor a = new Anchor();
a.setText(tag);
a.setHref("#Tags?id=" + tag);
tags.appendChild(a.getElement());
Label comma = new Label(",");
tags.appendChild(comma.getElement());
}
}
HTML Output (Browser):
<p data-field="tags" class="tag">Tags:
<a class="gwt-Anchor" href="#Tags?id=test">test</a>
<div class="gwt-Label">,</div>
<a class="gwt-Anchor" href="#Tags?id=tagg">tagg</a>
<div class="gwt-Label">,</div>
<a class="gwt-Anchor" href="#Tags?id=new">new</a>
<div class="gwt-Label">,</div>
</p>
The problem I face now is that the HTML output when run from the browser should be like this:
<p data-field="tags" class="tag">Tags:
<a class="gwt-Anchor" href="#Tags?id=test">test</a>,
<a class="gwt-Anchor" href="#Tags?id=tagg">tagg</a>,
<a class="gwt-Anchor" href="#Tags?id=new">new</a>
</p>
And not create gwt-label DIV in between
Instead of
Label comma = new Label(",");
tags.appendChild(comma.getElement());
Use
tags.setInnerHTML(tags.getInnerHTML() + ",");
instead of append child try
tags.appendData(",");
I'd recommend to use SafeHTML. SafeHTML templates could also make your code simplier.
public interface MyTemplate extends SafeHtmlTemplates {
#Template("<a class=\"gwt-Anchor\" href=\"#Tags?id={0}\">{1}</a>{2}")
SafeHtml getTag(String url, String text, String comma);
}
(the last argument, "comma" can either be ", " or "").

Categories

Resources