invoke jsp from java code and get output - java

I have a JSP page that show data in some formatted way. the browser can call spring showInfo.do and it is forward to that JSP.
i.e.
public showInfo(HttpServletRequest request, HttpServletResponse response) {
RequestDispatcher rd = getServletContext().getRequestDispatcher("info.jsp");
dispatcher.forward(request,response);
}
The output of the JSP is html.
Now I want to save this JSP output manually from my java server side code (not in a servlet context), something like this:
void saveInfo() {
params.setParameter("info1", "data");
String responseStr = Invoke("info.jsp", params);
//save responseStr to disk
}
I want to be able to save the html page on disk from a service and make it look the same as a user can see it from a browser. So if the server is offline a user can double click on the saved html file and see in his browser the last info.
Any idea how this can be done?

Oups. The servlet specification requires the servlet container to be able to execute a JSP file. This is commonly done by converting the JSP to plain Java and the generating a servlet class file.
If you are outside of a servlet container you must:
* either fully implement a JSP execution environment, for example by using sources from a servlet container like Tomcat
* or rely on a servlet container to convert the JSP file to a .java or .class servlet and then use the Servlet interface methods on it
Alternatively, you could try to use a headless browser to capture the output of the application.

Related

How to send file via Ajax call to Servlet

I have an HTML form in AEM where I have to attach the files and the same files will be sent to one Rest API via Java Servlet.
I am calling the Java Servlet via Ajax and able to send other String data to Java Servlet but not able to send the file Array which contains the files attached to the HTML Form attachment option while submitting the Form. How can I get the file in Java servlet?
In JS
var myFile [] is what I am sending in a ajax call.
$.ajax({
url: /servletUrl,
type: 'post',
data: {
'myFile': myFile,
},
success: function(response){
}
});
In Java :
Enum paramObject = request.getparameter();
When I put the object in HashMap and try to get the file, its type is coming as String not Object.
I am not sure where I am setting it as String.
The servlet has to be able to process Multipart-Messages.
I do not know AEM, but in Jakarta / Java Enterprise Edition / JEE / J2EE:
you have to specifically add the #Multipart annotation to the servlet.
Now, open your browser, press F12 to go into debug details, and when you trigger the request, the Network tab will display alle the infos that are posted. Look up the name of the parameter, usually it's calles file[]
When handling the request in the servlet, you can use the HttpServletRequest's request.getParts() method to find all parameter parts.
With final Part filePart = request.getPart(pFileParamName); and final InputStream filecontent = filePart.getInputStream(); you will be able to access the data.
And this will probably be very similar in most servlet frameworks.

Servlets + JSP leading to response 404 and server error "PWC6117"

I am just a beginner in Java Web and I am exploring the pure Servlets and JSPs (with no frameworks). I am trying to build up a simple CRUD and I got stuck in an error that makes no sense at all (at least to me!).
Objective
I wanna build a simple CRUD with several Servlets containing the logics and database operations (controller) and JSPs to display the pages (views). I have already successfully build up a CustomerIndexServlet (route: /customers), which returns the list of records and a button to CustomerNewServlet (route: /customers/new) which SHOULD return a JSP with the form to create new records.
Issue
Calling CustomerNewServlet leads to a Page Not Found (404) and GlassFish prints the message PWC6117: File "null" not found in the console. By debugging the code, the error occurs when forwarding the request through RequestDispatcher. I don't understand! If I try to access the JSP directly (at http://localhost:8080/MyApp/customerForm.jsp), it returns OK (200). I even printed the path of JSP before forwarding to make sure it is the one expected!
#WebServlet(name = "NewCustomer", urlPatterns = {"/customers/new"})
public class NewCustomerServlet extends HttpServlet {
#Override
protected void doGet(
HttpServletRequest request,
HttpServletResponse response
) throws ServletException, IOException {
System.out.println(request.getContextPath());
if (request.getSession().getAttribute("login") == null)
/*error*/ request.getRequestDispatcher(request.getContextPath()).forward(request, response);
else
/*error*/ request.getRequestDispatcher(request.getContextPath() + "/customerForm").forward(request, response);
}
}
And in server's console it is displayed:
Info: /MyApp
Server: PWC6117: File "null" not found
What am I doing wrong? Does it have something to do with the file locations and directories?
I figured out what happen and how redirection and forward deal with URI's... I'm gonna share the knowledge I've acquired:
response.sendRedirect(URL)
When using the sendRedirect() method, you are requesting the client to submit a new request to the passed URL. When using an absolute path, you have to concatenate the request.getContextPath() prefix to your URL, if you wanna target a resource within your application.
request.getRequestDispatcher(URL).forward(...)
When dispatching the request to another URL, it already uses application context. So using request.getContextPath() + "/customerForm.jsp" as target URL will only look for a resource in /AppName/AppName/customerForm.jsp. Then, omitting the getContextPath() call is enough to make my code work as expected.

Cannot redirect when the script is include by RequestDispatcher

