date does not get printed : why is this so? - java

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).

Related

Adding Parameters to Hello World JSP page

I'm new to this so i'm sure there is a simple solution but the question I'm trying to answer is this "This page should display a simple hello world message. In addition, your JSP page should look for a parameter in the request (GET) named “user”. If the user parameter is present, it should read the name from the request and display a greeting to the user. If the parameter is not present, it should display a generic “Hello World” message"
So far what I have is this:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hello World - JSP tutorial</title>
</head>
<body>
<%= "Hello World!" %>
</body>
</html>
How would I go about adding the parameters?
Here it goes:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hello World - JSP tutorial</title>
</head>
<body>
<%
String user = request.getParameter("user");
response.getWriter().println(user == null ? ("Hello World") : ("Hello World " + user));
%>
</body>
</html>

ArrayList iterate inside jQuery

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

Reading a JSP variable from JavaScript

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.

how to use jquery autocomplete?

i am creating a web project using JSP, and is trying to implement a simple search for users from my database using jquery autocomplete, however i am having trouble understanding how it works. i have little to no knowledge on jquery and ajax just to let you know. i have done the following code and am stuck.
<%#page contentType="text/html" pageEncoding="UTF-8" import="ewa.dbConnect,ewa.sendEmail,ewa.pwGen,ewa.hashPw,java.sql.*" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/jquery.autocomplete.css" />
<script src="js/jquery.autocomplete.js"></script>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<input type="text" id="search" name="search"/>
<script>
$("#search").autocomplete("getdata.jsp");
</script>
</body>
</html>
getdata.jsp
<%#page contentType="text/html" pageEncoding="UTF-8" import="ewa.dbConnect,java.sql.*" %>
<%! dbConnect db = new dbConnect(); %>
<%
String query = request.getParameter("q");
db.connect();
Statement stmt = db.getConnection().createStatement();
ResultSet rs = stmt.executeQuery("SELECT username FROM created_accounts WHERE username LIKE "+query);
while(rs.next())
{
out.println(rs.getString("username"));
}
db.disconnect
%>
if i am not wrong i read from a website, the parameter q is default and is just there, however how do i display the data? how do i pass the values from getdata.jsp into the autocomplete?
You're calling the autocomplete script tag before jQuery has been included. So, not having jQuery to latch onto (as the jQuery object hasn't been defined), nothing from the jQuery autocomplete plugin will load.
You have
<script src="js/jquery.autocomplete.js"></script>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
It should be
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script src="js/jquery.autocomplete.js"></script>
Reverse the order, and the Firebug errors you mentioned should disappear; I'm not sure it'll solve everything, but nothing will work until that's resolved.
I don't see jQuery UI being included (that one provides the autocomplete functionality)
http://jqueryui.com/demos/autocomplete/
So you need to include jquery.ui.autocomplete.js
(Or are you using the plugin autocomplete? if so, move to the jquery UI version)
Could also be that the data from getdata.jsp is malformed for the use in autocomplete.
How you tried debugging the javascript in a browser such as chrome or in firefox(with firebug)
I usual give (for jquery UI autocomplete) a JSON formatted answer, while I see your answer loop give a CR delimited list.
In getdata.jsp instead of produce:
jim<cr>
jack>cr>
jhon<cr>
try to return:
[{label: 'jim', value: 'jim'}, {label:
'jack', value: 'jack'}, {label:
'jhon', value: 'jhon'}]

Closing open XML tags with regex

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>

Categories