How can we create request, response cycle with JSP pages? - java

While developing JSP pages, we can run a Java code in server side, while JSP page is active in the client side...
How to create request and response cycle between Java Code(at the server side) and JSP page(at the client side)...
What is the difference between JSP and JSF technology for this kind of dynamic web pages?
And which one is better JSF or JSP?

You can use RequestDispatcher Method
In Server side create test.java you can write
ServletContext context= getServletContext();
RequestDispatcher rd= context.getRequestDispatcher("/LoggedIn");
rd.forward(request, response);// used to forward data
if you want to include data use
rd.include(request,response);// used to include data

The common way to send information from java code to JSP is to set appropriate attributes of HttpServletRequest object. But you can't access JSP variables from java code because there is no sense in it. So it's "unidirectional communication", and when JSP page was sent to client only new HTTP request can help you.
Schematic HTTP request processing:
client -> servlet container -> servlet -> JSP -> HTML -> client

Related

How to send values from one jsp page to other but redirect to some other page?

I want to send values from jsp1.jsp to jsp2.jsp but redirect jsp1.jsp to jsp3.jsp . I used the following code in servlet for jsp1
response.sendRedirect("welcome1.jsp");
request.setAttribute("usern",user);
RequestDispatcher rd = request.getRequestDispatcher("afterlogin.jsp");
rd.forward(request,response);
but it keeps on giving this error "org.apache.jasper.JasperException: PWC6033: Error in Javac compilation for JSP".
you can use the possiblites of sessions in those case so you can access the parameter in jsp2 and redirect the jsp 1 to 3
https://www.javatpoint.com/servlet-http-session-login-and-logout-example
http://java.candidjava.com/tutorial/Servlet-Jsp-HttpSession-Login-logout-example.htm
You can use a HttpSession object as a user session, or use the ServletContext object for sharing global application information. Then use methods getAttribute (String attb) and setAttribute (String attb, String value) for sharing information within JSPs. The issue when you use a request is that the domain of the request is constraining you to use this information only when you receive this request.
You can also use JavaBeans to share information within JSPs
EDIT: Have you included your Java code inside a scriptlet? Using <% your code here %>
when you are using the sendRedirect function it will immediately redirect to that page it will not read next line code.
So according to your code your compiler is smart enough to check it so it is giving you an error.
please see below
1) SendRedirect ():
This method is declared in HttpServletResponse Interface.
Signature: void sendRedirect(String url)
1)In case of sendRedirect request is transfer to another resource to different domain or different server for further processing.
2)When you use SendRedirect container transfers the request to client or browser so URL given inside the sendRedirect method is visible as a new request to the client.
3)In case of SendRedirect call old request and response object is lost because it’s treated as new request by the browser.
4)SendRedirect is slower because one extra round trip is required because completely new request is created and old request object is lost.Two browser request required.
5)But in sendRedirect if we want to use we have to store the data in session or pass along with the URL.
2) Forward():
This method is declared in RequestDispatcher Interface.
Signature: forward(ServletRequest request, ServletResponse response)
1)When we use forward method request is transfer to other resource within the same server for further processing.
2)In case of forward Web container handle all process internally and client or browser is not involved.
3)When forward is called on requestdispather object we pass request and response object so our old request object is present on new resource which is going to process our request
4)Using forward () method is faster then send redirect.
5)When we redirect using forward and we want to use same data in new resource we can use request. setAttribute() as we have request object available.
more in : https://www.javatpoint.com/q/3577/difference-between-requestdispatcher-and-sendredirect

Obtain servlet response when using Cross-Context

I'm using cross-context to call a servlet in another server application: Servlet /bar from server application 'A' calls /foo servlet on server application 'B'.
I'm using this very nice solution, just as in the Abhijeet Ashok Muneshwar answer, I forward the request from server application A to the /foo servlet on server application B.
I'm using the class RequestDispatcher () to send a request, but the response is returned in the same call?
RequestDispatcher rd = context.getRequestDispatcher("/Servlet2");
rd.forward(request, response);
How can I process and return the response from server application B in A's servlet.
Thanks.
If you use a forward, that passes control to the target of the forward. The other option with a RequestDispatcher is to do an include.
If you want more control than that, you'll have to use an HTTP client to retrieve the response and then apply whatever processing you want to but using an HTTP client this way is not something I'd recommend. You'd be better off refactoring your application so you can use RequestDispatcher.include.

Forward to a servlet and set attribute

