I have a request object that probably belons to this class: https://tomcat.apache.org/tomcat-6.0-doc/api/org/apache/catalina/connector/RequestFacade.html
I am trying to print the names of the attributes and their values. This is my futile attempt.
Enumeration rns = request.getAttributeNames();
while (rns.hasMoreElements()) {
Object param = rns.nextElement();
out.println("\nattribute name: " + param.toString());
out.println("attribute value: " + request.getAttribute(param.toString()));
}
What I am missing? In another language there is a trivial answer to such question. How different it is done in java?
Rails: How do I print the request parameters?
my hardcoded attempt
Enumeration rns = request.getAttributeNames();
while (rns.hasMoreElements()) {
out.println("\nattribute name: " + rns.nextElement() );
}
// i have copied the logs output from above and edited it to create the array below
String[] madAttrs = { "dayToGraph",
"yearFromGraph",
"yaxis",
"yearToGraph",
"monthToGraph",
"monthFromGraph",
"currentMachine",
"onlyGraph",
"currentSample",
"currentAnalyte",
"dayFromGraph",
"analyteid"};
// then I got what I want.
for (String an : madAttrs) {
out.println("sttribute " + an);
out.println("the value is: "+ request.getAttribute(an));
}
But how do I do it without hardcoding the attributes in the array?
Not the answer you want, but the real answer to your question
Leave the 1990s in the past and stop putting java code in JSP files.
Instead receive the message in a servlet (or Spring handler) and do java work therein.
Next create the display values and put them in some context (perhaps the response) and dispatch the request to your JSP page.
Don't do this
If you refuse to do the above,
import the required classes into your JSP file.
I will not include the syntax for importing files into a JSP file,
but be assured,
Google has fewer compunctions about such things than do I.
Related
I am trying to create a NetCDF file using java (unidata library). One of the requirements is to include the _FillValue attribute in all the Variables. I have one of type CHAR, and I can not do it.
The Attribute constructor only accepts Strings or numbers (or arrays of them), not chars. I have tried both of them anyway but the final netcdf does not show the attribute.
Other languages let you do it (we have seen this working in matlab), but I don't know how to do it using java.
I see in the documentation that the _FillValue should be of the same type of the Variable itself but Attribute values does not accept Chars, only String or Numbers
For example: When I try
Nc4Chunking chunker = Nc4ChunkingStrategy.factory(Nc4Chunking.Strategy.standard, 6, true);
NetcdfFileWriter dataFile = NetcdfFileWriter.createNew(NetcdfFileWriter.Version.netcdf4_classic, fileName, chunker);
....
Variable varid_scdr = dataFile.addVariable(null, "SCDR", DataType.CHAR, dimsTMS15);
varid_scdr.addAttribute(new Attribute("_FillValue", " "));
....
dataFile.write(varid_scdr, scodData);
dataFile.close();
The resulting netcdf file has no _FillValue, it is not written in the file.
But if I change the attribute name and do this
varid_scdr.addAttribute(new Attribute("FillValue", " "));
the parameter is present in the output file
I have no problems with other data types or other attribute names. I am prety sure that the problem is about the attribute _FillValue for the variable of type Char. I dont know how to write it and I need the _FillValue attribute to be explicity present in the variable attribute list.
********* 5th July 2019 ***********
I realized that the problem is only related to netcdf4 and netcdf4_classic files. So perhaps is about chunking or something like that. If I try it creating netcdf3 files it workis.
Any help about this issue? what am I missing?
I think this is due to bug that has been addressed in the latest version of netcdf-java (v5.0.0). v5.0.0 has been released and is available for download; my hope is that the announcement will go out today.
If you want to be explicit about writing a CHAR valued attribute, one way to to it would be:
String fillValue = " ";
Array charArrayFillValue = ArrayChar.makeFromString(fillValue, 1);
charAttrFillValue = new Attribute("_FillValue", charArrayFillValue);
varid_scdr.addAttribute(charAttrFillValue)
another way would be:
String fillValue = " ";
Array charArrayFillValue = ArrayChar.makeFromString(fillValue, 1);
charAttrFillValue = new Attribute("_FillValue", DataType.CHAR);
charAttrFillValue.setValues(charArrayFillValue);
varid_scdr.addAttribute(charAttrFillValue)
Both of those are a bit verbose, though. I just checked using version 5, and your one liner works:
varid_scdr.addAttribute(new Attribute("_FillValue", " "));
However, if you try to pass in a value for _FillValue that isn't a string of length 1, the netCDF-C library will throw an error. So this:
varid_scdr.addAttribute(new Attribute("_FillValue", "ab"));
will result in:
-36 (NetCDF: Invalid argument) on attribute ':_FillValue = "ab"' on var varid_scdr
netCDF-Java will make sure the string you pass in gets converted to CHARs, but it won't truncate the resulting set of CHARs to fit into the single character limit on the _FillValue attribute.
I am getting stuck in a basic JSP Operation. I want to a new line so i have added \n in the end but it throws me an exception. If i remove \n everything works fine
Exception
java.lang.IllegalArgumentException: Invalid LF not followed by whitespace
Class File
StringBuilder junitLog = new StringBuilder();
junitLog.append("The class that is being executed : " + description.getClassName() +"\n");
junitLog.append("Number of testcases to execute : " + description.testCount()+"\n");
/**
* #return the junitLog
*/
public StringBuilder getJunitLog() {
return junitLog;
}
/**
* #param junitLog the junitLog to set
*/
public void setJunitLog(StringBuilder junitLog) {
this.junitLog = junitLog;
}
JSP:-
response.setHeader("finalJUNITReport",""+ junitListener.getJunitLog());
try Base64 encoding them before you set in headers and Base64 decoding them when you want to read them back.
As long as you think to it in the OO way, you can wonder why you couldn't put new line in your headers.
But as soon as you think that it will be transmitted using HTTP protocol, it becomes evident : a HTTP message (request or response) is nothing else than a sequential serie of bytes. For HTTP, the header section comes first and is composed of lines like that :
HEADER_NAME: header value
If you put a new line in a header value, anything that would follow would be considered as a new header. And if you put 2 consecutive new lines that would denote the end of the header section.
All you can do is to use "\n ", because a line beginning with a space if supposed to be a continuation line.
That's the reason of the error message Invalid LF not followed by whitespace, and hopefully it was there, because you would have send an incorrect header section what could be harder to detect ...
I howeva suceeded in my requirement. :)
As clearly stated by Serge Ballesta.
If you put a new line in a header value, anything that would follow would be considered as a new header..
So below is the logic i applied based on my requirement.
Below were my code changes:
junitLog.append("The class that is being executed : " + description.getClassName() +"?");
junitLog.append("Number of testcases to execute : " + description.testCount()+"?");
I added a question mark at the end of the string. THe string became something as mentioned below.
The class that is being executed : testCreateHaulier? Number of testcases to execute : 39?
I passed the String from JSP using response.setHeader Code as below:
response.setHeader("finalJUNITReport",""+ junitListener.getJunitLog());
and in my java class file i did something like this:
junitReportString=yc.getHeaderField("finalJUNITReport").toString();
System.out.println(junitReportString);
junitReportString=junitReportString.replaceAll("\\?", "\n");
System.out.println("Report Details ==============>"+junitReportString);
Using replaceAll i replaced all question marks to new line and my requirement was done.
Hope it helps others too.:)
I'm trying to send an email using a javascript code in a Java project. Database connection works fine, I already tested it. I got the error:
javax.script.ScriptException: sun.org.mozilla.javascript.internal.EvaluatorException: missing ) after formal parameters (#1) in at line number 1
The only information of relevance is not readily reported: the final JavaScript string executed. Make sure to look at relevant data when debugging. After inspecting the final string it will be apparent why it is incorrect and trivial to "fix".
Hint: it will look something like function sendMail(userblah, foo#bar.qux) { .., which is indeed invalid JavaScript.
The problem and solution should be self-evident from that - use fixed parameters (variable names) in the function declaration and supply arguments (values) via the invokeFunction call.
Solution:
// The following parameter names are JAVASCRIPT variable names.
String script = "function sendMail(username, email, body) { ..";
// And pass correct arguments (values), in order. The variables used
// here are JAVA variables, and align by-position with the JS parameters.
inv.invokeFunction("sendMail", username, email, "EMAIL SENT!!!!");
In addition, the getElementById (invalid ID) is wrong, the body parameter is never used, and encodeURIComponent should be used (instead of escape).
Not sure if this is a typo or not:
result = request.executeQuery("SELECT user.login, user.email "
+ "FROM user " + );
It looks like you are missing the end of your statement.
Hmmmm, your function definition:
function sendMail("username","email") {...}
doesn't look like valid JavaScript to me, apart of that, you never call the function.
Pseudocode, how to do it:
function sendMail(username, email) {
var link = "jadajada" + email; // .... etc
}
sendMail("+username+","+email+");
So this question suggested using a servlet to do the file check before doing the include:
How can you check if a file exists before including/importing it in JSP?
So I wrote a servlet that does that. I call it using something like
<jsp:include page='<%= "/servlet/fileChecker?section=THX&file=1138" &>'></jsp:include>
but the output of that servlet call contains a jsp:include tag, to the file I was checking for. Unfortunately, the browser doesn't "include" it. I'm getting errors like "there is no attribute 'page'" and "element 'jsp:include' undefined" -- which suggests the servlet output is not being rendered as Java but as HTML.
Here is the output:
<p>Text before the servlet call</p>
<p><h4>From THX1138</h4><jsp:include page='thx/results_1138.jsp'></jsp:include></p>
<p>Text after the servlet call</p>
Here is the main call of my servlet:
private String FileChecker(String section, String file) {
String result = ""; // assume file does not exist
String pathToCheck = section + "/results_" + file + ".jsp";
// realPath is defined in the init() method as config.getServletContext().getRealPath("/");
File fileToCheck = new File(realPath + pathToCheck);
if (fileToCheck.exists()) {
result = "<p><h4>" + section + "</h4><jsp:include page='" + pathToCheck + "'></jsp:include></p>";
}
return result;
}
I feel like the answer is close, but I'm not sure what curtain I should be looking behind. Any help?
Do not write a string with a bunch of HTML and JSP tags to the response. This makes no sense. The webbrowser does not understand JSP tags.
Call RequestDispatcher#include() instead.
request.getRequestDispatcher(checkedJspPath).include(request, response);
And move that HTML back into the JSP.
Unrelated to the concrete question, I know that you're referring to an old answer of me, but I realize that it's actually better to check if ServletContext#getResource() doesn't return null instead of using File#exists(). This way it'll work as well whenever the WAR is not expanded.
I am working with a java generated dynamic webpage, and I'm printing links from a query to a JDO. But I don't understand how can I get and use the parameter from the url.
My html objects are printed like this
print = print + "Nome:<a href='displayFotos?album="+results.get(i).nome+ "'>"+
results.get(i).nome+ "</a></br>";
The results in having for example:
Nome:<a href='displayFotos?album=album1'>album1</a>
So, in my head when clicked it should be calling the address of the dynamic webpage album like this and should get the parameter. In this case it would be the album1.
else if (address.indexOf("/dinamicas/album") != -1) {
String album = param1;
System.out.println("did it work? "+album);
}
And I have in the beginning of the class a general parameter that I use to get text from html forms.
String param1 = req.getParameter("param1");
I understand this might be an easy question but I'm not getting there by myself.
Nome:<a href='displayFotos?album=album1'>album1</a>
Here, you're using a parameter name of album.
However, you're attempting to get it by a parameter name of param1. This does obviously not match.
String param1 = req.getParameter("param1");
You need to use the same parameter name as is been definied in the request.
String album = req.getParameter("album");
// ...