• No results found

COMMUNI CATION WITH HTML

In document Java Book Latest (Page 63-76)

// exception handler code here

COMMUNI CATION WITH HTML

<input‏type‏=submit‏name‏=submit‏value‏=submit‏action=‏‖url‏page‏/ *‏.do‖> Data Transfer between Servlets

1. getParameter() 2.setParameter() 3. getInitPrameter() package jsp.tutorials.servletexample; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class WelcomeServlet extends HttpServlet {

@Override

public void init(ServletConfig config) throws ServletException { super.init(config);

}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

/* * Get the value of form parameter */ String name = request.getParameter("name"); String welcomeMessage = "Welcome "+name;

/* Set the content type(MIME Type) of the response. */ response.setContentType("text/html");

PrintWriter out = response.getWriter(); /* * Write the HTML to the response */ out.println("<html>");

out.println("<head>");

out.println("<title> A very simple servlet example</title>"); out.println("</head>");

out.println("<body>");

out.println("<h1>"+welcomeMessage+"</h1>");

out.println("<a href="/servletexample/pages/form.html">"+"Click here to go back to input page "+"</a>");

out.println("</body>"); out.println("</html>"); out.close();

}

public void destroy() { }

Port Numbers

Oracle – 1521 ,WebLogic – 7001 , RMI – 1099, Tomcat 8080. doGet( )

allow only 256 characters at a time. URL will be displayed.not secure. To avoid URL Display use encodeURL()

to‏get‏things.Can‘t‏modify‏anything‏from‏Server.

doPost( )

allow any number of characters at a time.

url will not be displayed. to send data to be processed. Servlet Context

ServletContext Defines a set of methods that a servlet uses to communicate with its servlet container.

The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized.

You can specify param-value pairs for

ServletContext object in <context-param> tags in web.xml file.

The ServletContext parameters are specified for an entire application outside of any particular servlet and are available to all the servlets within that application

Servlet Config.

The ServletConfig parameters are specified for a particular servlet and are unknown to other servlets

Deployment Descriptor – web.XML contents. <web-app>

<servlet>

<servlet –name> . . . . </servlet-name> < servlet-class> . . . . </servlet-class> </servlet> <servelt-Mapping> <servelt-name> . . . .</servelt-name> <url-pattern> . . . </url-pattern> </servlet-Mapping>

<load-on-startup>1</load-on-startup> --> alternate way to create instance. <session-config>

<session-timeout> 50 </session-timeout> --> can invalidate of session if put 0. </session-config> <error-page> <error-code> 404</error-code> <exception-type>Exception</exception-type> <location>/ filename.jsp</location> </error-page> <jsp-config> <taglib> <taglib-uri>---</taglib-uri> <taglib-location>--</taglib-location> </taglib> </jsp-config> </web-app>

Javax.servlet contains:

Interfaces Classes Servlet Generic Servlet ServletRequest ServletInputStream ServletResponse ServletOutputStream ServletConfig ServletException ServletContext UnavailableException SingleThreadModel Javax.servlet.http contains: Interfaces Classes HttpServletRequest Cookie HttpServletResponse HttpServlet HttpSession HttpSessionBindingEvent HttpSessionContext HttpUtils HttpSessionBindingListener

