Get URL # hash with JSTL - java

To get the URL hash # in javascript you can just do:
window.location.hash
Is there a similar simple and easy way to do it in JSTL?
Example of a URL I have: http://hatsos.com/#somehashname
If there is not a built-in easy method, how would I go about getting the URL and then parsing the hash out of it?

The only way to get the hash fragment identifier in the server side is to let the client side send a HTTP request with the value as a request parameter whenever it has changed. For example, with Ajax during the window.onhashchange event. I see in your question history that you're familiar with jQuery. Here's a kickoff example:
window.onhashchange = function() {
$.get('someservlet', { 'hash', window.location.hash }, function(response) {
// ...
});
}
with
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String hash = request.getParameter("hash");
// ...
}
To cover lack of IE6/7 support for window.onhashchange, consider jQuery hashchange plugin.

You're talking about a URI Fragment id, and most user agents don't even send that to the server, so you can't really get it there. JavaScript can access it because it runs on the client side.

Related

I need to change the content of a web page without refreshing where the change happens in the server side

I have a web app with java that take requests from clients, process the request then send the result back to the client. I want to add a graphic interface that will show information about the request, the process and the result after the arrival of each request. I want to do this without having the page reloading, the server can receive a lot of requests in a short time so reloading the page is not a good solution. I've tried doing this with AJAX but the change is after an event provoked at the client side, for example a click on a button. I want the event to be on the server's side my event needs to be the arrival of a new request. tried using setInterval but the result is not what I expect, its like only one request get shown out of 10
this is the setInterval code :
setInterval(function() {
$.get("log", function(responseText) {
$("#container").append(responseText + "<br>");
});
}, 10);
log is the URL of the servlet that gives information about the request
the doGet methode of the log servlet :
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(requestInfo);
}
every time a request arrive I start putting information in requestInfo
If you want to constantly check the status, you have to recall your ajax function. If you want to be informed by push, you have to use websockets.
function checkLog(){
$.get("log", function(responseText) {
var $notFinished = true;
console.log('fetch from server')
$("#container").append(responseText + "<br>");
// do some checks to determine server has finished, set notFinished to false if it is your last ajax request
...
if($notFinished){
// recall the function in 10 seconds for status check
setInterval(function() {
checkLog();
}, 10000);
}
});
}
// call the function the first time
checkLog();

Is there any method for request object in servlets that can identify page reload event for the webpage

I need to detect the page reload event on the servlet. I was wondering if there is any method in request object that can help me to do so or if there is not.... is there any other way to do the same?
When you tap the "Reload" button in a browser, it specifically ignores the cache-control directives and requests a fresh copy. Therefore you can inspect the request headers and look for an absent If-Modified-Since header:
public void doGet( final HttpServletRequest request, final HttpServletResponse response ) throws ServletException, IOException
{
if ( isReloaded(request) ) handleReload( request, response );
else handleNormal( request, response );
}
boolean isReloaded( final HttpServletRequest request )
{
return request.getParameter("If-Modified-Since") == null;
}
/**
* You may need to modify this function or you may not need it at all.
* Let me know and I'll edit the solution.
*/
protected long getLastModified( final HttpServletRequest request )
{
return new Date().getTime();
}
If you're behind a proxy such as Apache mod_proxy,
you may also need to set ExpiresActive off in the Apache files.
Also there's no way to distinguish between the first time someone visits a page and the "Reload" button without the use of cookies.
Cache control directives don't come into play on doPost, so the same trick won't work for doPost.
If you have a small server with a limited number of URLs, you could consider setting a cookie for every URL. If the cookie is present it's a reload event. If it's absent, it's a first time visit. That would work for both doGet and doPost.
The negative is that it seems there's a maximum limit in most browsers on how many cookies you can set per domain. For Chrome, the limit seems to be 180 cookies per domain, and 4096 bytes per cookie.

how to append getRequestDispatcher with extra data in java?

So Basically I have:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/zips/packet.html").forward(request, response);
return;
}
As you can you can see when a request is made for this servlet, It responds with packet.html file. To be precise, inside my packet.html I have a video element with src="" which I need to fill it by users requested url.
Question: How do I send a little extra data saying video source to the client, So in my client side it could change the video source from src="" to src="actual video source"
I TRIED:
String video_source = "/zips/video.mp4";
response.getWriter().append(video_source);
request.getRequestDispatcher("/zips/packet.html").forward(request, response);
With this method I can see my packet.html being received in my front-end But I can't find the video_source. FYI: don't know how to receive the video_source.
Well, To satasify your demand you can follow many apporoaches. One approach that I would suggest would put into consideration whatever you've already started
As Below
Step 1. Forward your request and response objects into packet.jsp,instead of into packet.html
Step 2. inside packet.jsp grab the input from user and send it with
the request object from packet.jsp
Step 3. Write a servlet class that process the request object from
packet.jsp and send the video as mulitpart file with the response.
Moreover, Do some research on how to use jsp's and servlets
The second approach would be to write client side javascript code that send ajax request to grab the video in a second call. For this you might even consider some client side frameworks and libraries(like jquery, angular, etc) that ease your work.
You could do the following:
Pass that additional information via request attribute (request.setAttribute())
Use some dynamic handler (like a servlet or JSP) to serve /zips/handler.html
Use request.getAttribute() in that handler.
So:
in your initial servlet, put
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("real_source", /some real source/);
request.getRequestDispatcher("/zips/packet.html").forward(request, response);
return;
}
In your /zips/packet.html you just use request.getAttribute("real_source") to generate the html attribute you need.

