Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Servlets. Introduction Servlet is a language to develop the server side applications, and it is also server side component. It can develop.

Similar presentations


Presentation on theme: "Introduction to Servlets. Introduction Servlet is a language to develop the server side applications, and it is also server side component. It can develop."— Presentation transcript:

1 Introduction to Servlets

2 Introduction Servlet is a language to develop the server side applications, and it is also server side component. It can develop web-based applications, and it is provide component-based platform independent methods. Servlet is a server as well as platform independent. It gives a freedom to you for selecting your server, platforms and tools. Web developers can create fast and efficient web based applications using by servlet.

3 HTTP Servlet HTTP Servlet is a base class of servlet program; it is used to dynamic content. HTML submitted data to store the process. The dynamic content getting the result of a database and returning to the client, and manage the information of the stateless HTTP. Hyper Text Markup Language (HTML) is the describe inside of web documents Hypertext Transfer Protocol (HTTP) is the language used to describe how documents are sent over the internet.

4 Servlets role in J2EE

5 Life cycle of Servlet

6

7 Advantages of Java Servlets Portability Servlets are written in java and follow well known standardized APIs so they are highly portable across operating systems and server implementations.They are write once, run anywhere (WORA) program. Powerful Servlets can talk directly to the web server while the CGI programs can't do. Servlets can share data among each other, they even make the database connection pools easy to implement. They can maintain the session by using the session tracking mechanism which helps them to maintain information from request to request. Efficiency When the servlet get loaded in the server, it remains in the server's memory as a single object instance. However with servlets there are N threads but only a single copy of the servlet class. Multiple concurrent requests are handled by separate threads so we can say that the servlets are highly scalable.

8 Advantages of Java Servlets Safety As servlets are written in java, servlets inherit the strong type safety of java language. Java's automatic garbage collection and a lack of pointers means that servlets are generally safe from memory management problems. In servlets we can easily handle the errors due to Java's exception handling mechanism. If any exception occurs then it will throw an exception. Integration Servlets are tightly integrated with the server. Servlet can use the server to translate the file paths, perform logging, check authorization, and MIME type mapping etc. Extensibility The servlet API is designed in such a way that it can be easily extensible. The servlet API support Http Servlets, but in later date it can be extended for another type of servlets. Inexpensive There are number of free web servers available for personal use or for commercial purpose. Web servers are relatively expensive. So by using the free available web servers you can add servlet support to it.

9 Simple Example import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class DisplayingDate extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ PrintWriter pw = response.getWriter(); Date today = new Date(); pw.println(" "+" Today Date is "); pw.println(" "+ today+" "+ " "); } }

10 HTTP Request HTTP: Hypertext Transfer Protocol is the language used to describe how the documents are sent over the internet. HTTP recommends the rules by which browser make request and servers provide response. This rules or protocol includes, – Document name – Data format – User name – Decide handle outdated resources – Indicate the request

11 HTTP request mode Basic HTTP Client and Server Communication A key consideration is this model is stateless After a TCP connection is created, the client request and server response is communicated. Client Request: The HTTP client sends a request message formatted by the rules of the HTTP standard an HTTP request. Information provided to be provided to the server. Server Response: server received the clients request and interprets the request. It takes action on the client request and server creates an HTTP response message and sends back to client. If request was successful the response message

12 The HttpServletRequest class getParameter() getParameterValues() getParameterNames() getParameterMap().

13 getParameter() This method is used to get the client request parameter It is returns the value of a request parameter as a String value. HTTP Servlet parameter are contained in the query string or posted form data. While client request only one at a time, method can be get the parameter string. This method cannot get more than one parameter value.

14 getParameterValues() This method is used to get the parameter values from the client request. It is return an array of string objects. If the string values are null the parameter does not exist. This method can get more than one parameter and its value also. The String objects containing all of the values the given request parameter If the parameter return single value the array values is one.

15 getParameterNames() This method is used to get the request parameter and return the string objects name This method derived the Enumeration class. The string objects containing the parameters name contained in this request. If the request has no parameters, the method returns a null/empty Enumeration.

16 getParameterMap(). This method derived Map class, this method returns parameter values as map values using by parameter name as key. The parameter name has the key of type as String, and the parameter map values type as String array.

17 Attribute in Servlet An attribute in servlet is an object that can be set, get or removed from one of the following scopes: request scope session scope application scope The servlet programmer can pass informations from one servlet to another using attributes. It is just like passing object from one class to another so that we can reuse the same object again and again.

18 Attribute specific methods There are following 4 attribute specific methods. public void setAttribute(String name,Object object):sets the given object in the application scope. public Object getAttribute(String name):Returns the attribute for the specified name. public Enumeration getInitParameterNames():Returns the names of the context's initialization parameters as an Enumeration of String objects. public void removeAttribute(String name):Removes the attribute with the given name from the servlet context.

19 import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class DemoServlet1 extends HttpServlet{ public void doGet(HttpServletRequest req,HttpServletResponse res) { try{ res.setContentType("text/html"); PrintWriter out=res.getWriter(); ServletContext context=getServletContext(); context.setAttribute("company","IBM"); out.println("Welcome to first servlet"); out.println(" visit "); out.close(); }catch(Exception e){out.println(e);} }}

