I have passed arraylist from Servlet to JSP using session. I want to use autocomplete textbox with values from that arraylist. but i am not sure how to do that..
My list is
<%! List l1=new ArrayList()%>
<%l1=(ArrayList)session.getAttribute("authorname");%>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
var availableTags = ['<%=l1.get(2)%>'];
$("#tags").autocomplete({
source: availableTags
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags:</label>
<input id="tags">
</div>
</body>
</html>
when i use specific values like "l1.get(2)" i can get that value in autocomplete textbox, but i am not sure how to give all values of list inside jquery..
This is the snippet for loading the List to array type in javascript in JSP
<script>
var availtags= [];
<% for(String name:l1)
{
%>
availtags.push("<%=name%>")
<%
}
%>
</script>
EXPLANATION after getting the attribute immediately use this script so that all the list value is been stored in the var availtags
and then use the same var for any reference in your javascript
function
Hope so this will be helpful for you
for more details
w3schools
Related
I am making a job search web application using java. I have alotted a job id to each job and i am displaying the list of jobs in a bootstrap table from database. on each button click i need to forward this job id to a jsp page where i am adding the applicant name to the database corresponding to the jobs.My code is:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="com.dbutil.CrudOperation"%>
<%# page import="java.util.*,java.sql.*" %>
<%# page import="javax.servlet.http.HttpSession" %>
<html>
<head>
<title>Job List</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/jobs.css">
<script src="jquery.js"></script>
<script src="bootstrap.min.js"></script>
</head>
<body data-spy="scroll" data-target=".navbar" data-offset="50">
<% Connection con = null;
ResultSet rs = null,rs1=null;
PreparedStatement ps = null;
HttpSession hs = null;
hs=request.getSession();
con = CrudOperation.createConnection();
%>
<div class="container">
<%String strsql = "select * from postjob1 where sr>0";
try {
ps = con.prepareStatement(strsql);
rs = ps.executeQuery(); %>
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th>Job Id</th><th>Job Category</th><th>Available Posts</th><th>Required Qualifications</th><th>Salary Details</th><th>Location</th><th>Last date of application</th><th></th>
</tr>
</thead>
<% while (rs.next()) {
%>
<tbody>
<tr><td><%=rs.getString("id")%></td><td><%=rs.getString("jobcategory")%></td><td><%=rs.getString("available")%></td><td><%=rs.getString("requiredqualification")%></td><td><%=rs.getString("salarydetails")%></td><td><%=rs.getString("location")%></td><td><%=rs.getString("lastdate")%></td><td><button type="button" class="btn btn-primary" onclick="<% hs.setAttribute("ID",rs.getString("id")); %>" >View Details </button></td></tr>
</tbody>
<%}
} catch (SQLException se) {
System.out.println(se);
}%>
</table>
</div
</div>
</body>
</html>
I am facing difficulty when I am retreiving the session value ID in other jsp page as i am getting id of the last row in the table irrespective of whichever button i click.Kindly help me run my code.Thanks!
<% hs.setAttribute("ID", rs.getString("id")); %>
In the excerpt above, you are setting the session attribute "ID". After executing the while loop, it stores the last "id" value. The same value is recovered in the destination page, whichever the clicked link.
A possible solution is passing the id in the invoked URL to the following page.
<a href="jobDetails.jsp?idJob=<%=rs.getString("id")%>">
<button type="button" class="btn btn-primary">View Details</button>
You can recover the parameter in jobDetails.jsp using
request.getParameter("idJob")
Note: I'm a bit rusty in JSP. Maybe I've forgotten a quote or something, but that's the idea.
You can pass job id like request's parameter.
For example you can call your jsp-page like that:
<a href="jobDetails.jsp?job_id=3" />
Where job_id is a parameter name and 3 is its value.
After that you can read parameter's value in your jobDetails.jsp in next way:
<%=request.getParameter("job_id")%>
I have the following problem iterating on a collection into a JSP page.
This is the code of my JSP:
<%# page import="com.myproject.xmlns.EDILM.SalReport.SalDettaglio" %>
<%# page import="com.myproject.xmlns.EDILM.SalReport.RM" %>
<!-- showSalwf.jsp -->
<html>
<head>
<title>Libretti</title>
<link href="css/business_thema.css" rel="stylesheet" type="text/css">
<link href="css/dataTables/datatable.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery-ui.js"></script>
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<style type="text/css">
#TabellaSalwf2 {
background-color: #99FFFF;
}
</style>
</head>
<body>
<%
out.println("TEST SALWF");
%>
<table id="TabellaSalwf">
<tr><td>-</td></tr>
<%
for (SalDettaglio salDettaglio : (SalDettaglio[]) request.getSession(false).getAttribute("salDettaglio")) {
%>
<tr>
<td><%=salDettaglio.getCodice()%></td>
<td><%=salDettaglio.getStato()%></td>
<td><%=salDettaglio.getDataCreazione()%></td>
<td><%=salDettaglio.getDataRegistrazione()%></td>
<td><%=salDettaglio.getAutoreConvalida()%></td>
<td><%=salDettaglio.getAutoreConvalida()%></td>
<td><%=salDettaglio.getAutoreAcquisizione()%></td>
</tr>
<%}%>
</table>
<br />
<table id="TabellaSalwf2" border="1">
<%
for (SalDettaglio salDettaglio : (SalDettaglio[]) request.getSession(false).getAttribute("salDettaglio")) {
%>
<tr id="salDettaglioRow">
<td><%=salDettaglio.getCodice()%></td>
<td><%=salDettaglio.getStato()%></td>
<td><%=salDettaglio.getDataCreazione()%></td>
<td><%=salDettaglio.getDataRegistrazione()%></td>
<td><%=salDettaglio.getAutoreCreazione()%></td>
<td><%=salDettaglio.getAutoreConvalida()%></td>
<td><%=salDettaglio.getAutoreAcquisizione()%></td>
<td><%=salDettaglio.getTotImponibile().toString()%></td>
<td><%=salDettaglio.getFornitore()%></td>
<td><%=salDettaglio.getRmConRiserva()%></td>
<td><%=salDettaglio.getErrore()%></td>
</tr>
<%
for (RM currentRM : salDettaglio.getRM()) {
}
%>
<%}%>
</table>
</body>
</html>
As you can see there is a table that contains 2 nested iteration. I have no problem with the first iteration (the most external): this iteration retrieve an array of SalDettaglio objects from the session and iterate on this object printing all the fields of each SalDettaglio object as a row.
Now each SalDettaglio object contains itself an array of RM objects.
Now I have to iterate also on the object of this array (in the inner iteration).
The problem is that with these lines I can't do it:
for (RM currentRM : salDettaglio.getRM()) {
// DO SOME OPERATIONS ON EACH OBJECT
}
Using the debugger I see that salDettaglio.getRM() is an array of 2 RM objects but in the debugger say Cannot find local variable for 'currentRM' (that have to contain the current RM object into the retrieved array).
Why it don't work? How can I fix this issue?
Tnx
Your inner loop has no code in it. Because of that, you can't place your breakpoint in any place where the currentRM is certain to be defined. In fact, it's conceivable that the whole loop is optimized out.
In the javascript function jsp I am trying to print the date.But it doesn't get printed. Why is this so ? The date should get printed before the text in the h1 tag. But the problem is date doesn't get printed ! Why is this so ?
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP - 1</title>
<script>
function jsp() {
<%= new java.util.GregorianCalendar().getTime().toString() %>
}
</script>
</head>
<body>
<h1>
Was I printed first ? Or is it the date... ..
</h1>
<script type="text/javascript">
setTimeout(jsp,2000);
</script>
</body>
<script>
function jsp() {
document.write('<%= new java.util.GregorianCalendar().getTime().toString() %>');
// or any other JS function you may want to use
}
</script>
You're mixing server-side and client-side.
With your original function, your browser will see (for example)
<script>
function jsp() {
2012-08-24 11:57:00
}
</script>
but this isn't JS-valid (as you see).
And to answer your hidden question, the date will be printed last, because it's located after the h1 (in a DOM-speaking way).
How can I read/access a JSP variable from JavaScript?
alert("${variable}");
or
alert("<%=var%>");
or full example
<html>
<head>
<script language="javascript">
function access(){
<% String str="Hello World"; %>
var s="<%=str%>";
alert(s);
}
</script>
</head>
<body onload="access()">
</body>
</html>
Note: sanitize the input before rendering it, it may open whole lot of XSS possibilities
The cleanest way, as far as I know:
add your JSP variable to an HTML element's data-* attribute
then read this value via Javascript when required
My opinion regarding the current solutions on this SO page: reading "directly" JSP values using java scriplet inside actual javascript code is probably the most disgusting thing you could do. Makes me wanna puke. haha. Seriously, try to not do it.
The HTML part without JSP:
<body data-customvalueone="1st Interpreted Jsp Value" data-customvaluetwo="another Interpreted Jsp Value">
Here is your regular page main content
</body>
The HTML part when using JSP:
<body data-customvalueone="${beanName.attrName}" data-customvaluetwo="${beanName.scndAttrName}">
Here is your regular page main content
</body>
The javascript part (using jQuery for simplicity):
<script type="text/JavaScript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<script type="text/javascript">
jQuery(function(){
var valuePassedFromJSP = $("body").attr("data-customvalueone");
var anotherValuePassedFromJSP = $("body").attr("data-customvaluetwo");
alert(valuePassedFromJSP + " and " + anotherValuePassedFromJSP + " are the values passed from your JSP page");
});
</script>
And here is the jsFiddle to see this in action http://jsfiddle.net/6wEYw/2/
Resources:
HTML 5 data-* attribute: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes
Include javascript into html file Include JavaScript file in HTML won't work as <script .... />
CSS selectors (also usable when selecting via jQuery) https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_started/Selectors
Get an HTML element attribute via jQuery http://api.jquery.com/attr/
Assuming you are talking about JavaScript in an HTML document.
You can't do this directly since, as far as the JSP is concerned, it is outputting text, and as far as the page is concerned, it is just getting an HTML document.
You have to generate JavaScript code to instantiate the variable, taking care to escape any characters with special meaning in JS. If you just dump the data (as proposed by some other answers) you will find it falling over when the data contains new lines, quote characters and so on.
The simplest way to do this is to use a JSON library (there are a bunch listed at the bottom of http://json.org/ ) and then have the JSP output:
<script type="text/javascript">
var myObject = <%= the string output by the JSON library %>;
</script>
This will give you an object that you can access like:
myObject.someProperty
in the JS.
<% String s="Hi"; %>
var v ="<%=s%>";
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
<title>JSP Page</title>
<script>
$(document).ready(function(){
<% String name = "phuongmychi.github.io" ;%> // jsp vari
var name = "<%=name %>" // call var to js
$("#id").html(name); //output to html
});
</script>
</head>
<body>
<h1 id='id'>!</h1>
</body>
I know this is an older post, but I have a cleaner solution that I think will solve the XSS issues and keep it simple:
<script>
let myJSVariable = <%= "`" + myJavaVariable.replace("`", "\\`") + "`" %>;
</script>
This makes use of the JS template string's escape functionality and prevents the string from being executed by escaping any backticks contained within the value in Java.
You could easily abstract this out to a utility method for re-use:
public static String escapeStringToJS(String value) {
if (value == null) return "``";
return "`" + value.replace("`", "\\`") + "`";
}
and then in the JSP JS block:
<script>
let myJSVariable = <%= Util.escapeStringToJS(myJavaVariable) %>;
</script>
The result:
<script>
let myJSVariable = `~\`!##$%^&*()-_=+'"|]{[?/>.,<:;`;
</script>
Note: This doesn't take separation of concerns into consideration, but if you're just looking for a simple and quick solution, this may work.
Also, if you can think of any risks to this approach, please let me know.
Basically I want to do the same as here which is done in Python.
I'd like to replace all self-closed elements to the long syntax.
Example
<iframe src="http://example.com/thing"/>
becomes
<iframe src="http://example.com/thing"></iframe>
Full example:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="/sample.css">
<title></title>
<script type="text/javascript" src="/swfobject.js">
//void
</script>
<script type="text/javascript" language="JavaScript" src="/generate.js">
//void
</script>
<script type="text/javascript" language="JavaScript" src="/prototype.js">
//void
</script>
</head>
<body id="mediaPlayer" style="margin:0;padding:0;">
<script type="text/javascript">
swfobject.registerObject('id_G12564763');
function getFlashObject() {
var object;
if (navigator.appName == 'Microsoft Internet Explorer' || navigator.userAgent.indexOf("Chrome")!=-1)
{
object = document.getElementById('id_G12564763');
}
else
{
object = document['flash_id_G12564763'];
}
return object;
}
</script>
</body>
</html>
This can be used to replace one tag (code in javascript).
var becomes = "<iframe src='http://example.com/thing'/>".replace(/<(\w*) (.*)\//,'<$1 $2></$1')
The same, in Java.
String becomes = "<iframe src=\"http://example.com/thing\"/>".replaceFirst("<(\\w*) (.*)\\/", "<$1 $2></$1");
Ok guys. I found a workaround. I hooked the output method to xml where this html comes from and the XSLT engine takes care of closing those open tags for me. Thanks for answers, but if you happen to have a solution for the problem pls, leave your answer and I will mark it as an answer. This could be useful for others.
String resultHtml = inputHtml.replaceAll("(?six)<(\\w+)([^<]*?)/>", "<$1$2></$1>");
and this will properly handle tags that are not terminated like <hr> and <img>