I'm working with servlets in java; I'm trying to forward from one servlet to another servlet.
I also want to pass an attribute to that other servlet.
When i want to forward to a JSP, it works fine. i do
request.setAttribute("attrName", attribute)
request.getRequestDispatcher("forward.jsp").forward(request, response);
But When I do the same with a servlet:
request.setAttribute("attrName", attribute)
request.getRequestDispatcher("TheServlet").forward(request, response);
My server freaks out and I get the following error:
javax.servlet.ServletRequestWrapper.isAsyncStarted(ServletRequestWrapper.java:395)
I know I can use the following line to redirect to a servlet:
response.sendRedirect("TheServlet");
But for some reason the set Attribute doesn't work when I redirect instead of forward.
redirect is a HTTP response sent to the browser requesting it to submit a new request to the specified URL. Since it results in issuing an entirely new request previous request attributes you set wont be available in the new request.
In terms of forwarding to a servlet, did you check your web.xml configuration. Is it setup so that the forwarded servlet is seeing forwarded requests ?
You could save the attribute to the session in the first servlet and access it from the second.
Use http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getSession()
Also you could pass the attribute value in the URL query string in the redirect. So your redirect URL would look like 'myRedirectUrl?attributeName=attributeValue'
Also additionally try using 'include' method rather than 'forward'.

In BrightSpotCMS HOWTO inspect the "request" object from HttpServlet before the JSP is rendered for a "Content" object

In many MVC frameworks when a request is made it goes to a controller/action class (based on the URL pattern among other things). If the developer wants to do something with the request object or other processes then it does that with in the execute or doGet or doPost etc methods & then forwards it to the dispatcher. The response type could be a JSON, JSP, XML etc.
I have a brightspot cms webapp in which I want to do something similar. It is based on the open source project dari framework.
In case of a object of type Content if I want to setup some pre-processing of variables to be used in the JSP page based on the request object, how can I do it? I am unable to find the point of intervention between the request going to conten type object AND request being forwarded to the backing JSP page.
I know I can just add scriptlets to the JSP page, but I had rather not do it for variety of reasons.
I was able to resolve this by adding a Filter for the URL pattern I was interested in. More info here.

Is it possible to use a JSP as a template for a servlet?

I've been intermixing JSPs and Servlets in the web app I'm building and I'm starting to find that my more complex JSPs end up containing a lot of code, which flies in the face of all the MVC lessons that have been pounded into me. I know I can do this by just forwarding to the JSP, but this seems like a stupid hack.
What I'd like to do is use a servlet to do processing and then send a set of values to the JSP to render the HTML and return the response. Something along the lines of:
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
// ... Do some processing
resp.getWriter.print(renderJSP("mypage.jsp", values));
}
}
I've been poking around Sun's documentation and found this: http://java.sun.com/developer/technicalArticles/javaserverpages/servlets_jsp/
It seems like the JSP Model 2 architecture is exactly what I want to implement, but I cannot find an example of how one can set that up. For technical reasons, I cannot use one of the more advanced template frameworks like Struts.
Is this possible or a lost cause?
Put the object(s) in the request, forward the request to the jsp page and then use the object(s) in the jsp to render the response.
In your servlet,
MyObject obj = ... //build somehow
request.setAttribute("myObject", obj);
RequestDispatcher rd = request.getRequestDispatcher("WEB-INF/jsp/my.jsp");
rd.forward(request, response);
If your result JSP should not be accessed directly from a URL you should hide it inside the WEB-INF directory where it can be accessed only through the forward directive.
Then on your jsp you can have,
<% MyObject obj = (MyObject) request.getAttribute("myObject"); %>
To retrieve the object and used it as needed.
As others suggested, eventually it would be a good idea to learn to use JSTL and maybe an MVC framework like Spring MVC. The tutorial can be found here.
Put Java objects in the Request/Response/Session and use a javax.servlet.RequestDispatcher in your servlet, something like that:
RequestDispatcher dispatcher = request.getRequestDispatcher("/test.jsp");
dispatcher.forward(request,response);
A forward is server-side and the target servlet/JSP receives the same request/response objects as the original servlet/JSP. Therefore, you can pass data between them using request.setAttribute().
The other option is to use response.sendRedirect(String location) which is client-side (this method sends a temporary redirect response to the client) so the location URL receives a new request from the client, and the only way to pass data is through the session or with web parameters (url?name=value).
This is basically what MVC frameworks do (and no, it's not a hack).
You describe forwarding to the JSP as a hack, but really, that's exactly what the MVC frameworks do (Spring MVC and Struts, at least).
The "model" is the request attributes, which the servlet populates; then the JSP just retrieves them to show. You can wrap that in a "ModelAndView" like Spring MVC does, but it's really about it.
You can get more sophisticated on the JSP, of course, parsing request parameters, session attributes or servlet context ("global") attributes. I've found, in general, it's cleaner to let the front controller/servlet marshall all those into request attributes and have the page just pull from them. If you're using JSTL, the difference between request and session can be even blurrier.

Categories

Resources