20 SendRedirect in servlet The sendRedirect() method of HttpServletResponse interface can be used to redirect response to another resource, it may be servlet, jsp or html file. It accepts relative as well as absolute URL. It works at client side because it uses the url bar of the browser to make another request. So, it can work inside and outside the server.

21 Difference between forward() and sendRedirect() method forward() methodsendRedirect() method The forward() method works at server side. The sendRedirect() method works at client side. It sends the same request and response objects to another servlet. It always sends a new request. It can work within the server only. It can be used within and outside the server. Example: request.getRequestDispacher("servlet2").forward(request,response); Example: response.sendRedirect("servlet2");

22 import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class DemoServlet extends HttpServlet{ public void doGet(HttpServletRequest req,HttpServlet Response res) throws ServletException,IOException { res.setContentType("text/html"); PrintWriter pw=res.getWriter(); response.sendRedirect("http://www.google.com"); pw.close(); }}

23 Output

24

25 Session Tracking Http is a stateless protocol- means that it can't persist the information. It always treats each request as a new request. In Http client makes a connection to the server, sends the request., gets the response, and closes the connection. In session management client first make a request for any servlet or any page The container receives the request and generate a unique session ID and gives it back to the client along with the response. This ID gets stores on the client machine

26 Ways of Session Tracking Hidden Form Fields: This is one of the way to support the session tracking. The hidden form field are sent back to the server when the form is submitted. In hidden form fields the html entry will be like this :. In this session ID information would be embedded within the form as a hidden field and submitted with the Http POST command.

27 URL Rewriting: URLRewriting can be used in place where we don't want to use cookies. It is used to maintain the session. Whenever the browser sends a request then it is always interpreted as a new request because http protocol is a stateless protocol as it is not persistent. In session tracking firstly a session object is created when the first request goes to the server. Then server creates a token which will be used to maintain the session. The token is transmitted to the client by the response object and gets stored on the client machine. By default the server creates a cookie and the cookie get stored on the client machine.

28 Cookies: When cookie based session management is used, a token is generated which contains user's information, is sent to the browser by the server. The cookie is sent back to the server when the user sends a new request. By this cookie, the server is able to identify the user. Cookie is nothing but a name- value pair, which is stored on the client machine. By default the cookie is implemented in most of the browsers. If we want then we can also disable the cookie. For security reasons, cookie based session management uses two types of cookies.

29 Session Example import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class CheckingTheSession extends HttpServlet{ protected void doGet(HttpServletRequest request, HttpServlet Response response)throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("Checking whether the session is new or old "); HttpSession session = request.getSession(); if(session.isNew()){ pw.println("You have created a new session"); } else{ pw.println("Session already exists"); } } }

30 Get Session ID import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SessionIdServlet extends HttpServlet{ protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{ response.setContentType("text/html"); PrintWriter pw = response.getWriter(); HttpSession session = request.getSession(); String id = session.getId(); pw.println("Session Id is : " + id); } }

31 import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class CounterServlet extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(true); response.setContentType("text/html"); PrintWriter out = response.getWriter(); Integer count = new Integer(0); String head; if (session.isNew()) { head = "This is the New Session"; } else { head = "This is the old Session"; Integer oldcount =(Integer)session.getValue("count"); if (oldcount != null) { count = new Integer(oldcount.intValue() + 1); } } session.putValue("count", count); out.println(" \n" + " " + head + " \n" + " \n” + " \ n" +" Information Type Session Count\n“ +" \n" +" Total Sessio n Accesses\n" + " " + count + "\n" + " \n" +" " ); } }

32 Cookie Introduction Cookies are small pieces of information that are sent in response from the web server to the client. Cookiesare the simplest technique used for storing client state. Cookies are stored on client's computer. They have a lifespan and are destroyed by the client browser at the end of that lifespan.

33 Cookies API Cookies are created using Cookie class present in Servlet API. Cookies are added to response object using the addCookie() method. This method sends cookie information over the HTTP response stream. getCookies() method is used to access the cookies that are added to response object.

34 Cookies API

35 Cookie Example

36 index.html Name: Password:

37 MyServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class MyServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String name = request.getParameter("user"); String pass = request.getParameter("pass"); if(pass.equals("1234")) { Cookie ck = new Cookie("username",name); response.addCookie(ck); response.sendRedirect("First"); } } }

38 First.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class First extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF- 8"); PrintWriter out = response.getWriter(); Cookie[] cks = request.getCookies(); out.println("Welcome "+cks[0].getValue()); } }

39 Registration form in Servlet

40 Create a Table in your Database create table Student ( name varchar(60), email varchar(60), pass varchar(100) ) Index.html Register form Name: Email ID: Password:

41 Register.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; public class Register extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String name = request.getParameter("name"); String email = request.getParameter("email"); String pass = request.getParameter("pass"); try{ Class.forName("com.mysql.jdbc.Driver"); con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","username","pas sword"); PreparedStatement ps=con.prepareStatement ("insert into Student values(?,?,?)"); ps.setString(1, name); ps.setString(2, email); ps.setString(3, pass); int i=ps.executeUpdate(); if(i>0) { out.println("You are sucessfully registered"); } } catch(Exception se) { se.printStackTrace(); } } }


Download ppt "Introduction to Servlets. Introduction Servlet is a language to develop the server side applications, and it is also server side component. It can develop."

Similar presentations


Ads by Google