Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Unit-IV 1 Cookies Http is a stateless- every HTTP request is different from others. It is necessary to keep track of related requests sent by a client to 2 perform some task-called “SESSION TRACKING” Cookies are one of the solution for session tracking. A cookies is a key-value pair created by the server and installed in clients browser , when the client makes a request for the first time. Browser also maintains a list of cookies installed in them and send them to the server as a part of HTTP request. The server can easily identified that this request is a part of sequence of related request.-solution Cookies contd... A servlet API also supports cookies. A cookies is represented using the javax.servlet.http.cookie class and is created using the following constructor. Cookies(String key, String value) 3 4 public class SessionTrack extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); HttpSession hs = request.getSession(true); Date date = (Date)hs.getValue("date"); if(date != null) out.println("Last access :"+date+"<br>"); date = new Date(); hs.putValue("date", date); out.println("Current date :"+date); } } public class AddCookie extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ response.setContentType("text/html"); String data = request.getParameter("data"); response.addCookie(new Cookie("MyCookie",data)); Cookie[] cookies = request.getCookies(); PrintWriter out = response.getWriter(); out.println("Found following cookies :<br>"); for(int i=0;i<cookies.length;i++) { out.println("name: "+cookies[i].getName()); out.println("value: "+cookies[i].getValue()+"<br>"); } out.println("<br>Cookie has been sent to "+data); } } 5 Limitations of cookies Cookies carry small piece of information Not standard way of communication Some browsers limit the number of cookies that can be installed The value of a cookie should never exceed 4KB. Cookies cannot identify a particular user. As cookies cannot differentiate between multiple browsers running in a single computer. Intruders can snoop, steal cookies and attack sessions-session hijacking 6 Filters Filters are objects that are installed between the client and the server to inspect requests and responses. Filters are not servlets and hence cannot create actual responses. Filters process requests before they reach a servlet and/or process responses after leaving a servlet. A filter can do the following intercept and inspect requests before dispatching them to servlets. Modify requests headers and data and discard or filter requests Intercept and inspect responses before dispatching them to clients Modify requests headers and data and discad or filter responses. 7 Filters contd... A filter class must implement the javax.servlet.filters interface, which provides a framework for filtering mechanism. void init(FilterConfig config) The filterconfig interface defines methods to retrieve the filters name, its init parameters and underlying servlet context. Void defiler(ServletRequest request, ServletResponse response, FilterChain chain) If the filter decides, it may not forward request to the next filter, filters can drop malicious intended for the servlet Void destroy() 8 Deploying filter To use this filter, you must specify it in the web.xml file using the <filter> tag. <filter> <filter-name>MyFirewall</filter-name> <filter-class>Firewall</filter-class> This notifies the server that a filter named MyFirewall is implemented in the Firewall class. Add the following lines in the web.xml <filter-mapping> <filter-name>myFirewall</filter-name> <url-pattern>/HelloWorld</url-pattern> </filter-mapping> 9 Problems with servlet Servlets are not usefull for generating presentation content such as 10 HTML. it is acceptable if you want to generate smaller HTML files. However, if the size of the HTML document is large, it is tedious process to generate it. Another drawback of the servlet over JavaSeverPages(JSP) is that you have to recompile the code yourself after any modification is done. However, the web server has to be restarted to get the effect of the modified code. Whereas JSP can perform this task autoamatically Servlets often contain presentation logic as well as processing logic, which makes the code difficult to read. Security issues Before installing servlets in the web server, make sure that they come from trusted sources. The concept of “sandbox” may be incorporated. A sandbox is a container of servlets where restrictions are imposed. The administrator of the web server decides which servlets are given which permissions In addition to these security issues, the author of the servlet should consider the following points. Take sufficient care while writting the file upload code. Review the code that accessess files/database based on the user input 11 Security issues make sure that the request comes from an authorized user. Do not rely on the existence of a session variable. Make sure that you have not used the “system.exit()” method anywhere in your program. Do not display sensitive parameter values in the web page. 12 JSP and HTTP JSP is a server-side technology that enables web programmers to generate web pages dynamically in response to client requests. JSP is nothing but high-level abstraction of Java Servlet Technology. It allows us to embed pure java code in an HTML page. JSP pages run under the supervision of an environment called “web container” The web container compiles the page on the server and generates a servlet, which is loaded in the Java Runtime Environment.(JRE) 13 JSP JSP technology provides excellent server-side programming 14 for web applications that need database access. JSP not only provides cross-web-server and cross-platform support, but also integrates the “WYSIWYG” (What You See Is What You Get) features of static HTML pages with the extreme power of java technology. JSP allows to separate the dynamic content of our web pages from the static HTML content. We can insert the java code for the dynamic parts using special tags:starts with <% and end with %> JSP file have the extension .jsp JSP and HTTP JSP specification extends the idea of java servlet API to provide a 15 robust framework to developers of web applications for creating dynamic web content. JSP or servlet technology supports only HTTP. A developer may extend the idea of JSP or servlet to implement other protocols such as FTP or SMTP. Since JSP uses HTML, XML and Java Code the applications are secure, fast and independent of server platforms. It allows us to embed pure java code in an HTML document. The life cycle and many of the capabilities especially the dynammic aspects of JSP pages are exactly the same as Java Servlet Technology. JSP Engines To process JSP pages , a JSP engine is needed JSP engine is nothing but a specialized servlet, which runs under the supervision of he servlet engine. JSP engine is typically connected with a web server or can be integrated inside a web server or an application server. Many web servers are available free- Tomcat, Java Web Server, WebLogic ad WebSphere. Once you downloaded and installed a JSP-capable web server or appllication server in your machine, you need to know where to place the JSP files and how to access them from the web browser using the URL. 16 Tomcat Download the appropriate version of Tomcat from Apache 17 site Uncompress the file in a directory Set environmental variable JAVA_HOME to point to the root directory of your JDK hierarchy. Go to the bin directory under the tomcat installation directory and start tomcat using the command line command “ startup.bat”- windows or startup.sh-Unix/Linux Tomcat is running on a default port :8080 Test it: http://IP address:8080 Java Web Server It is a leading web server that delivers secure infrastructure for medium and large business technologies and applications. Sun claims that it delivers 8* better performance than Apache 2.0 with tomcat It is available on all major operating sytems and supports a wide range of technologies such as JSP and Java Servlet technologies, PHP and CGI 18 Web logic WebLogic by BEA systems is a J2EE application server and also an 19 HTTP server for microsoft windows, Unix/Linux and other platforms. WebLogic supports DB2, Oracle, Microsoft SQL Server and other JDBC- complaint databases. WebLogic server also includes the .NET framework for interoperability and allow integration of the following native components. CORBA connectivity, COM+ Connectivity, J2EE connector Architecture, IBM’s WebSphere MQ connectivity and Native JMS messaging for enterprise. Data Mapping functionality and Business Process Management are also included in WebLogic Server process Edition WebSphere IBM attempted to develop a software to set up, operate and integrate electronic business applications that can work across multiple computing platforms, using Java-based web technologies. The result isWebSphere Application Server (WAS) It inclludes both the run-time components and the tools that can be used to develop robust and versatile applications that will run onWAS. 20 How JSP works When a client such as a web browser sends a request to a web server for a JSP file using a URL, web server identifies it as .jsp in URL and figures out that the requested resource is a Java Server Page. The web server hands over the request to a special servlet. This servlet checks whether the servlet corresponding to this JSP page exist or not. If the servlet does not exist, or exists but it is older than the JSP page, it performs the following: 21 How JSP works contd.... Translate the JSP source code into the servlet source code Compiles the servlet source code to generate a class file Loads the class file and creates an instance Intializes the servletinstances by calling the JspInit() method Invokes the _jspservice() method, passing request and response objects. • if the servlet exists and is not older than the corresponding JSP page requested, it does the following If an instance is already running, it is simply forwards the request to this instance. Otherwise, it loads the class file, creates an instance, intializes it, forwards the request to t his instance. 22 JSP and SERVLET Java Server Technology is powerful technology, when it is used to generate large, complex HTML code, it becomes a bit difficult. In most servlets, a small piece of code is a written to handle application logic and a large code is written using serveral out.println() statements that handle output formatting. JSP separates the static presentation templates from the logic,to generate the dynamic content by encapsulating it with external JavaBean components. When the presentation template is changed by the web designer, the jsp engine recompiles the JSP page and reloads it in the Java Runtime Environment (JRE) 23 JSP and Servlet Another problem of servlets is that each time the servlet code is modified, it needs to recompiled and the web server also needs to be restarted. Whenever a JSP code is modified, the JSP engine identifies it and translates it into a new servlet. The servlet code is then compiled, loaded and instantiated automatically. JSP uses technologies based on reusable component engineering engineering such as JavaBean component archiecture and Enterprise JavaBean technology For these reasons, web appication developers turn towards JSP technology as an alternative to servlet technology 24 Translation and Compilation Every JSP page gets converted to a normal servlet behind the scene by the web container automatically . 25 Translation and compilation Each type of data in a JSP page is processed differently during the 26 translation phase. The translation and compilation phase may results in error.-errors are generated when a user request the page for the first time. The JSPengine returns returns a ParseException if an error occurs during the translation phase.-servlet source file is empty or incomplete The last incomplete line describes the cause of error in the JSP page. If an error occur during compilation phase,JSP engine returns a JasperException and a message that describes the name of the JSP page servlet and the line that caused error Life Cycle of JSP servlet Three methods jspInit() jspService() jspDestroy() jspInit(): to intialize jspService(): responsible for serving the clients requests. JSP specification prohibits the overriding of the _jspService(). However the developers are allowed to override jspInit() and jspDestroy() respectively. By default, the servlet container dispatches the _jspService() method using a separate thread to process concurrent client requests. 27 Life cycle of JSP’s servlet diagram 28 Anatomy of JSP page A JSP page basically consists of two parts: HTML/XML 29 markups and JSP constructs. A large percent of JSP page consists of static HTML/XML components, known as “template text”. We can create and maintain JSP pages using traditional HTML/XML tools. We use three types of JSP constructs in a JSP page: “ scripting elements, directives and actions” Java code that will become an integral part of the resultant servlet is inserted using “scripting lements” Anatomy of JSP page Directives:control the overall structure and behaviour of the 30 generated servlet. Actions: allows us to use existing components and otherwise control the behaviour of the JSP engine. There are three types of scripting elements:”scriptlets, declarations and exxpressions” Scriplets allows us too insert any java-server-relevant API in the HML or XML page provided that the syntax is correct Declarations allows us to declare variables and methods Expressions are used to print the value of a java expressions. JSP syntax The syntax of JSP is almost similar to that of XML. All JSP tags must conform to the following rules: tags must have their matching end tags attributes must appear in the start tag attribute values in the tag must be quoted. • White spaces within the body of a JSP page are preserved during the translation phase to use special characters such as ‘%’ and ‘\’ character before it. • To use ‘\’ character use another ‘\’ before it 31 JSP components A JSP page consist of the following comoponents. 32 Directive Declarations Expressions Scriplets Actions Directives A JSP page may contain instructions to be used by the JSP container to indicate how this page is interpreted and executed.. Those instructions are called “directives”. Directives do not generate any output directly, but tells the JSP engine how to handle the JSP page. They are enclosed within <%@ and %> tags. Commonly used directives are “page, include, taglib”. 33 Syntax of page directive 34 Page directive Import: the value of this attribute is a list of fully qualified names of classes separated by commas, to be imported by the JSP file. To import all the classes of a package use “.*” at the end of the package name. <%@ page import=“java.io.*%> Session: This attribute indicates whether the JSP file requires a HTTP session. Following syntax is used session=“true | false” Buffer: buffer=“none | sizekb” The buffer attribute indicates the size in kilobytes (default is 8kb) of the output buffer to be used by the JSP file. If buffer is none then output is written directly to the output screen. 35 JSP components autoFlush: autoFlush=“true | false” The autoFlush indicates whether the buffer should be fushed automatically when it is full. If set to false, a buffer overflow exception is thrown when the buffer becomes full. Default value is true. isThreadSafe: isThreadSafe=“true | false” This attribute indicates whether the JSP page can handle multiple threads simultaneously. 36 JSP components Info: info=“text” it allows to specify a descriptive information about the JSP page. This information can be retrieved using the “ servlet.getServletInfo() method. ContentType: contentType=“MIMEType [ ; charset=characterSet]; It specifies the MIME type and encoding used in the generated response to be sent to the client. MIME types and encoding supported by the JSP container can anly be specified. The default MIME type and character encoding are text.html and ISO-8859-1 respectively. 37 JSP componets errorPage and isErrorPage: errorPage=“relativeURL” isErrorPage=“true | false” Include Directive: this directive inserts the content of a file in a JSP page, during the translation phase when the JSP page is compiled. <%@ include file=“relativeURL” %> If the file to be included is an HTML or text file, its content is directly included in the place of include directive. <%@ include file=“header.jsp” %> 38 comments Comments: Comments are used to documenet the JSP page and can beinserted anywhere in the JSP page. <%-- JSP comment --%> Anything between comments is ignored by the JSP engine and is not even added in the servlet’s source code. The java – like comments may also be used in scriptlets and a declaration. They are added to the servlet, but not interpreted and hence are not sent to the client. <% //get all cookies Cookie[] cookies=request.getcookie(); /* */ %> 39 expressions Expressions: JSP 2.0 specification includes a new feature “expressions”. It is used to insert usually a small piece of data in a JSP page, without using the out.print() or out.write() statements. <%=expressions %> 3+4=<%= 3+4 %> The expression is embeded within the pair tag. No semicolon is used at the end of the end of the expression. The expression is evalluated , converted to a string and inserted in the place of expression using an out.print() statement. 40 Scriptlets You can insert any piece of java code using the JSP Scriptlets construct in the JSP page. This code will be inserted in the servlet’s _jspService() method. Scriptlets are useful if you want to insert complex code which would otherwise difficult using expressions. A scriptlet can contain any number of variables, class declarations, expressions, or other language statements. Form of scriptlets: <% Scriptlets %> 41 Scriptlets-example The following scriptlet inserts the current date and time in the JSP page <% Java.util.Date d = new java.util.Date() Out.println(“Date and time is :” +d); %> 42 Conditional Processing Several scriptlets and templates can be merged, to do some designated task. Example: <% Int no=(int) (math.random()*10); If(no % 2 == 0) { %> Even <% } else { %> Odd <% } %> 43 Declarations JSP declarations are used to declare one or more variables, methods or inner classes, which can be used later in the JSP page. <%! Declarations %> Examples: <%! Int sum=0; %> <%! Int x,y,z; %> <%! Java.util.Hashtable table=new java.util.Hashtable(); %> JSP also has the following XML equivalent for declaration <jsp:declaration> Declarations </jsp:declarations> 44 Scope of JSP objects In a JSP page, objects may be created using directives , actions, or 45 scriptlets. Every object created in a JSP page has a scope. The scope of a JSP object is defined as the availability of the object for use from a particular place of the web application. There are four object scope: page, request,session and application Page: objects having page scope can be accessed only from the same page where they were created. Request: a request can be served by more than one page. Objects having request scope can be accessed from any page that serves the request. Session: objects having session scope are accessible from pages that belong to the same session from where they were created Application: JSP objects that have application scope can be accessed from any page that belong to the same application. Implicit Objects: web container allows us to directly access many useful objects defined in the _jspService() method of the JSP page underlying servlet. These objects are called implicit objects as they are instantiated automatically. Ref Page No: 648 table 21.2 JSP implicit objects 46 Variables,methods and classes Variables, methods and classes can be declared in JSP page. If they are declared in the declaration section, they become part of the class. For example: variables declared in the declaration section become instance variables and are accessible from any method of the JSP’s servlet class Ex: <%! Double PI=22/7.0 ; %> Synchronization: note that variables declared int the declaration section becomes instance variables. Instance variables become shared automatically among all request handling threads.You must write the code to access these variables syncronously. 47 Synchronization:example <%! Int n=1;%> <% for (int i-0; i<5; i++) { out.println(“next integer: “ +n ++ +”<br>”); Thread.sleep(500) } %> It works well for single request. If two or more requests are sent to this JSP fpage, the result is not displayed correctly. 48 Result: Next integer:1 Next integer:3 Next integer:5 Next integer:7 Next integer:9 Next integer:2 Next integer:4 Next integer:6 Next integer:8 Next integer:10 One of the solution of this problem is to make for loop atomic so that only one request can access at a time. 49 solution <%! Int n=1; Object o =new object (); %> Synchronized(0){ For (int i=0; i<5; i++) Out.println(“next integer:” + n++ +”<br>>”); Thread.sleep(500); } } %> 50 Standard actions: JSP actions are nothing but XML tags that can be used in a JSP page to use these functions Note that the same thing can be achieved by writing java code within scriptlets. JSP action tags are convinient way to use those functions The following are commonly used JPS tags Incldue: this action tag provides n alternative way to include a file in a JSP page. Syntax: <jsp:include page=“relativeURL | <%=expression%>” flush=“true”/> 51 Standard actions Param: the jsp <jsp:param> action allows us to append additional prameters to the current request <jsp:param name=“parameerName” value=“parameter Value |<%=expression%> Action: this action tag hands over the current request to the specified page internally at the server side. <jsp:forward page=“relativeURL | <%expression%> /> 52