A Sample File Upload Program using Servlets import java.io.IOException; import java.io.File; import java.io.PrintStream; import java.io.ByteArrayOutputStream; import java.util.Hashtable; import java.util.Enumeration; import javax.servlet.* ; import javax.servlet.http.* ; /* *

* This is a basic file upload servlet. It will handle file uploads, * as performed by Netscape 3 and 4. Note: This program does not implement RFC 1867, merely a subset of it.

* /

public class FileUploadServlet extends HttpServlet { protected int maxSize = // ...

public void init( ServletConfig sc ) { // ... }

/* * * Since fileupload requires POST, we only override this method. * / protected void doPost( HttpServletRequest req, HttpServletResponse res ) throws ServletException, IOException

{ // ... }

/* * * Obtain information on this servlet. * @return String describing this servlet. * /

public String getServletInfo() {

return "File upload servlet -- used to receive files"; }

when i login to 1 application the path should forward to all the applications with out relogin ‏‏‏‏SSO is one of them

3.store uid and pwd in DB Predefined Objects. 1. request 2.response 3.servletRequest 4.servletResponse 5.Session 6.Exception 7.Cookie.

printWriter out = res.getWriter();

out.println() ;--> write data in Character Stream. ServeltOutputStream out1= res.getOutputStream() Out.write(oByteArray); --> Write in byte Stream. To restrict a servlet/ JSP to display in browser

 Res.setHeader(―pragma‖, ―no cache‖);  bufferSize = 0 kb; // in JSP

Servlet chaining is a technique in which two or more servlets can cooperate in servicing a single request.In‏servlet‏chaining,‏one‏servlet‘s‏output‏is‏piped‏to‏the‏next‏servlet‘s‏input.‏This‏process‏ continues until the last servlet is reached. Its output is then sent back to the client.

Servlet Tunneling : Used in applet to servlet communications, a layer over http is built so as to enable object serialization.

Context ServletRequest HttpSession

GetAttribute() GetAttribute() GetAttribute()

SetAttribute() SetAttribute() SetAttribute()

RemoveAttribute() RemoveAttribute() RemoveAttribute() GetAttributeNames() GetAttributeNames() GetAttributeNames()

For storing a variable temporarily for a particular request -->‏‏Req.setAttribute(―name‖,value); For storing a variable temporarily for a particular request -->‏session.SetAttribute(―name‖,value); GetServeltContext().setAttribute(―name‖,value);

GetServeltContext().getAttribute(―name‖);‏--> will print its value. Lock Session & Context --> synchronized(getServletContext());

synchronized‏(‏―session‖); Session Tracking Methods.

1. Cookie( ) – it is a piece of information generated on the client side for identification of server. Cookie c1 = new Cookie();

c1.setValue(―name‖,value); c1.getCookie();

c1.setMaxAge(0) --> delete cookie

2.Hidden fields and Query strings – transfer data from page 1 to page 2 as hidden fields. 3.URL Rewriting.

Response.encodeURL(―/el.do‖)

Response.encodeRedirectURL(―/el.do‖)‏ add extra session id to this URL 4. Session( )

It is the time difference between a user login and logout. Store on the server side. HttpSession --> interface.

HttpSession. S1=req.getSession(false); --> continue with existing session ID. HttpSession. S1=req.getSession(true); --> create new session.

HttpSession.getSession(true); S1.setSession(―name‖,value); S1.getSession();

session.isNew() --> check if session is available. Major methods in Session

getCreationTime(); getLastAccessedTime(); getMaxInactiveInterval(); setMaxInactiveInterval(); invalidate();

Close Session techniques 1. timeout.

2. close application 3. session.invalidate()

4. setMaxInactiveInterval(0) --> close session immediately. 5.Authentication --> Using HTTPS protocol.

HTTPS Protocol  define in Web.xml <security–constraint> <userdataconstraint> <transport-guarentee> CONFIDENTIAL <transport-Guarentee> </userData-Constraint> <security-constraint> as on webService.xml  In‏protocol‏=‖HTTPS‖ Hidden field.

The disadvantage is that every user action must result in the submission of a form or you lose the data. This limits the sort of HTML you can put on the page.

Since hidden fields put all previous data on each form as you go through several forms the pages transmitted get bigger, and bigger, and bigger -- taking longer, and longer, and longer to load. Read XML DATA

String XML=xml_data_as_a_string; File f = new File(C:\xmlData‖); FileWriter fw= new FileWriter(f); Fw.write(xml);

singleThreadModel

class c1 extends httpServletRequest implements singleThreadModel . when a class get more than 1 request ,more than 1 instance will be created for a particular class.

SSI – Server Side Include :

Server-Side Includes allows embedding servlets within HTML pages using a special servlet tag. In many servlets that support servlets, a page can be processed by the server to include output from servlets at certain points inside the HTML page. This is accomplished using a special internal SSINCLUDE, which processes the servlet tags. SSINCLUDE servlet will be invoked whenever a file with an. shtml extension is requested. So HTML files that include server-side includes must be stored with an .shtml extension.

servlet –servlet communication

servletcontext.config.getServlet‏(―‏req‏URL‖)

TestServlet test= (TestServlet)getServletConfig().getServletContext().getServlet("OtherServlet"); Servlet – Servlet / JSP communication

1.‏servletcontext.config.requestDespacher(―req‏URL‖) include(req,res); forward(req,res);

RequestDispatcher

request.setAttribute("selectedScreen", request.getServletPath());

1. RequestDispatcher dispatcher = request.getRequestDispatcher ("/template.jsp"); if (dispatcher != null) { dispatcher.forward(request, response); }

2. servletcontext.config.sendRedirect(―req‏URL‖) SendRedirect

String destination ="/jsp/destination.jsp";

response.sendRedirect(response.encodeRedirectURL(destination)); response.sendRedirect(response.encodeRedirectURL("http://www.google.com"));

Read a Data from XML

ServletContext context = getServletContext();

String myValue = context.getInitParameter("emailid"); Forward( ) : javax.Servlet.RequestDispatcher interface. - RequestDispatcher.forward( ) works on the Server.

- The forward( ) works inside the WebContainer.

- The forward( ) restricts you to redirect only to a resource in the same web-Application.

- After executing the forward( ), the control will return back to the same method from where the forward method was called.

- The forward( ) will redirect in the application server itself, it does'n come back to the client. - The forward( ) is faster than Sendredirect( ) .

To use the forward( ) of the requestDispatcher interface, the first thing to do is to obtain RequestDispatcher Object. The Servlet technology provides in three ways.

1. By using the getRequestDispatcher( ) of the javax.Servlet.ServletContext interface , passing a String containing the path of the other resources, path is relative to the root of the ServletContext.

RequestDispatcher rd=request.getRequestDispatcher ("secondServlet"); Rd.forward(request, response);

2. getRequestDispatcher( ) of the javax.Servlet.Request interface , the path is relative to current HtpRequest.

RequestDispatcher rd=getServletContext( ).getRequestDispatcher("servlet/secondServlet"); Rd.forward(request, response);

3. By using the getNameDispatcher( ) of the javax.Servlet.ServletContext interface. RequestDispatcher rd=getServletContext( ).getNameDispatcher("secondServlet"); Rd.forward(request, response);

Sendredirect( ) : javax.Servlet.Http.HttpServletResponce interface - RequestDispatcher.SendRedirect( ) works on the browser.

- The SendRedirect( ) allows you to redirect trip to the Client. - The SendRedirect( ) allows you to redirect to any URL.

- After executing the SendRedirect( ) the control will not return back to same method.

- The Client receives the Http response code 302 indicating that temporarly the client is being redirected to the specified location , if the specified location is relative , this method converts it into an absolute URL before redirecting.

- The SendRedirect( ) will come to the Client and go back,.. ie URL appending will happen. Response. SendRedirect( "absolute path");

Absolutepath – other than application , relative path - same application.

When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completely with in the web container. When a sendRedirtect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completely new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.

Include

method this is used to tag in the contents of a resource as a part of the response flow as if it were part of the calling servlet. If you include a jsp or a servlet, it must not attempt to change the response status code or the http headers, as any such request will be ignored.

Forward

this method is used to show a different resource in place of the servlet originally requested. This resource may be a jsp, a servlet etc. When a request is sent from the client to the web server through an url , the web container intercepts the request and sends it to another resource without the knowledge of the client browser. And a response is received from that resource after processing of the request is done.

RequestDespatcher

control between servlets will be forwarded temporarily from one to another and is received back in servlet communications.

sendRedirect

control is forward permanently from one servlet to another on servlet communications

Include

Connection is temporarily forwarded and returned back

Forward

Control is permanently forwarded to next servlet. SendRedirect

1. always sends a header back to the client/browser. this header then contains the resource(page/servlet) which u wanted to be

Forward

1. resources from the server, where the fwd. call was made, can only be requested for.

redirected.

2. the browser uses this header to make another fresh request.

3. sendRedirect has a overhead as to the extra remort trip being incurred.

4. the advantage is that u can point to any resource

2.forward just routes the request to the new resources which u specify in ur forward call. 3.That means this route is made by the servlet engine at the server level only.

no headers r sent to the browser which makes this very eficient.

4.also the request and response objects remain the same both from where the forward call was made and the resource which was called. res.sendRedirect ()

With response.sendRedirect(), the browser is asked to go get another page. All HTTP

parameters of the original request are lost. The browser's location bar changes.

Jsp:Forward( )

<jsp:forward> is more efficient. It forwards the request to the specified JSP page on the server side, without asking the browser to generate a new request. You can only forward to resources served by your application server! It also keeps the state. The browser's location bar doesn't change.

Filters --> A‏filter‏is‏an‏object‏that‏can‏transform‏a‏request‏or‏modify‏a‏response.It‏won‘t create response . They are preprocessors of requests before they reach a Servlet and postprocessors of responses after leaving a Servlet.

Implement javax.servlet.filter I nterface Servlet filters can:

Intercept a Servlet's invocation before the Servlet is called. Examine a request before the destination Servlet is invoked.

Modify request headers and request data by subclassing the HttpServletRequest object and wrapping the original request.

Modify the response headers and response data by subclassing the HttpServletResponse object and wrapping the original response. Intercept a Servlet's invocation after the servlet is called

The designers of Servlet Filters identified the following examples for their use: 1. Authentication Filters.

2. Logging and Auditing Filters. 3. Image conversion Filters. 4. Data compression Filters. 5. Encryption Filters

6. Tokenizing Filters

1. Filters that trigger resource access events 2. XSL/T filters

3. Mime-type chain Filter Filer Life Cycle

public interface Filter {

public void init(FilterConfig filterConfig);

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain); public void destroy(); }

init( ) : called when the filter is initialized and loaded into memory by the Servlet container; called when the filter is being put into service.

doFilter( ) : called by the Servlet container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain.

The FilterChain passed in to this method allows the Filter to pass on the request and response to the next entity in the chain.

destroy( ) : called just prior to the filter being removed from memory; called when the filter is being taken out of service.

The init and destroy methods manage an internal FilterConfig member variable The following two sections were added to web deployment descriptor that parallel the Servlet descriptors:

filter: defines a unique filter name and the fully qualified class name that it references filter-mapping: maps URLs to filters

In Web.xml Add the following <filter> <filter-name>TimerFilter</filter-name> <filter-class>com.informit.webtechnologies.TimerFilter</filter-class> </filter> <filter-mapping> <filter-name>TimerFilter</filter-name> <url-pattern>/* </url-pattern> </filter-mapping> Event Listeners

Servlet context-level (application-level) event --> This involves resources or state held at the level of the application servlet context object.

Session-level event --> This involves resources or state associated with the series of requests from a single user session; that is, associated with the HTTP session object.

At each of these two levels, there are two event categories: 1. Lifecycle changes

2. Attribute changes

Event Category Event Descriptions Interface Servlet context

lifecycle changes

Servlet context creation, at which point the first request can be serviced Imminent shutdown of the servlet context

javax.servlet.ServletContextListener Servlet context attribute changes

Addition of servlet context attributes javax.servlet. ServletContextAttributeListener

Event Category Event Descriptions Interface Removal of servlet context attributes Replacement of servlet context attributes Session lifecycle changes

Session creation Session invalidation Session timeout javax.servlet.http. HttpSessionListener Session attribute changes Addition of session attributes Removal of session attributes

Replacement of session attributes javax.servlet.http.

HttpSessionAttributeListener Typical Event Listener Scenario

The listener is notified of application startup.

The application logs in to the database and stores the connection object in the servlet context.

Servlets use the database connection to perform SQL operations.

The listener is notified of imminent application shutdown (shutdown of the Web server or removal of the application from the Web server).

Prior to application shutdown, the listener closes the database connection. Event Listener Declaration and Invocation In web.xml

<web-app> <listener> <listener-class>com.acme.MyConnectionManager</listenerclass> </listener> <listener> <listener-class>com.acme.MyLoggingModule</listener-class> </listener> </web-app>

In a multithreaded application, attribute changes might occur simultaneously. There is no requirement for the servlet container to synchronize the resulting notifications; the listener classes themselves are responsible for maintaining data integrity in such a situation. Each listener class must have a public zero-argument constructor.

Each listener class file must be packaged in the application WAR file, either under /WEBINF/ classes or in a JAR file in /WEB-INF/lib.

ServletContextListener Methods, ServletContextEvent Class

The ServletContextListener interface specifies the following methods:

void contextInitialized(ServletContextEvent sce) --> The servlet container calls this method to notify the listener that the servlet context has been created and the application is ready to process requests.

void contextDestroyed(ServletContextEvent sce) --> The servlet container calls this method to notify the listener that the application is about to be shut down.

ServletContext getServletContext() --> The servlet container creates a

javax.servlet.ServletContextEvent object that is input for calls to ServletContextListener methods. ServletContextAttributeListener Methods, ServletContextAttributeEvent Class

The ServletContextAttributeListener interface specifies the following methods:

void attributeAdded(ServletContextAttributeEvent scae) --> The servlet container calls this method to notify the listener that an attribute was added to the servlet context.

void attributeRemoved(ServletContextAttributeEvent scae)--> The servlet container calls this method to notify the listener that an attribute was removed from the servlet context. void attributeReplaced(ServletContextAttributeEvent scae) --> The servlet container calls this method to notify the listener that an attribute was replaced in the servlet context. The container creates a javax.servlet.ServletContextAttributeEvent object that is input for calls to ServletContextAttributeListener methods. The ServletContextAttributeEvent class includes the following methods, which your listener can call:

String getName() --> Use this to get the name of the attribute that was added, removed, or replaced.

Object getValue() --> Use this to get the value of the attribute that was added, removed, or replaced. In the case of an attribute that was replaced, this method returns the old value, not the new value.

HttpSessionListener Methods, HttpSessionEvent Class The HttpSessionListener interface specifies the following methods:

void sessionCreated(HttpSessionEvent hse) --> The servlet container calls this method to notify the listener that a session was created.

void sessionDestroyed(HttpSessionEvent hse) --> The servlet container calls this method to notify the listener that a session was destroyed.

The container creates a javax.servlet.http.HttpSessionEvent object that is input for calls to HttpSessionListener methods. The HttpSessionEvent class includes the following method, which your listener can call:

HttpSession getSession() --> Use this to retrieve the session object that was created or

destroyed, from which you can obtain information as desired. See HttpSessionAttributeListener Methods, HttpSessionBindingEvent Class

The HttpSessionAttributeListener interface specifies the following methods:

void attributeAdded(HttpSessionBindingEvent hsbe) --> The servlet container calls this method to notify the listener that an attribute was added to the session.

void attributeRemoved(HttpSessionBindingEvent hsbe) --> The servlet container calls this method to notify the listener that an attribute was removed from the session.

In document Java Book Latest (Page 63-76)