Whilst working on our coursework for Computer Science, we have had to change from Java to JavaScript in HTML due to a server in-capability. Therefore, I have spent all my research into Java and have a fully working computer program in Java but with this new problem, my whole project needs to be made into JavaScript (or better, HTML)... I have had a brief working with HTML & Dreamweaver so I know how the UI etc. but I need help making a Search Bar that has variables. Previously, it was coded as
(search bar here)
if search == example:
System.out.println("You have chosen example")
etc
but now we have had to convert everything to HTML and I have no clue on how to make the if statements in this new language...
Any help is welcomed!
In your case you need to consider Java Servlet technology.
You will need to have a servlet on the server (servlet-container), and an HTML page, with JavaScript code, that makes a GET request with parameters to this servlet.
Note, that you need to encode the search string, before passing it to the server.
This servlet receives request from the client (HTML page), does the search, and prints results to the output stream.
Your JavaScript code receives server response and modifies HTML page to show the search results.
To implement client/server interaction via asynchronous requests (AJAX) consider jQuery.
Here is an example, how to make a GET request to the server: https://api.jquery.com/jquery.get/
plain sample:
$.get( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
alert( "Load was performed." );
});
And there is an example, how to read GET request params in the servlet:
protected void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String param1 = request.getParameter("param1");
String param2 = request.getParameter("param2");
}
Related
I'm implementing an enterprise application with Java EE on Glassfish server. I need to my application to execute some logic to show the proper output for a specific subset of URLs.
Problem description:
My web pages folder has this structure:
Web Pages
Protected
- CorrectPage.xhtml
- A.xhtml
- B.xhtml
- Index.xhtml
I want the user to access the URL:
/Protected/CorrectPage.xhtml
But the user must not be able to access the following URLs:
/Protected/A.xhtml
/Protected/B.xhtml
When the URL /Protected/CorrectPage.xhtml is entered I want to execute some logic and depending on the outcome of this logic I want to show either A.xhtml, or B.xhtml, without any visible URL changes (redirects).
Solutions tried so far:
I thought about using a servlet mapped to /Protected/*.xhtml while leaving the Faces Servlet deal with any other URL in my application.
and having :
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if(*Requested URL is /Protected/CorrectPage.xhtml*) {
if(logic())
*Show A.xhtml*
else
*Show B.xhtml*
} else
*Show 404*
My issue is that I don't know how to implement the Show A.xhtml. I basically want to print to the client my xhtml page.
I also thought about solving this last issue by using the response PrintWriter.
PrintWriter pw = response.getWriter();
But than again this doesn't solve my issue since I don't know how to print the xhtml file while also having the evaluation of the expression language contained in it.
Conclusion
Any help is extremely appreciated. Even if that means changing something in the structure I proposed. Naturally if the creation of a servlet isn't the correct solution for my issues I will leave that track.
I'm interested only in the outcome the user will experience.
Thanks in advance
You may use request.getRequestDispatcher("/protected/page[A|B]").forward(request, response)
Ok, here is my problem. I am building the Ajax Web app & to make my webapp to be seen by Google spider, I need to use the url that contain hashbang "#!". For example, my url could be like this:
mydomain.com/#!getCustomer
mydomain.com/#!getOrder
....
These url look pretty ugly & beside Google adword does not allow # in the url so I can't advertise my url in Goolge.
Thus, I want that everytime user go to the above link, the system will change "#!" to "d/", so that users will see these:
mydomain.com/d/getCustomer
mydomain.com/d/getOrder
....
Note: even the url doesn't contain "#!", but the system still be able to let Google spider to index my website.
So, I use FilterServlet to do that:
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String fullURLQueryString = getFullURL(httpRequest);
System.out.println(fullURLQueryString); // test url
if ((fullURLQueryString != null) && (fullURLQueryString.contains("#!"))) {
fullURLQueryString=fullURLQueryString.replace("#!", "d/");
request.getRequestDispatcher(fullURLQueryString).forward(request, response);
}
}
However, the system does not recognize the part "#!" when capturing the fullURLQueryString
So the System.out.println(fullURLQueryString); only print out the mydomain.com & it ignores completely the part #!getCustomer or #!getOrder.
Did i do anything wrongly here?
Can you fix it?
You do not have to use #!, if your web application doesn't use client-side generated content. If your URLs do not currently contain #, this functionality is of no interest for your.
In typical scenario in which this is useful user goes to page: http://example.com/#page1.
The browser requests http://example.com/ (notice #page1 is not in the request). After the page is loaded, client side JavaScript examines the part after # and downloads additional content.
Google bots do not support JavaScript and cannot download any additional content. For them, every page http://example.com/#page1, http://example.com/#page2 ... looks the same.
To fix this, #! syntax was introduced. You can learn more about it here.
You cannot do this server-side because browsers never send the URL fragment (the # and everything after it) to the server. You can do this replacement only with client-side JavaScript:
if (location.href.match(/\/#!/)) {
location.replace(location.href.replace(/\/#!/, '/d/'));
}
You should be constructing your URLs with the URL class (not a String).
Here is the official Java 8 Documentation:
http://docs.oracle.com/javase/8/docs/api/java/net/URL.html
The problem is with your getFullURL() method. Instead you should use getRequestURL().
I'm building a Django App with allauth.
I have a page, with authentication required, where I put a Java applet. This applet do GET requests to other pages (of the same django project) which return Json objects.
The applet gets the CSRF token from the parent web page, using JSObject.
The problem is that I want to set ALL the pages with authentication control, but I cannot get the sessionid cookie from the parent web page of the applet, so it cannot do GET (and neither POST) to obtain (or save) data.
Maybe it is a simple way to obtain this, but I'm a newby, and I haven't found anything.
Ask freely if you need something.
Thank you.
EDIT:
Has I wrote downstairs, I found out that the sessionid cookie is marked as HTTPOnly, so the problem now is which is the most safe way to allow the applet to do POST and GET request.
For example it is possible to create a JS method in the page, which GET the data and pass it down to the applet?
Maybe in the same way I can do the POST?
EDIT:
I successfully get the data, using a jquery call from the page. The problem now is that the code throws an InvocationTargetException. I found out the position of the problem, but I don't know how to solve it.
Here is the Jquery code:
function getFloor() {
$.get(
"{% url ... %}",
function(data) {
var output = JSON.stringify(data);
document.mapGenerator.setFloor(output)
}
);}
And here there are the two functions of the applet.
The ** part is the origin of the problem.
public void setFloor(String input) {
Floor[] f = Floor.parse(input);
}
public static Floor[] parse(String input) {
**Gson gson = new Gson();**
Floor[] floors = gson.fromJson(input, Floor[].class);
return floors;
}
And HERE is the log that come out on my server, where you can see that the applet try to load the Gson's library from the server (instead from the applet)
"GET /buildings/generate/com/google/gson/Gson.class HTTP/1.1" 404 4126
Somebady can help me?
You can do something like this in your applet:
String cookies = JSObject.getWindow(this).eval("document.cookie").toString();
This will give you all the cookies for that page delimited by semicolons.
Well, I'm Trying to Make a Data Importing Module. From the module, the user choose the .txt File with Data and then click the upload button. I want to make a Textarea or textbox (My project is a Java EE WebApp) where the webapp shows the real-progress of the upload proccess with Descriptive Messages.
I'm thinking (And i've searched) about Multiple Ajax Requests, and, Multiple Ajax Responses with one Request (The last one is not valid, as i read), but, i'm confused about the usage of AJAX in this case. It is Valid the user hit "Upload", and then, i call an AJAX Request that returns the text with the progress of the actual registry imported?
I'm thinking to use:
jQuery 1.6.2
GSon (For ajax)
Any suggestion would be appreciated
I would recommend using JBoss RichFaces 'poll' mechanism for that, or just a simple jquery script on the client side:
Ajax Poll Example with RichFaces: http://richfaces-showcase.appspot.com/richfaces/component-sample.jsf?demo=poll&skin=blueSky
JQuery (loads of examples on the web):
http://net.tutsplus.com/tutorials/javascript-ajax/creating-a-dynamic-poll-with-jquery-and-php/
jQuery AJAX polling for JSON response, handling based on AJAX result or JSON content
How about using a iframe that handles the upload form? This way it would not require the browser to update (by AJAX calls) the contents of a page that "we're already leaving". The iframe could be styled so that it's indistinguisable from other content.
AJAX-calls to a some method that keeps an eye on to some progress-variable (lets say a double that indicates percentage) is perfectly valid. Below is a barebones pseudo-example.
!PSEUDO!
double progress = 0.0d
void upload(request, response) {
// updates progress real-time
}
void ajaxProgress(request, response) {
// set progress to response
}
You may want to consider all the traffic back and forth showing real time processing information of uploaded files.
I have abandoned my earlier quest to make the applet communicate directly with the database, even though users and webpages have said that it's possible. I am now trying to get my applet to pass information (String and boolean format) entered in textfields or indicated by checkboxes, and give this to the servlet, which then stores it appropriately in the database. I've got the applet front end - the GUI - built, and the servlet - database connection also built. The only problem is the link between the two, applet and servlet. How would one pass String data from an applet to a servlet?
Thanks,
Joseph G.
First up, you have to acknowledge that you can only communicate with the server from where your applet was downloaded from, that includes the port number, unless you want to mess around with permissions, applet signing and all that malarky. This also isn't just an Applet restriction, the same applies to Flash and JavaScript (though in the case of JavaScript there are tricks to get around it).
Using either the "getCodeBase()" or "getDocumentBase()" method on your Applet will get you a URL from which you can get the component parts required to build a new URL that will let you call a servlet.
Thus, your Applet must be being served from the same server that your servlet is hosted on.
e.g. if your Applet is in the following page:
http://www.example.com/myapplet.html
...it means you can make calls to any URL that starts with
http://www.example.com/
...relatively easily.
The following is a crude, untested, example showing how to call a Servlet. This assumes that this snippet of code is being called from within an instance of Applet.
URL codeBase = getCodeBase();
URL servletURL = new URL(codeBase.getProtocol(), codeBase.getHost(), codeBase.getPort(), "/myServlet");
// assumes protocol is http, could be https
HttpURLConnection conn = (HttpURLConnection)servletURL.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
PrintWriter out = new PrintWriter(conn.openOutputStream());
out.println("hello world");
out.close();
System.out.println(conn.getResponseCode());
Then in your servlet, you can get the text sent by overriding doPost() and reading the input stream from the request (no exception handling shown and only reads first line of input):
public void doPost(HttpServletRequest req, HttpServletResponse res) {
BufferedReader reader = req.getReader();
String line = reader.readLine();
System.out.println("servlet received text: " + line);
}
Of course, that's just one approach. You could also take your inputs and build up a query string like this (URLEncoding not shown):
String queryString = "inputa=" + view.getInputA() + "&inputb=" + view.getInputB();
and append that to your URL:
URL servletURL = new URL(codeBase.getProtocol(), codeBase.getHost(), codeBase.getPort(), "/myServlet?" + queryString);
However, it seems fairly common to build up some kind of string and stream it to the servlet instead these days.
A recommended format would be JSON as it's semi-structured, while being easy to read and there are plenty of (de)serializers around that should work in your Applet and in your servlet. This means you can have a nice object model for your data which you could share between your Applet and Servlet. Building up a query string of complex inputs can be a mind bender.
Likewise, you could actually use Java serialisation and stream binary to your Servlet which then uses Java serialisation to create the appropriate Java objects. However, if you stick to something like JSON, it'll mean your servlet is more open to re-use since Java serialisation has never been implemented outside of Java (that I am aware of).
Hm, I guess the applet and the servlet run in two separate Java processes. In that case you'll have to use some remoting technology, e.g. an http call to localhost. In fact, that is what servlets are mainly used and implemented for: Accept and process http requests.