Java servlet redirect has wrong URL and uses wrong HTTP method

I have a form that is submitting a POST request to a servlet defined by #WebServlet("/SignUp").
I also have checks on the client side to make sure all of the form inputs are populated, but if they sneak by that and submit the form with an empty input I'd like the servlet to send them back /Home (i.e. index.jsp) as a fallback.
I have the following for my SignUp servlet's doPost():
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
final String METHODNAME = "doGet";
logger.entering(CLASSNAME, METHODNAME);
String email = request.getParameter("email");
String pass = request.getParameter("password");
String cpass = request.getParameter("confirmPassword");
String forwardJsp = "";
if (StringUtils.isNotBlank(email) && StringUtils.isNotBlank(pass)
&& StringUtils.isNotBlank(cpass)) {
forwardJsp = "/SignUpMoreInfo.jsp";
} else {
// one of the fields was empty
request.setAttribute("signupFieldWasEmpty", true);
forwardJsp = "/Home";
}
request.getRequestDispatcher(forwardJsp).forward(request, response);
logger.exiting(CLASSNAME, METHODNAME);
}
This all works on a basic level. If they neglect to enter a value (i have yet to do any real checking, like .trim() or invalid characters), then they are send back to index.jsp (which backed by the /Home servlet).
However, I have two problems with the way my code is working and I can't figure out how to get around them.
My index.jsp is now being loaded as a POST request, rather than the usual GET. If the user refreshes the page, they get a client warning about refreshing the page on a POST request which is really ugly and cumbersome on the homepage.
The URL in the browser still has the address http://localhost:8080/SignUp, when I was expecting it to be http://localhost:8080/Home. This is also ugly and kind of confusing to the user, as the url no longer properly represents the page they associate with the "Home" page of the site.
How do I fix these issues I have with my Java backend code while maintaining as much MVC as possible?
You have to use redirect here instead to start a new request to /home :
Try this:
if (StringUtils.isNotBlank(email) && StringUtils.isNotBlank(pass) && StringUtils.isNotBlank(cpass)) {
forwardJsp = "/SignUpMoreInfo.jsp";
} else {
request.setAttribute("signupFieldWasEmpty", true);
response.sendRedirect("/Home");
}
However the problem now is that you are going to lose this information signupFieldWasEmptyso if you want to keep it you have to add as a request param to the uri :
else {
response.sendRedirect("/Home?signupFieldWasEmpty=true");
}
You can use the Post/Redirect/Get pattern to avoid this problem.
The servlet receives the Post request, processes the form, then sends a redirect to the desired page.

A one step upload for uploading images using google app engine

I am trying to implement a very basic functionality of uploading images from Android,iPhone and web clients to the google app engine. I did an initial version of the implementation thanks to this blog:
However there always seems to be a 2 step process to uploading an image:
Get the initial upload URL to POST to using the createUploadUrl(). I am attaching the fragment of code which I use :
public class CreateUploadUrl extends HttpServlet {
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
String uploadURL = blobstoreService.createUploadUrl("/image/uploadImage");
resp.setContentType("text/plain");
resp.getWriter().println(uploadURL);
}
}
POST the image using the URL which you just "got"
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
BlobKey blobKey = ParameterExtractor.getBlobParameter(req, "blob-key", blobstoreService);
if (blobKey == null) {
log.info("blob Id is null. POST failed");
} else {
log.info("ze business logic");
}
}
My question is if it is possible to do it in one step since right now all clients need to do a http GET to get the upload URL and then a http POST to POST the image.
Is it not possible to just do one Http POST with a predefined URL.
Thanks
Rajat
This is possible, with limitations. You can bypass the UploadUrl mechanism by creating blobs directly in your servlet using the (currently experimental) createNewBlobFile API. In your mobile app(s) create an HTTP request encoded as multipart/form-data, and teach your servlet how to decode such a thing (consult e.g. How to upload files in JSP/Servlet?). Be aware that HTTP requests are limited to 32MB; with form encoding the amount of binary data you can upload will be less than that.
Sure you can do it with single POST. For example you have user that have an id. This user select image and you send in POST image data and user data on client side.
On server side (GAE) you have url for image uploding (your_host/imageUpload) and server or Spring controller that read data from request and write it to Blobstore.

Categories