Java EE - Show page based on internal business logic - java

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)

Related

Search Variables in HTML from Java?

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");
}

How to change the URL that contains "#!" to "d/" in Java?

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

redirecting between java servlets from url containing #

Hey,
Maybe the title is not the best choice, but I really don't know how to better describe the problem.
The thing is when you point your browser to url that contains #
http://anydomain.com/test/elsem/1234#dogeatdog
and for some reason (ie. there is a business logic) you want to redirect to other page
http://anydomain.com/test/els/1234
the #dogeatdog will be added to new url.
I found this behavior while developing wicket app, but just now I tested it with simple pure java servlet. Can someone explain it to me?
Here is the code just in case I'm doing something wrong:
private void process(HttpServletRequest req, HttpServletResponse res)
{
res.setContentType("text/plain");
try
{
HttpSession session = req.getSession();
Object as = session.getAttribute("as");
if (as == null)
{
log.info("redirecting");
session.setAttribute("as", 1);
res.sendRedirect("/test/");
}
else
{
log.info("writing");
PrintWriter out = res.getWriter();
out.write("after redirect "+as);
out.flush();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
Hash fragments (#a_hash_fragment) never leave the browser, they are not part of HTTP request.
What the web server gets in this case is GET /test/elsem/1234, and it responds with redirect 3xx code and the new url /test/els/1234, which your browser picks and appends #dogeatdog. Makes sense now?
UPDATE: Thanks to Zack, here's a W3C document that exactly explains how this (should) work:
http://www.w3.org/Protocols/HTTP/Fragment/draft-bos-http-redirect-00.txt
From the sendRedirect Javadoc:
Sends a temporary redirect response to the client using the specified
redirect location URL. This method can accept relative URLs; the
servlet container must convert the relative URL to an absolute URL
before sending the response to the client. If the location is relative
without a leading '/' the container interprets it as relative to the
current request URI. If the location is relative with a leading '/'
the container interprets it as relative to the servlet container root.
Because of repetitive use of "relative" in the Javadoc, I suspect the new URL is using what it can from the old URL and then building from there...
In the brief amount of what I've read, forwarding should be used if possible instead of redirect.
See this for a good explanation of forward verses redirect.
See this for straight-forward examples of forwarding requests to Servlets or JSPs.
Of course, with forwarding, the original URL will remain intact so that may not be what you're looking for...
EDIT
With information from milan, I found some more information regarding URL fragments (the stuff after "#" - I didn't know that was their official name until corresponding with milan).
There's another SOF post that has some good information concerning this and possibly the best answer: URL Fragment and 302 redirects
I have "+1'd" milan for giving good direction on this...

Applet - Servlet Communication

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.

Can we somehow change the url in addressbar after dispatching request from servlet to jsp

I am having a weird problem here, and I am really stuck, need to get this work badly.
so i have a page say index.jsp with a link say "a href=servlet?id=10". when I click on this link it will go to doGet() on my servlet and here is the code in my servlet.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getParameter("id");
// search database and create an arraylist
if(//user logged in)
address = "s/results.jsp";
else
address = "results.jsp";
// set arraylist in session object
RequestDispatcher dispatcher = request.getRequestDispatcher(address);
dispatcher.forward(request,response);
}
So the above code works fine but after request forwarding, my browser shows the url as
http://localhost/project/servlet?id=10.
I don't want the above url as i am forwarding to two different jsp's based on the user login status one is in 's' folder and other is outside of that.
if user is logged in then i forward to 's/results.jsp' and if user is not logged in i am forwarding to 'results.jsp'.
in case of s/results.jsp i am accessing resources like images and scripts from outside of 's' folder by using ../ in the results.jsp.
as url is not changing to s/results.jsp , i am unable to access the resources with '../'
and as i am using jsp pagination , when i click next the url is changing to s/results.jsp
and in that case i am able to access resources using ../
one solution in my mind is to copy all resources in s folder , but that would increase
redundancy.
one other solution in my mind is to create two different servlets for two jsp's
but i don't know where to put the servlet so that it can access resources outside of s folder with ../
is their any other good way i can do the task..
I have tried to find information about this but haven't been able to figure it out.
Any help will be very much appreciated.
You have basically instructed your webbrowser to send a request to exactly that URL. The forward does not change the URL. It is entirely server side. Apart from using response.sendRedirect() instead -which would trash the current request, including all of its attributes, and create a brand new request on the given URL-, you could also just change your link to <a href="results?id=10">, or when the user is logged in, to <a href="s/results?id=10">.
<a href="${user.loggedin ? 's/' : ''}results?id=10">
Finally alter the servlet mapping accordingly so that it get invoked on those URLs.
<url-pattern>/results</url-pattern>
<url-pattern>/s/results</url-pattern>
You'll only miss the JSP extension. But JSPs which are to be used by a dispatcher belong in /WEB-INF folder anyway so that they cannot be viewed by the enduser directly without invoking the servlet first. You also end up with nicer URLs.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("id");
// search database and create an arraylist
if(//user logged in)
address = "s/results.jsp";
else
address = "results.jsp";
// set arraylist in session object
RequestDispatcher dispatcher = request.getRequestDispatcher(address);
dispatcher.forward(request,response);
}
in the above code instead of using request dispatcher,
RequestDispatcher dispatcher = request.getRequestDispatcher(address);
dispatcher.forward(request,response);
we can try with
response.sendRedirect(request.getContextPath()+"/address");

Categories

Resources