I am having problem with redirect in jsp , the page just remains and doesn't throw any error.
I am able to do redirect when I direct write the script in my login.jsp like
<%
String redirectURL = "/client/index.jsp";
response.sendRedirect(redirectURL);
%>
<t:login title="Client Login">
..........
</t:login>
But I am unable to do redirect when I split the file into three and include it. below is my implementation.
login.jsp
<%#include file="/include/checkhandler.jsp"%>
checkhandler.jsp - this is a script that will check for file in handler folder and include it when it is exist.
......
request.getRequestDispatcher(handler).include(request, response);
......
login_handler.jsp this is the file the dispatcher will include
String redirectURL = "/client/index.jsp";
response.sendRedirect(redirectURL);
out.println("hello world");
After I execute this script , the hello world displayed but it is still stay at the same page without any error.
You need to use RequestDispatcher#forward() instead. Change your checkhandler.jsp to
request.getRequestDispatcher(handler).forward(request, response);
A server-side include is prohibited to change the response status code which is what happens when you use sendRedirect(). Any such attempt is simply ignored by the container.
From the RequestDispatcher#include() docs:
The ServletResponse object has its path elements and parameters remain
unchanged from the caller's. The included servlet cannot change the
response status code or set headers; any attempt to make a change is
ignored.
This limitation is by design. The spec treats the web component being included as a guest i.e. it cannot direct the flow and any such attempts would be rightly ignored instead of throwing an exception to possibly allow an include for any servlet that you may have.
Only the hosting web component (the one doing an include) would be in complete control of the flow as well as what response headers are sent over to the client.
You have this in your code
out.println("hello world");
String redirectURL = "/client/index.jsp";
response.sendRedirect(redirectURL);
which will not work because you cannot redirect after writing to the response stream. The redirect is sent in the response header. The response body should not contain any html.

Can GWT client read the httpservletresponse with which it was invoked?

I have a Greasemonkey script that reads contents of a file from one site and sends it via HTTP POST method to a servlet in my GWT application. Once the content is available in my servlet I want to pass on the file content to the GWT client(i.e. trigger open the application with the file contents).
For triggering the application, I use this in my servlet code:
response.sendRedirect("/path/to/my/application");
Is there any way to read the file contents in the onModuleLoad() of my GWT entry point class? Because I am redirecting the response from servlet to the client, will the response contain the string file that was read from the other site?
Currently what I do is,
read the file from the site and send it via HTTP-POST to my server.
store the String contents in session
send a cookie to the client to indicate that a file is available in server session to be read
client on reading the cookie, sends a request to the server to get the file.
I find that this method seems to be sort of round about. Is there an easier way to do this, by accessing the file contents directly by reading the response content in client side?
You might want use load-on-startup in your web.xml file and then override the init() method in your servlet to do the required task.
<servlet>
<servlet-name>startupTasks</servlet-name>
<servlet-class>xxx.xxxxxx.server.StartupTasksServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
Additional Info can be found here
Use Timer that will continuously look into user session using GWT RPC call. If file content is found in session then just send the content to the client.
Put below code in your Entry point class.
Timer timer = new com.google.gwt.user.client.Timer() {
#Override
public void run() {
//GWT RPC call to check the user session
// if you want then cancel the timer
//timer.cancel();
}
};
timer.scheduleRepeating(5000); // 5 seconds
Or you can try this one also
If /path/to/my/application is redirecting to a JSP file then you can read session attribute in JSP file.
Server side:
session.setAttribute("keyname",fileContent);
JSP:
<div id="myHiddenDiv" style="visibility: hidden;"><%=session.getAttribute("keyname")%></div>
Entry Point:
System.out.println(getElementById("myHiddenDiv").getInnerHTML());
...
public static final native Element getElementById(String id) /*-{
return $wnd.document.getElementById(id);
}-*/;

Url Shortener redirects to index.html

Yes, yet another url shortener written in java, because I wanted my own, and because why not. Currently everything works, just not they way I want to to. In short, there is only one servlet mapped to "/" in the entire project. There are no frameworks involved, or anything fancy, this is just a basic Servlet "project". on doPost a new shortUrl is created, and you get a JSON response. On doGet, if the URL is "/*{any_valid_short_url}" then a redirect is sent (below).
response.sendRedirect("longUrlString")
The issue I am having is with the index page, when the same doGet is called, I check the requested path, if it is "/" then currently, I use a FileInputStream and stream the index.html page out via response.getOutputStream(), which is pretty hacky in my opinion. I would like to use a requestDispatcher instead, however when I do try to implement that (below) I get into a re-direct loop, and the servlet container (jetty or tomcat) stack overflow's.
getServletContext().getRequestDispatcher("/index.html").forward(req, res);
Is there something that I am mis-understanding about how this is being done? The project is currently hosted on my github page. https://github.com/justinmburrous/ShortUrl
You need to make this check more narrower, because for all requests this condition is true and hence for all requests are forwarded to 'index.html' again and again
if(requestedPath.equals("/")){
//tried with multiple variations of /index.html, renamed to jsp, etc...
RequestDispatcher dispatcher = request.getRequestDispatcher("index.html");
dispatcher.forward(request, response);
}
Edit:
Since your servlet is mapped as default servlet , all forwards or request will be handled by this Servlet.
You should map the url to more specific range.
RequestDispatcher - forward - produces infinite loop
Okay, I have figured this one out with thanks to How to access static resources when mapping a global front controller servlet on /*
My github page has the working code along with the Filter, modified servlet and web.xml for.

Categories