I have my JSP that controls the frame behavior of my page as the following:
<%
print_header();
String especialidade = request.getParameter("especialidade");
String medico = request.getParameter("medico");
String paciente = request.getParameter("paciente");
String data_consulta = request.getParameter("data_consulta");
String convenio = request.getParameter("convenio");
if (especialidade == null) {
print_especialidade_form();
} else if(paciente == null) {
print_agendamento_form();
}
print_footer();
%>
I have the definition of the functions defined in the same JSP, delimited by <%! and %> tags, but the creation of the form, that happens inside of those functions, get executed even if the function isn't called like print_footer(); for instance.
I 'm used to programming in ASP and I could easily do these there, but I'm having a hard time migrating to JSP. What am I doing wrong?
Related
I want to change the table from the page /manager/html/sessions of Tomcat.
The jsp file for that page is tomcatpath/webapps/manager/WEB-INF/jsp/sessionsList.jsp
I want to add a new column in table which contains the path of last page which client has requested.
Ex: if the last request of client is mydom.com/path/3, I want to show in table /path/3
This is the part where are iterated all sessions
<%
for (Session currentSession : activeSessions) {
String currentSessionId = JspHelper.escapeXml(currentSession.getId());
String type;
if (currentSession instanceof DeltaSession) {
if (((DeltaSession) currentSession).isPrimarySession()) {
type = "Primary";
} else {
type = "Backup";
}
} else if (currentSession instanceof DummyProxySession) {
type = "Proxy";
} else {
type = "Primary";
}
//I have problem getting the last accessed path by client.
String lastPath = ...;
%>
//html where is printed every row with data from session
//use here <%= lastPath %>
<%
} //end of for
%>
I don't know how to extract the last accessed path.
Tomcat version: Apache Tomcat/9.0.20
I've been looking for a solution to this for awhile. Working on a small side project to play around mini search engines. I've created a series of java classes that crawl through a certain amount of links through a webpage and stores the information into a JDBM RecordManager HTree.
When I run a print function for the contents of this RecordManager, I can get the contents just fine, but when I try to imitate this on a JSP file on my Tomcat server, the object that is supposed to be returned by this print function is empty. (Note: I have a HTML page that sends the necessary string to this JSP file)
The DataManager object, when called, is supposed to "create and Initialize a RecordManager"
The querySimilarity function is supposed to return Vector of integer pageIDs taken from the generated RecordManager.
Any ideas? The code below is from my JSP file.
<%# page import="java.util.Vector,searchEngine.*,jdbc.*" %>
<%
out.println("The words you entered are: <br>");
String arr = request.getParameter("words");
String[] a = arr.split(" ");
Vector<Integer> pageIDList = new Vector<Integer>();
DataManager dm = new DataManager();
pageIDList = dm.querySimilarity(a);
for(int i = 0; i < pageIDList.size(); i++){
out.println(pageIDList.get(i) + "<br>");
}
%>
I need java code for this jsp line code.
I know how to make it for scope "page" or "application" but i really dont know how it works with "session"
<jsp:useBean id=”pera” class=”beans.User” scope=”sesion”>
This is Solution.
beans.User user = null;
synchronized (application) {
user = (beans.User) _jspx_page_context.getAttribute("user",
PageContext.APPLICATION_SCOPE);
if (user == null){
user = new beans.User();
_jspx_page_context.setAttribute("user", user,
PageContext.APPLICATION_SCOPE);
}
}
I'm trying to call a JavaScript-Method from within my JavaFX-WebView via:
JSObject win = (JSObject)getEngine().executeScript("window");
win.call("showPDF", myPDFFile /*typeof java.io.File*/);
the result of this call is:
Invalid parameter object: need either .data, .range or .url
This is the JavaScript-Part (not by me), which throws the error:
var source;
if (typeof src === 'string') {
source = { url: src };
} else if (isArrayBuffer(src)) {
source = { data: src };
} else if (src instanceof PDFDataRangeTransport) {
source = { range: src };
} else {
if (typeof src !== 'object') {
error('Invalid parameter in getDocument, need either Uint8Array, ' +
'string or a parameter object');
}
if (!src.url && !src.data && !src.range) {
error('Invalid parameter object: need either .data, .range or .url');
}
}
Implementation of isArrayBuffer:
function isArrayBuffer(v) {
return typeof v === 'object' && v !== null && v.byteLength !== undefined;
}
So my question is:
What type of (java) object could be used so that this call might work?
win.call("showPDF", ???);
EDIT 1:
String cannot be used, because it will be treated as a URL.
I would like to commit something like a ByteArray (my concrete file), but using a byte[] (instead of java.io.File) causes the same error.
Here are some comments from the JS function above:
https://github.com/mozilla/pdf.js/blob/master/src/display/api.js#L234
This is the main entry point for loading a PDF and interacting with it.
NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
is used, which means it must follow the same origin rules that any XHR does
e.g. No cross domain requests without CORS.
#param {string|TypedArray|DocumentInitParameters|PDFDataRangeTransport} src
Can be a url to where a PDF is located, a typed array (Uint8Array)
already populated with data or parameter object.
What Datatype i have to use (in JAVA), so it will be a (e.g) TypedArray (Uint8Array) in JAVASCRIPT?
EDIT 2:
I was trying Aarons suggestion:
String encoded = Base64.getEncoder().encodeToString(Files.readAllBytes(myPDFFile.toPath()));
engine.executeScript("var src = _base64ToArrayBuffer('"+encoded+"'); showPDF(src);");
This causes a new problem:
Error: Invalid PDF binary data: either typed array, string or array-like object is expected in the data property.
This (new) error is thrown (few lines later) here: https://github.com/mozilla/pdf.js/blob/master/src/display/api.js#L291
console.log(_base64ToArrayBuffer(encoded)) returns: [object ArrayBuffer]
Solution:
I managed to make this work (with help of Aaron):
pdfViewer.html
<!doctype html>
<html>
<head>
<script src="web/compatibility.js"></script>
<script src="build/pdf.js"></script>
<script>
function _base64ToBinaryString(base64) {
var binary_string = window.atob(base64);
return binary_string;
}
function showPDF(pdfFile) {
console.log('calling showPDF...');
'use strict';
PDFJS.disableWorker = true; /* IMPORTANT TO DISABLE! */
PDFJS.workerSrc = 'build/pdf.worker.js';
console.log('TRYING TO GET DOCUMENT FROM BINARY DATA...');
PDFJS.getDocument({data: pdfFile}).then(function(pdf)
{
console.log('PDF LOADED.');
console.log('TRYING TO GET PAGE 1...');
pdf.getPage(1).then(function(page) {
console.log('PAGE 1 LOADED.');
var scale = 1.0;
var viewport = page.getViewport(scale);
var canvas = document.getElementById('the-canvas');
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
var renderContext = {
canvasContext: context,
viewport: viewport
};
console.log('RENDERING PAGE 1...');
page.render(renderContext);
});
});
};
</script>
</head>
<body>
<canvas id="the-canvas" style="border:1px solid black;"/>
</body>
</html>
After loading the above HTML-Page into the WebView,
following Java-Code is used to load a PDF-File into the Page:
String encoded = Base64.getEncoder().encodeToString(Files.readAllBytes(myPdfFile.toPath()));
webEngine.executeScript("var src = _base64ToBinaryString('"+encoded+"'); showPDF(src);");
Try myPDFFile.getURI().getURL().toString() since the method accepts URLs in the form of Strings. Since WebKit is running locally, you should be able to read file:// URLs.
If you want to try the ArrayBuffer, then you can find some examples in the MDN JavaScript documentation at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
That means you need to create a FileReader, pass the URL, handle the asynchronous events. I only recommend this if you know JavaScript fairly well.
Unfortunately, the examples are all geared towards handling files in a web page, not passing data into a page.
[EDIT] Here is an example how to convert a Base64 encoded string to ArrayBuffer: Convert base64 string to ArrayBuffer
So you need the load the file into a Java byte[] array. Then convert the array to a Base64 encoded Java String. You can then paste this into dynamic JavaScript:
String encoded = ...byte[] -> Base64...
getEngine().executeScript("var src = _base64ToArrayBuffer('"+encoded+"'); showPDF(src);");
In my web application, I use the .load() function in JQuery, to load some JSP pages inside a DIV.
$("#myDiv").load("chat.jsp");
In chat.jsp, no Java codes is executed unless this client has Logged in, means, I check the session.
String sessionId = session.getAttribute("SessionId");
if(sessionId.equals("100")){
//execute codes
}else{
//redirect to log in page
}
Those java codes that will be executed, they will out.println(); some HTML elements.
I don't want the client to write /chat.jsp in the browser to access this page, as it will look bad, and the other stuff in the main page won't be there, and this could do a harm to the web app security.
How can I restrict someone from accessing chat.jsp directly, but yet keep it accessible via .load() ?
UPDATE:
JavaDB is a class that I made, it connects me to the Database.
This is chat.jsp
<body>
<%
String userId = session.getAttribute("SessionId").toString();
if (userId != null) {
String roomId = request.getParameter("roomId");
String lastMessageId = request.getParameter("lastMessageId");
JavaDB myJavaDB = new JavaDB();
myJavaDB.Connect("Chat", "chat", "chat");
Connection conn = myJavaDB.getMyConnection();
Statement stmt = conn.createStatement();
String lastId = "";
int fi = 0;
ResultSet rset = stmt.executeQuery("select message,message_id,first_name,last_name from users u,messages m where u.user_id=m.user_id and m.message_id>" + lastMessageId + " and room_id=" + roomId + " order by m.message_id asc");
while (rset.next()) {
fi = 1;
lastId = rset.getString(2);
%>
<div class="message">
<div class="messageSender">
<%=rset.getString(3) + " " + rset.getString(4)%>
</div>
<div class="messageContents">
<%=rset.getString(1)%>
</div>
</div>
<% }
%>
<div class="lastId">
<% if (fi == 1) {%>
<%=lastId%>
<% } else {%>
<%=lastMessageId%>
<% }%></div>
<% if (fi == 1) {%>
<div class="messages">
</div>
<% }
} else {
response.sendRedirect("index.jsp");
}%>
</body>
Guys I don't know what Filter means.
UPDATE
If I decided to send a parameter that tells me that this request came from Jquery.
.load("chat.jsp", { jquery : "yes" });
And then check it in chat.jsp
String yesOrNo = request.getParameter("jquery");
Then they can simply hack this by using this URL.
/chat.jsp?jquery=yes
or something like that..
UPDATE
I tried Maksim's advice, I got this when I tried to access chat.jsp.
Is this the desired effect?
In order to achieve this in my application I check for X-Requested-With field in http header the client sends to my page in its request. If its value is XMLHttpRequest, then it's very likely that it came from an ajax request (jQuery appends this header to its requests), otherwise I don't serve the page. Regular (direct) browser requests will leave this header field blank.
In ASP.Net it looks like this, you will have to change your code slightly for JSP:
if (Request.Headers["X-Requested-With"] != "XMLHttpRequest")
{
Response.Write("AJAX Request only.");
Response.End();
return;
}
UPD: After quick googling your code will probably be something like this
if(!request.getHeader("X-Requested-With").equals("XMLHttpRequest")){
out.println("AJAX Request only.");
out.flush();
out.close();
return;
}
UPD2: Looks like request.getHeader("X-Requested-With") returns null in your case change the condition to something like this:
String ajaxRequest = request.getHeader("X-Requested-With");
if(ajaxRequest == null || !ajaxRequest.equals("XMLHttpRequest")){
...
}
Is your code snippet a servlet? If that's so, use a security framework (such as Spring Security) or a javax.servlet.Filter for applying security, then you can apply security to JSPs too.
you should use Filter. Check session in filter code and redirect to login.
according to http://www.c-sharpcorner.com/blogs/2918/how-to-set-a-request-header-in-a-jquery-ajax-call.aspx
JQuery gives you the tools you need to create a request and retrieve a response through it's ajax library. The raw $.ajax call gives you all kinds of callbacks to manipulate http messages.
So you can add a custom request header in your Ajaxa call like this
$.ajax({
type:"POST",
beforeSend: function (request)
{
request.setRequestHeader("Authority", "AJAXREQUEST");
},
...........
And then in your servlet check to see if the request has the header Authority equals to AJAXREQUEST. This is how you read request headers http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Request-Headers.html