I have a working servlet wich originates back from this template:
http://www.objectdb.com/tutorial/jpa/eclipse/web/servlet
So the basic rountrip works.
I added a new feature where I POST data to the servlet, construct a call/request out of the data to a remote http server, retrieve the response-html-string (the content of the website I requested) and want to show this HTML String now as response to my original POST call.
I tried it like this:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
boolean showDetails = Boolean.valueOf(request.getParameter("showDetails"));
if (showDetails) {
String details = detailsLoader.loadDetails(String.valueOf(request.getParameter("value1")),
String.valueOf(request.getParameter("value2")));
response.getWriter().println(details);
response.getWriter().flush();
response.getWriter().close();
return; // <----------------- if showDetails then this is the end of doPost
}
// Display the list of guests:
doGet(request, response);
}
When I press the link that creates the POST event I see in the logfile, that "loadDetails" has succesfully loaded the content from the remote server, but the browser window does not refresh. Why?
PS: a simple redirect to the other side is not possible for technical reasons.
Try making a ajax request to your servlet which gives to html content as string sent it back to ajax call and set it to innerHTML of a div element.
I changed to use GET instead of POST and I used a separate Servlet for this kind of call. This solved my problem.
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String details = detailsLoader.loadDetails(String.valueOf(request.getParameter("value1")),
String.valueOf(request.getParameter("value2")));
response.getWriter().println(details);
response.getWriter().flush();
response.getWriter().close();
}
Related
I created one program that prints 'Welcome to our site' text on browser using servlet. It works fine inside the eclipse default browser but when I use that URL to other browser it displays text as below:
And below is the image of the code that is working well inside eclipse browser
And my code is as follows:
public class WelcomePage extends HttpServlet {
#Override
public void init() throws ServletException {
}
#Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
PrintWriter out = res.getWriter();
out.println("<h3>Welcome to our site<h3>");
out.println("<form>");
out.println("</form>");
}
#Override
public void destroy() {
}
}
After adding res.setContentType(text/html); problem resolved :)
Before sending data to client (displayed by Browser on client machine), the Servlet container informs the client browser of what type of data is being sent now. The data that can be sent may be simple plain text, html form, xml form, image form of type gif or jpg, excel sheet etc. To send this information, the Servlet container uses response object with the method setContentType().
Some examples :
response.setContentType("text/html");
response.setContentType("text/plain");
response.setContentType("text/css");
response.setContentType("application/html");
response.setContentType("image/gif");
response.setContentType("application/zip");
response.setContentType("application/pdf");
One of the webservices I am trying to connect requires me to submit a form to an url, lets say LINK_A.
I have a form view VIEW_A, I submit VIEW_A to my own servlet called SERVLET_A. Here in SERVLET_A from the form params, I generate a signature key, which is required by the webservice.
Then I need to submit to LINK_A programmaticaly from my servlet, BUT they told me that I need to submit it and redirects to LINK_A, so unlike what I've known so far (using httpclient httppost and getting the response data), I need to do something like a redirect with post data to their link.
So in summary:
1. from my view, submit a form
2. modify post data from servlet
3. submit the form to the webservice link and move to that link (as if the form from the view submit directly to the webservice link)
How can i do this?
If you need the form to be submitted from the browser (not from within your servlet using httpclient) your servlet needs to return a self-submitting form. E.g. use document.getElementById('myForm').submit() on documentReady.
If your form params can be submitted via GET you might also respond with a HTTP 302 redirect containing all params in the query string.
mean if you want collect request from previous form and check in servlet class and forward to new form den check this logic if its help
form code within servlet
rotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<html body=\"red\"> <center>");
pw.println("<form action=\"./NewFile.do\" method=\"get\">");
pw.println("<h2>enter the name </h2> <input type=\"text\" name=\"username\">");
pw.println("<h2>enter the password </h2> <input type=\"text\" name=\"passward\">");
pw.println("<input type=\"submit\" value=\"login\">");
pw.println("</form>");
pw.println("<center></body></html> ");
}
this below code to check and initialize path, before that you have to configure web.xml for this servlet class to behave as controller.
public class ServletControl extends HttpServlet {
#Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("inside the servlet");
String servletpath=request.getServletPath();
String path = null;
if(servletpath.equalsIgnoreCase("/NewFile.do")){
path="NewFile.jsp";
}
if(path!=null){
RequestDispatcher dis=request.getRequestDispatcher(path);
dis.forward(request, response);
}
}
}
I wrote this Servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/event-stream;charset=UTF-8");
response.setHeader("Cache-Control","no-cache");
PrintWriter printWriter=response.getWriter();
printWriter.write("Hello!");
}
and also this java script in index.jsp:
<script>
var resource = new EventSource("/servlet");
resource.onmessage = function (e) {
document.getElementById("container").innerHTML = e.data;
}
</script>
in order to create demo on server-sent events in html5. I inspected the jsp page in firefox and I got this error: the resource from this url is not text and nothing shows up. by the way request status is 200, OK. What is wrong with that?
Try to change the response header
response.setContentType("text/event-stream");
I have a requirement to set custom headers in http response and read them whenever required. I use the following code to read the header.
servlet1:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.addHeader("cust-header", "cust-value");
RequestDispatcher rd = request.getRequestDispatcher("servlet2");
rd.include(request, response);
}
servlet2:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(request.getHeader("cust-header"));
}
When I tried to read the custom header value, I got "null" in the console. Why this is happening? How can I read custom headers set in response whenever required?
From the RequestDipatcher include method API doc:
[...]
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.
[...]
So, if you look at your code, you are setting the header at the response object, but trying to get it from the request.
As they remain unchanged, it won't work.
The most common way to pass values from a servlet to another in a forward or include redirection, is passing it as a request attribute:
servlet1:
//set a request attribute
request.setAttribute("cust-header", "cust-value");
RequestDispatcher rd = request.getRequestDispatcher("servlet2");
rd.include(request, response);
servlet2:
System.out.println(request.getAttribute("cust-header"));
I have an authorization frame displayed on every page and I want to keep that page displaying even if the user will choose to log in (using jstl tags i will simply put instead of this frame user info and link to shopping cart). How can i achieve that ? I have some ideas, but they all breaking out my controller design.
public class FrontController extends HttpServlet {
private ActionContainer actionContainer = ActionContainer.getInstance();
public FrontController() {
super();
}
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#SuppressWarnings("unchecked")
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String page = null;
try {
Action action = actionContainer.getAction(request);
page = action.execute(request, response);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(page);
dispatcher.forward(request, response);
} catch (ActionNotFoundException e) {
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(PageNames.ERR_PAGE);
request.setAttribute(AttributeNames.ERR_MESSAGE_ATTRIBUTE, "Unknown Action command: " + e.getMessage());
dispatcher.forward(request, response);
} catch (Exception e) {
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(PageNames.ERR_PAGE);
request.setAttribute(AttributeNames.ERR_MESSAGE_ATTRIBUTE, "Exception:\n" + e.getMessage());
dispatcher.forward(request, response);
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Front Controller";
}
#Override
public void init() throws ServletException {
super.init();
Locale.setDefault(new Locale("ru","RU"));
}
}
I was thinking about of redirecting to especially written for this case page, which will redirect to the original page, or to check page string for null and reloading from controller the original page, but i cannot clearly understand how to do this.
Your question isn't clear enough. But I think you're asking how you can replace a certain component on a page (Login button) with an other (username, welcome message and shopping cart details) after the user logs in.
If I understand your requirements, then what I would do after the user logs in is set a cookie (or a value in localStorage). The cookie is added to the Set-Cookie response header by means of the addCookie method of HttpServletResponse. Here's an example:
Cookie userCookie = new Cookie("user", "uid1234");
response.addCookie(userCookie);
Then in your controller simply check if the "user" value is set or not and take the appropriate action. A tutorial on servlets with cookies.
If you need to handle the front-end component, and change values on the form without reloading the page, I would recommend using javascript to do this, you can find and remove the old DOM elements with new ones (User's name, Welcome message, shopping cart, whatever).
If your iFrame is doing the login, then on successful login, have it call a function in your top window that does the update after reading the updated values from the cookie.
If you want to handle this completely at the front-end, i.e. Javascript, then I would skip using cookies and use localStorage instead. There is plenty of help on Stackover and on the internet about what localStorage is, but I will suggest the YUI Storage Lite library which makes storing and loading data from localStorage very simple.
Regards,
Include the current URL as a hidden field of your authentication form. In the action handling the authentication, once the user is authenticated, redirect to this URL.
In the JSPs, test if the user is authenticated and include the authentication form or the shopping cart. This test can be done by just putting a boolean value in the HTTP session once the user is authenticated.