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;
Related
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()}}">
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);
I am developing a web application in which I which I have a JavaScript array and I want this array in my JSP page and iterate it save the data in database.
var value = response;
for (var key in value) {
if (value.hasOwnProperty(key)) {
alert(key + " -> " + value[key]);
var sample = new Array();
sample=value[key];
console.log(sample);
// document.getElementById('');
}
}
});
I want this data on my JSP page is it possible. If it is possible, then how?
You can have javascript in jsp but that will always execute on client side. So if you want to save some stuff on trigger of some event inside browser you can do that by making ajax call or form submission. Ajax is preferred way because its faster and better experience for user
But if you have intention of execution of javascript on server side thats not possible
Java script client side script whereas jsp is server side script so you can't simply do this.
What you can do is submit the calculated variable from javascript to server by form-submission, or using URL parameter or using AJAX calls and then you can make it available on server to store in database.
Client Side:
<script type="text/javascript">
var n = document.getElementById("data");
var f=new Array( "apple", "orange", "mango" );
n.value = f;
</script>
<form action="Your_JSP.jsp" method="POST">
<input type="hidden" id="data" name="data" value="" />
<input type="submit" />
</form>
Server Side:
<%
String val = request.getParameter("data");
String aa[]=val.split(",");
for(String x : aa )
out.println(x);
//now hereyou can use aa array tostore in database or do whatever you want
%>
Try this if you have two different jsp:
first.jsp
<script>
var response = [];
...
var put = function(form) {
form.resp.value = response.join(','); //using comma as separator
};
</script>
<form onsubmit='put(this)' method='next.jsp' method='post'>
<input type='hidden' name='resp' />
<button>Submit</button>
</form>
next.jsp
<%
String[] resp = request.getParameter("resp").split(",");
%>
Response is: ${param.resp} <!-- debugging -->
yes , its possible to do that. you can show array in HTML tag
<!DOCTYPE html>
<html>
<head>
<script>
var value=response;
for (var key in value) {
if (value.hasOwnProperty(key)) {
alert(key + " -> " + value[key]);
var sample = new Array();
sample=value[key];
console.log(sample);
// do here as
document.getElementById("array").innerHTML = sample;
// here array is <p> tag in html and sample is array which will be shown in jsp page.
}
}
</script>
</head>
<body>
<form action="get.jsp" method="POST">
<p id="array" name="array" type="hidden"></p>
<input type="submit" />
</body>
</html>
in get.jsp you will able to get value from array as:
<%
String []array = request.getParameter("array").split(",");
//this String array you can use to store data in DB
%>
I have a slide menu in my jsp Page and After login, I am checking whether user is allowed to view element or not from parameters stored in the database. I need to hide the items based on whether the user is allowed to view or not.
My jsp
<ul style = "display:none">
<li>MyfirstSubmenu</li>
<li>MyfirstSubmenu1</li>
</ul>
My dao:extract:
public boolean userallowed(username, itemid){
..........................
return true;
}
my servlet extract:
if(userallowed(username, itemid)){
session.setAttribute("userallowed", true);
request.getRequestDispatcher("/mypage.jsp").forward(request, response);
}else{
request.getRequestDispatcher("/mypage.jsp").forward(request, response);
session.setAttribute("userallowed", false);
}
How Can I write a javascript Function to able to hide elements based on user permissions?
You may simply do this:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:if test="${true == sessionScope.userallowed}">
<ul>
<li>MyfirstSubmenu</li>
<li>MyfirstSubmenu1</li>
</ul>
</c:if>
Instead of hiding the element with JavaScript, it's more secure if you put that logic in the JSP file:
<% if ((boolean) session.getAttribute("userallowed")) { %>
<ul>
<li>MyfirstSubmenu</li>
<li>MyfirstSubmenu1</li>
</ul>
<% } %>
Notice how those protected menu items are not sent to the client if they are not allowed to see them.
Also, your servlet code could be simplified a little:
session.setAttribute("userallowed", userallowed(username, itemid));
request.getRequestDispatcher("/mypage.jsp").forward(request, response);
Can we initialize JavaScript variables with java in jsp page?
like,
<script type="text/javascript">
var refreshId = setInterval(function() {
var nv=<% out.print(num_voted); %>;
var tv=<%out.print(totalvoted); %>;
var m=<% out.print(month);%>;
var y=<% out.print(year);%>;
alert("refreshed");
$('#alertmessagebox').text("Total members voted "+nv+" out of "+tv+" for "+m+" " +y);
}, 9000);
$.ajaxSetup({ cache: false });
</script>
Code is not working as expected. :(
Is there way to do this? Why it is not possible by this way? shall we need to create header to do this?
Here is an example of setting Javascript variables in a JSP.
<head>
<%
String numVotedStr = request.getParameter("numvoted");
int numVoted = 0;
if (numVotedStr != null) {
numVoted = Integer.parseInt(numVotedStr);
}
%>
<script type="text/javascript">
function setInterval() {
alert("hello " + <%= numVoted %>);
}
</script>
</head>
<body>
<form>
<input type="button" onclick="setInterval()" value="Press Me"/>
</form>
</body>
</html>
To test, use the appropriate version of this URL:
http://localhost:8080/sandbox/example.jsp?numvoted=99
This will popup an alert box with the integral value of "numvoted" on the HTTP request, by producing an HTML page where the value is initialized in Javascript. (The code should have at least a try-catch for the parseInt() call, but this will serve as simple example.)