I've searched for this but can't find anything.
Please correct my question if it's incorrect english.
This is my code:
EDIT: The code is within my .jsp file!
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Beoordeling', 'Stage Opleider', 'Student'],
['1', '1', '4'],
<% ArrayList < Stelling > alleStellingenLijst2 = new ArrayList < Stelling > ();
alleStellingenLijst2 = (ArrayList < Stelling > ) request.getAttribute("stellingen");
for (Stelling s: alleStellingenLijst2) {
out.println("['1', '" + s.getDeStelling() + "' , '" + s.getDeWaarde() + "'],");
} %> ]);
var options = {
title: 'Laatste competenties',
hAxis: {
title: 'Score',
titleTextStyle: {
color: 'green'
}
},
vAxis: {
title: 'Beoordeling nummer',
titleTextStyle: {
color: 'green'
}
},
// Allow multiple simultaneous selections.
selectionMode: 'multiple',
colors: ['#BEF781', 'green']
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
For some reason, it wont execute the code between the <% %> (from the jsp).
This page online: http://project-omega.appspot.com/grafieken.jsp
The google app engine logs say the error is on the last line of my page. It's a nullpointerexception.
I have no idea what it means and I really hope someone can help me.
Thanks a lot and sorry for my english.
EDIT
The rendered output looks as follows
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Beoordeling', 'Stage Opleider', 'Student'],
for (Stelling s : alleStellingenLijst2) {
out.println("['1', '" + s.getDeStelling() + "' , '" + s.getDeWaarde() + "'],");
}
]);
NEW CODE:
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Beoordeling', 'Stage Opleider', 'Student'],
['1', 1, 4],
<%
ArrayList<Stelling> alleStellingenLijst2 =(ArrayList<Stelling>) getServletContext().getAttribute("stellingen");
for (Stelling s : alleStellingenLijst2) {
out.println("['1', " + s.getDeStelling() + " , " + s.getDeWaarde() + "],");
}
%>
['2', 2, 2]
]);
These are JSP markups, you cannot use them in JavaScript!
That's because JSP files are compiled to the .java classes during compilation, and JavaScript is executed on the client side.
You could do the opposite - generate a JavaScript code in the JSP file, that way you could pass some data you want to the JS variables.
I suppose you haven't set the stellingen request attribute.
You usually set the request attributes in a servlet, before forwarding the request to jsp:
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
ArrayList<Stelling> list = ...;
req.setAttribute("stellingen", list);
req.getRequestDispatcher("/grafieken.jsp").forward(req, resp);
}
Also make sure the attribute is set in the JSP code:
<%
List<Stelling> stellingen = (List<Stelling>) getServletContext().getAttribute("stellingen");
if(stellingen == null) {
out.println("stellingen attribute not set!");
}else{
for (Stelling s : stellingen) {
out.println("['1', " + s.getDeStelling() + " , " + s.getDeWaarde() + "],");
}
}
%>
Related
I am trying to send a transaction through the Java driver in my spring application.
The following is the simplified code.
#Test
public void rawTransactionTest(){
var appContext = new AnnotationConfigApplicationContext(DataLoaderApplication.class);
var arangoOperations = appContext.getBean(ArangoOperations.class);
String action = "function(){\n" +
" db = require(\"#arangodb\").db; \n" +
"db._query(\"LET doc = {title: \\\"Hello\\\"} "+
"UPSERT { _key: doc._key } INSERT doc._key == null ? UNSET(doc, \\\"_key\\\") : doc " +
"REPLACE doc IN Books OPTIONS { ignoreRevs: false } RETURN NEW\");\n" +
"return \"Success\"; \n" +
"}";
System.out.println(action);
var tOpts = new TransactionOptions();
tOpts.writeCollections("Books");
tOpts.waitForSync(true);
var result = arangoOperations.driver().db().transaction(action, String.class, tOpts);
System.out.println("Commit");
}
This returns the return value "Success" in the variable result. But the database remains unchanged. Doing the same thing in ArangoShell works perfectly fine. The ArangoShell code is as follows -
db._executeTransaction({
collections: {
write: ["Books"]
},
action: function(){
db = require("#arangodb").db;
db._query("LET doc = {title: \"Hello\"} UPSERT { _key: doc._key } "+
"INSERT doc._key == null ? UNSET(doc, \"_key\") : doc REPLACE doc"+
" IN Books OPTIONS { ignoreRevs: false } RETURN NEW");
return "Success";
}
});
This code works fine from the shell. Other non-transaction queries work fine from he same Spring-container.
What might be the problem?
The .db() only points to the _system database. Had to pass the database name to fix it.
I am trying to store some data in a arraylist in each users session however when I try and grab the list it is apparently null...
Code:
<%
List<String> attacks = new ArrayList<>();
if (request.getSession().getAttribute("attackList") != null){
attacks = (List<String>) request.getAttribute("attackList");
int x = 1;
for (String attack : attacks){
String[] attacc = attack.split(":");
out.print("" +
"<tr>\n" +
" <th scope=\"row\">"+x+"</th>\n" +
" <td>"+attacc[0]+"</td>\n" +
" <td>"+attacc[1]+"</td>\n" +
" <td>"+attacc[2]+"</td>\n" +
" <td>"+attacc[3]+"</td>\n" +
" </tr>");
x++;
}
}else{
out.print("empty");
}
%>
That ^ is the code I am using to fetch the data, it is printing "empty", so its essentially null...
How I am adding the data:
if (request.getAttribute("attackList") != null) {
attacks = (List<String>) request.getAttribute("attackList");
request.removeAttribute("attackList");
}
attacks.add("data here");
request.setAttribute("attackList", attacks);
I have not tried anything due to me not knowing what to try here.
First, I suggest you, if it is possible, you can start working with expression language, instead of jsp directly, because turn your code more readable.
Look your problem, do you want to work with a List in a Request our a Session scope?
I ask because sometimes you get your list from request scope but your IF is verifying the Session.
And at no time are you adding your list to the session.
You could do this, after your logic, with:
request.getSession().setAttribute("attackList", attacks);
Here is more about session methods:
https://beginnersbook.com/2013/11/jsp-implicit-object-session-with-examples/
I've read a lot about the same question, I tried to follow the answers but it never work.
I have a servlet name: get_import.java
I have a jsp name: import.jsp
First, in processRequest(), i initiated a String s = "abcdef", then i wrote:
s=request.setAttribute("validate", s);
RequestDispatcher rd = getServletContext().getRequestDispatcher("import.jsp");
rd.forward(request,response);
Then, in import.jsp, i wrote:
<% String st = (String)request.getAttribute("validate");
out.println("<h1>Result: " +st+ "</h1>");
%>
Then output was: Result: null
I can't explain why the variable's value is null in jsp, please help me to solve this problem or find other way out. Thanks a lot!!
You have a number of options:
1.Store it in the session.
String username = request.getParameter("username");
if (username != null && username.length() > 0)
{
session.setAttribute("username", username);
}
2.Store it as a hidden field in the form.
<input name="filter" type="hidden" value=""/>
3.Store it in a cookie.
username = getCookie(userCookieName);
// Get from cookie.
function getCookie(name) {
if (document.cookie) {
index = document.cookie.indexOf(name);
if (index !== -1) {
f = (document.cookie.indexOf("=", index) + 1);
t = document.cookie.indexOf(";", index);
if (t === -1) {
t = document.cookie.length;
}
return(document.cookie.substring(f, t));
}
}
return ("");
}
4.Not really another option but a mechanism - pass it in the URL:
.... onclick="window.location = 'details.jsp?filter=...'
try storing the value in session like this way
session.setAttribute("validate", s);
Then, in import.jsp, :
<% String st = (String)session.getAttribute("validate");
out.println("<h1>Result: " +st+ "</h1>");
%>
One side note try avoiding writing java in jsp pages.Best alternate is JSTL/EL
I am trying to fetch page content with phantomjs. In many examples on the official site (eg.: https://github.com/ariya/phantomjs/blob/master/examples/imagebin.js) the function page.open() is used.
In my script though it does not seem to work. I used reflection to look at all defined methods of the page object:
for ( var prop in page) {
if (typeof page[prop] == 'function') {
log("method in page: " + prop);
}
}
and the open() method did not show up. (close(), render(), etc... did show up)
also when I am trying to execute a script:
// include plugins
var system = require('system');
var fileSystem = require('fs');
var page = require('webpage').create();
// global errorhandler
phantom.onError = function(msg, trace) {
console.log("ERROR!!!!! \n" + msg);
phantom.exit(1);
};
// read json input and remove single outer quotes if set
var jsonin = system.args[1];
if (jsonin.charAt(0) == "'") {
jsonin = jsonin.substr(1, jsonin.length - 2);
}
// make object of json
var data = eval('(' + jsonin + ')');
// optional url
var url = system.args[2];
// transfer file
var dest = system.args[3];
console.log("systemargs[1]: data -> " + data);
console.log("systemargs[2]: url -> " + url);
console.log("systemargs[3]: dest -> " + dest);
openRoot();
/*
* open site
*/
function openRoot() {
page.onConsoleMessage = function(msg) {
console.log('INNER ' + msg);
};
page.open(url, function(status) {
if (status === "success") {
if (loadCount == 0) { // only initial open
console.log("opened successfully.");
page.injectJs("./jquery-1.8.3.min.js");
} else {
console.log("page open error.");
console.log('skip refresh ' + loadCount);
}
} else {
console.log("error opening: " + status);
}
});
}
phantom.exit(0);
it does not execute the open function. The log does not show any messages inside the open() method.
Any advice on what I might do wrong would be greatly appreciated. If there is additional information required, please let me know.
Regards,
Alex
Edit:
The line
console.log(typeof (page.open));
outputs: function which is not what I expected, given the previous list of methods I wrote to the log, where open does not exist. Hmm.
After hours of senseless searching I found the mistake. Stupid me. At the end of the script I call phantom.exit() where I should not.
The working code includes an Interval which checks on an object, in my case content and a member of that content.isFinished. If I set this to true, then phantom.exit() gets called.
My bad, absolutely my fault.
Working code:
var url = system.args[2];
// transfer file
var dest = system.args[3];
content = new Object();
content.isFinished = false;
console.log("systemargs[1]: data -> " + data);
console.log("systemargs[2]: url -> " + url);
console.log("systemargs[3]: dest -> " + dest);
openRoot();
/*
* open site
*/
function openRoot() {
page.onConsoleMessage = function(msg) {
console.log('INNER ' + msg);
};
page.open(url, function(status) {
if (status === "success") {
if (loadCount == 0) { // only initial open
console.log("opened successfully.");
page.injectJs("./jquery-1.8.3.min.js");
// do stuff
content.isFinished = true;
} else {
console.log("page open error.");
console.log('skip refresh ' + loadCount);
content.isFinished = true
}
} else {
console.log("error opening: " + status);
}
});
}
/*
* wait for completion
*/
var interval = setInterval(function() {
if (content.isFinished) {
page.close();
f = fileSystem.open(dest, "w");
f.writeLine(out);
f.close();
// exit phantom
phantom.exit();
} else {
console.log('not finished - wait.');
}
}, 5000);
Regards,
Alex
I am sorry to ask this but i've been working on this for hours and I can't figure it out on my own.
I have to use json for part of a project and I was able to get it to work but now it's not returning it back to the right jsp but instead just displaying the json jsp. I am pretty sure it is how I am receiving the json.
here are screen shots of what is happening:
this is the jsp that I need to use ajax on, I am wanting to populate the second dropdown using ajax:
this is what is happening instead, (it's the right data):
here is the code(sorry it's long):
-the jsp I am doing ajax on
<script type="text/javascript">
/**
* Utility function to create the Ajax request object in a cross-browser way.
* The cool thing about this function is you can send the parameters in a two-dimensional
* array. It also lets you send the name of the function to call when the response
* comes back.
*
* This is a generalized function you can copy directly into your code. *
*/
function doAjax(responseFunc, url, parameters) {
// create the AJAX object
var xmlHttp = undefined;
if (window.ActiveXObject){
try {
xmlHttp = new ActiveXObject("MSXML2.XMLHTTP");
} catch (othermicrosoft){
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {}
}
}
if (xmlHttp == undefined && window.XMLHttpRequest) {
// If IE7+, Mozilla, Safari, etc: Use native object
xmlHttp = new XMLHttpRequest();
}
if (xmlHttp != undefined) {
// open the connections
xmlHttp.open("POST", url, true);
// callback handler
xmlHttp.onreadystatechange = function() {
// test if the response is finished coming down
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
// create a JS object out of the response text
var obj = eval("(" + xmlHttp.responseText + ")");
// call the response function
responseFunc(obj);
}
}
// create the parameter string
// iterate the parameters array
var parameterString = "";
for (var i = 0; i < parameters.length; i++) {
parameterString += (i > 0 ? "&" : "") + parameters[i][0] + "=" + encodeURI(parameters[i][1]);
}
// set the necessary request headers
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", parameterString.length);
xmlHttp.setRequestHeader("Connection", "close");
// send the parameters
xmlHttp.send(parameterString);
}
}//doAjax
/**
* Submits the guess to the server. This is the event code, very much
* like an actionPerformed in Java.
*/
function getSeats() {
// this is how you get a reference to any part of the page
var packInput = document.getElementById("pack");
var pack = packInput.value;
// while (packInput.childNodes.length > 0) { // clear it out
// aSeats.removeChild(aSeats.childNodes[0]);
// }
// an example of how to do an alert (use these for debugging)
// I've just got this here so that we know the event was triggered
//alert("You guessed " + seat);
// send to the server (this is relative to our current page)
// THIS IS THE EXAMPLE OF HOW TO CALL AJAX
doAjax(receiveAnswer, "ttp.actions.Sale3PackAction.action",
[["pack", pack]]);
// change the history div color, just 'cause we can
// var randhex = (Math.round(0xFFFFFF * Math.random()).toString(16) + "000000").replace(/([a-f0-9]{6}).+/, "#$1").toUpperCase();
// document.getElementById("history").style.background = randhex;
}
/**
* Receives the response from the server. Our doAjax() function above
* turns the response text into a Javascript object, which it sends as the
* single parameter to this method.
*/
function receiveAnswer(response) {
// show the response pack. For this one, I'll use the innerHTML property,
// which simply replaces all HTML under a tag. This is the lazy way to do
// it, and I personally don't use it. But it's really popular and you are
// welcome to use it. Just know your shame if you do it...
var messageDiv = document.getElementById("aSeats");
messageDiv.innerHTML = response.aSeats;
// replace our history by modifying the dom -- this is the right way
// for simplicity, I'm just erasing the list and then repopulating it
var aSeats = document.getElementById("aSeats");
while (aSeats.childNodes.length > 0) { // clear it out
aSeats.removeChild(aSeats.childNodes[0]);
}
for (var i = 0; i < response.history.length; i++) { // add the items back in
var option = aSeats.appendChild(document.createElement("option"));
option.appendChild(document.createTextNode(response.history[i]));
}
// reset the input box
//document.getElementById("pack").value = "";
}
</script>
<% Venue v = (Venue)session.getAttribute("currentVenue"); %>
<% List<Conceptual_Package> cpList = Conceptual_PackageDAO.getInstance().getByVenue(v.getId()); %>
What Packages do you want to see?
<form method="post" action="ttp.actions.Sale3PackAction.action">
<select name="packid" id="pack">
<% for (Conceptual_Package cp: cpList) { %>
<option value="<%=cp.getId()%>"><%=cp.getName1()%></option>
<% } %>
</select>
<input type="submit" value=" next " onclick="getSeats();"/>
</form>
<!--new-->
Available Seats:
<select name="eventSeatid" id="aSeats">
<option value="aSeats"></option>
</select>
<input type="button" value=" Add "/>
Selected Seats:
<form method="post" action="ttp.actions.sale4Action.action">
<select name="eventSeat2id" size="10" id="seat2">
<option value="seat2"></option>
</select>
</form>
<jsp:include page="/footer.jsp"/>
-the json jsp
<%#page contentType="text/plain" pageEncoding="UTF-8"%>
<jsp:directive.page import="java.util.*"/>
{
"history": [
<% for (String newSeats: (List<String>)session.getAttribute("newSeats")) { %>
"<%=newSeats%>",
<% } %>
]
}
-the action class
public class Sale3PackAction implements Action{
public String process(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
String packid = request.getParameter("packid");
System.out.println("packid is: " + packid);
Conceptual_Package cp = Conceptual_PackageDAO.getInstance().read(packid);
request.setAttribute("cp", cp);
List<Physical_Package> ppList = Physical_PackageDAO.getInstance().getByConceptual_Package(cp.getId());
request.setAttribute("currentPack", ppList);
session.setAttribute("aSeats", null);
//return "sale3Pack_ajax.jsp";
//new
//HttpSession session = request.getSession();
// ensure we have a history
for (Physical_Package pPack: ppList){
try {
if (session.getAttribute("aSeats") == null) {
LinkedList aSeatsList = new LinkedList<String>();
session.setAttribute("aSeats", aSeatsList);
aSeatsList.add("Sec: " + pPack.getVenueSeat().getRowInVenue().getSectionInVenue().getSectionNumber() + " Row: " + pPack.getVenueSeat().getRowInVenue().getRowNumber() + " Seat: " + pPack.getVenueSeat().getSeatNumber());
session.setAttribute("newSeats", aSeatsList);
} else {
LinkedList aSeatsList = (LinkedList) session.getAttribute("aSeats");
aSeatsList.add("Sec: " + pPack.getVenueSeat().getRowInVenue().getSectionInVenue().getSectionNumber() + " Row: " + pPack.getVenueSeat().getRowInVenue().getRowNumber() + " Seat: " + pPack.getVenueSeat().getSeatNumber());
session.setAttribute("newSeats", aSeatsList);
}
} catch (DataException ex) {
Logger.getLogger(Sale3PackAction.class.getName()).log(Level.SEVERE, null, ex);
}
}
// next jsp page to go to
return "AjaxPack_json.jsp";
}
}
Hehe, I think we've all been in your place. Spending hours on something just to eventually realize that we overlooked some simple detail.
Read comments for more information...