Summary

This document provides notes on advanced Java topics, specifically focusing on JavaServer Pages (JSP). It covers JSP architecture, life cycle, tags, and their roles. The document also details advantages and disadvantages of JSP over Servlets.

Full Transcript

Basic JSP Architecture, Life Cycle of JSP (Translation, compilation), JSP Tags and Expressions Role of JSP in MVC-2 JSP with Database, JSP Implicit Objects Tag Libraries, JSP Expression Language (EL) Using Custom Tag JSP Capabilities, Exception Handling Session Management, Directives JSP with Java B...

Basic JSP Architecture, Life Cycle of JSP (Translation, compilation), JSP Tags and Expressions Role of JSP in MVC-2 JSP with Database, JSP Implicit Objects Tag Libraries, JSP Expression Language (EL) Using Custom Tag JSP Capabilities, Exception Handling Session Management, Directives JSP with Java Bean JSP JSP technology is used to create web application just like Servlet technology. It can be thought of as an extension to Servlet because it provides more functionality than servlet such as expression language, JSTL, etc. A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain than Servlet because we can separate designing and development. It provides some additional features such as Expression Language, Custom Tags, etc. Advantages of JSP over Servlet There are many advantages of JSP over the Servlet. They are as follows: 1) Extension to Servlet JSP technology is the extension to Servlet technology. We can use all the features of the Servlet in JSP. In addition to, we can use implicit objects, predefined tags, expression language and Custom tags in JSP, that makes JSP development easy. 2) Easy to maintain JSP can be easily managed because we can easily separate our business logic with presentation logic. In Servlet technology, we mix our business logic with the presentation logic. 3) Fast Development: No need to recompile and redeploy If JSP page is modified, we don't need to recompile and redeploy the project. The Servlet code needs to be updated and recompiled if we have to change the look and feel of the application. 4) Less code than Servlet In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that reduces the code. Moreover, we can use EL, implicit objects, etc. The Lifecycle of a JSP Page The JSP pages follow these phases: o Translation of JSP Page o Compilation of JSP Page o Classloading (the classloader loads class file) o Instantiation (Object of the Generated Servlet is created). o Initialization ( the container invokes jspInit() method). o Request processing ( the container invokes _jspService() method). o Destroy ( the container invokes jspDestroy() method). As depicted in the above diagram, JSP page is translated into Servlet by the help of JSP translator. The JSP translator is a part of the web server which is responsible for translating the JSP page into Servlet. After that, Servlet page is compiled by the compiler and gets converted into the class file. Moreover, all the processes that happen in Servlet are performed on JSP later like initialization, committing response to the browser and destroy. Creating a simple JSP Page To create the first JSP page, write some HTML code as given below, and save it by.jsp extension. We have saved this file as index.jsp. Put it in a folder and paste the folder in the web-apps directory in apache tomcat to run the JSP page. index.jsp Let's see the simple example of JSP where we are using the scriptlet tag to put Java code in the JSP page. We will learn scriptlet tag later. 1. 2. 3. 4. 5. It will print 10 on the browser. How to run a simple JSP Page? Follow the following steps to execute this JSP page: o Start the server o Put the JSP file in a folder and deploy on the server o Visit the browser by the URL http://localhost:portno/contextRoot/jspfile, for example, http://localhost:8888/myapplication/index.jsp Do I need to follow the directory structure to run a simple JSP? No, there is no need of directory structure if you don't have class files or TLD files. For example, put JSP files in a folder directly and deploy that folder. It will be running fine. However, if you are using Bean class, Servlet or TLD file, the directory structure is required. The Directory structure of JSP The directory structure of JSP page is same as Servlet. We contain the JSP page outside the WEB-INF folder or in any directory. The JSP API The JSP API consists of two packages: 1. javax.servlet.jsp 2. javax.servlet.jsp.tagext javax.servlet.jsp package The javax.servlet.jsp package has two interfaces and classes.The two interfaces are as follows: 1. JspPage 2. HttpJspPage The classes are as follows: o JspWriter o PageContext o JspFactory o JspEngineInfo o JspException o JspError The JspPage interface According to the JSP specification, all the generated servlet classes must implement the JspPage interface. It extends the Servlet interface. It provides two life cycle methods. Methods of JspPage interface 1. public void jspInit(): It is invoked only once during the life cycle of the JSP when JSP page is requested firstly. It is used to perform initialization. It is same as the init() method of Servlet interface. 2. public void jspDestroy(): It is invoked only once during the life cycle of the JSP before the JSP page is destroyed. It can be used to perform some clean up operation. The HttpJspPage interface The HttpJspPage interface provides the one life cycle method of JSP. It extends the JspPage interface. Method of HttpJspPage interface: 1. public void _jspService(): It is invoked each time when request for the JSP page comes to the container. It is used to process the request. The underscore _ signifies that you cannot override this method. JSP Scriptlet tag (Scripting elements) In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's see what are the scripting elements first. JSP Scripting elements The scripting elements provides the ability to insert java code inside the jsp. There are three types of scripting elements: o scriptlet tag o expression tag o declaration tag JSP scriptlet tag A scriptlet tag is used to execute java source code in JSP. Syntax is as follows: 1. Example of JSP scriptlet tag In this example, we are displaying a welcome message. 1. 2. 3. 4. 5. Example of JSP scriptlet tag that prints the user name In this example, we have created two files index.html and welcome.jsp. The index.html file gets the username from the user and the welcome.jsp file prints the username with the welcome message. File: index.html 1. 2. 3. 4. 5. 6. 7. 8. File: welcome.jsp 1. 2. 3. 7. 8. 9. JSP expression tag The code placed within JSP expression tag is written to the output stream of the response. So you need not write out.print() to write data. It is mainly used to print the values of variable or method. Syntax of JSP expression tag 1. Example of JSP expression tag In this example of jsp expression tag, we are simply displaying a welcome message. 1. 2. 3. 4. 5. Note: Do not end your statement with semicolon in case of expression tag. Example of JSP expression tag that prints current time To display the current time, we have used the getTime() method of Calendar class. The getTime() is an instance method of Calendar class, so we have called it after getting the instance of Calendar class by the getInstance() method. index.jsp 1. 2. 3. Current Time: 4. 5. Example of JSP expression tag that prints the user name In this example, we are printing the username using the expression tag. The index.html file gets the username and sends the request to the welcome.jsp file, which displays the username. File: index.jsp 1. 2. 3. 4. 5. 6. 7. 8. File: welcome.jsp 1. 2. 3. 4. 5. JSP Declaration Tag The JSP declaration tag is used to declare fields and methods. The code written inside the jsp declaration tag is placed outside the service() method of auto generated servlet. So it doesn't get memory at each request. Syntax of JSP declaration tag The syntax of the declaration tag is as follows: 1. Difference between JSP Scriptlet tag and Declaration tag Jsp Scriptlet Tag Jsp Declaration Tag The jsp scriptlet tag can only declare variables The jsp declaration tag can declare variables as well not methods. as methods. The declaration of scriptlet tag is placed inside The declaration of jsp declaration tag is placed the _jspService() method. outside the _jspService() method. Example of JSP declaration tag that declares field In this example of JSP declaration tag, we are declaring the field and printing the value of the declared field using the jsp expression tag. index.jsp 1. 2. 3. 4. 5. 6. Example of JSP declaration tag that declares method In this example of JSP declaration tag, we are defining the method which returns the cube of given number and calling this method from the jsp expression tag. But we can also use jsp scriptlet tag to call the declared method. index.jsp 1. 2. 3. 8. 9. 10. JSP Implicit Objects  There are 9 jsp implicit objects. These objects are created by the web container that are available to all the jsp pages.  The available implicit objects are out, request, config, session, application etc.  A list of the 9 implicit objects is given below: Object Type out JspWriter request HttpServletRequest response HttpServletResponse config ServletConfig application ServletContext session HttpSession pageContext PageContext page Object exception Throwable 1) JSP out implicit object For writing any data to the buffer, JSP provides an implicit object named out. It is the object of JspWriter. In case of servlet you need to write: 1. PrintWriter out=response.getWriter(); But in JSP, you don't need to write this code. Example of out implicit object In this example we are simply displaying date and time. index.jsp 1. 2. 3. 4. 5. Output JSP request implicit object The JSP request is an implicit object of type HttpServletRequest i.e. created for each jsp request by the web container. It can be used to get request information such as parameter, header information, remote address, server name, server port, content type, character encoding etc. It can also be used to set, get and remove attributes from the jsp request scope. Let's see the simple example of request implicit object where we are printing the name of the user with welcome message. Example of JSP request implicit object index.html 1. 2. 3. 4. welcome.jsp 1. Output 3) JSP response implicit object In JSP, response is an implicit object of type HttpServletResponse. The instance of HttpServletResponse is created by the web container for each jsp request. It can be used to add or manipulate response such as redirect response to another resource, send error etc. Let's see the example of response implicit object where we are redirecting the response to the Google. Example of response implicit object index.html 1. 2. 3. 4. welcome.jsp 1. Output 4) JSP config implicit object In JSP, config is an implicit object of type ServletConfig. This object can be used to get initialization parameter for a particular JSP page. The config object is created by the web container for each jsp page. Generally, it is used to get initialization parameter from the web.xml file. Example of config implicit object: index.html 1. 2. 3. 4. web.xml file 1. 2. 3. sonoojaiswal 4. /welcome.jsp 5. 6. dname 7. sun.jdbc.odbc.JdbcOdbcDriver 8. 9. 10. 11. sonoojaiswal 12. /welcome 13. 14. welcome.jsp 1. Output 5) JSP application implicit object In JSP, application is an implicit object of type ServletContext. The instance of ServletContext is created only once by the web container when application or project is deployed on the server. This object can be used to get initialization parameter from configuaration file (web.xml). It can also be used to get, set or remove attribute from the application scope. This initialization parameter can be used by all jsp pages. Example of application implicit object: index.html 1. 2. 3. 4. web.xml file 1. 2. 3. 4. sonoojaiswal 5. /welcome.jsp 6. 7. 8. 9. sonoojaiswal 10. /welcome 11. 12. 13. 14. dname 15. sun.jdbc.odbc.JdbcOdbcDriver 16. 17. 18. welcome.jsp 1. Output 6) session implicit object In JSP, session is an implicit object of type HttpSession.The Java developer can use this object to set,get or remove attribute or to get session information. Example of session implicit object index.html 1. 2. 3. 4. 5. 6. 7. 8. welcome.jsp 1. 2. 3. 9. 10. second.jsp 1. 2. 3. 7. 8. Output 7) pageContext implicit object In JSP, pageContext is an implicit object of type PageContext class.The pageContext object can be used to set,get or remove attribute from one of the following scopes: o page o request o session o application In JSP, page scope is the default scope. Example of pageContext implicit object index.html 1. 2. 3. 4. 5. 6. 7. 8. welcome.jsp 1. 2. 3. 12. 13. second.jsp 1. 2. 3. 9. 10. Output 8) page implicit object: In JSP, page is an implicit object of type Object class.This object is assigned to the reference of auto generated servlet class. It is written as: Object page=this; For using this object it must be cast to Servlet type.For example: Since, it is of type Object it is less used because you can use this object directly in jsp.For example: 9) exception implicit object In JSP, exception is an implicit object of type java.lang.Throwable class. This object can be used to print the exception. But it can only be used in error pages.It is better to learn it after page directive. Let's see a simple example: Example of exception implicit object: error.jsp 1. 2. 3. 4. 5. Sorry following exception occured: 6. 7. 8. JSP directives The jsp directives are messages that tells the web container how to translate a JSP page into the corresponding servlet. There are three types of directives:  page directive  include directive  taglib directive Syntax of JSP Directive 1. JSP page directive The page directive defines attributes that apply to an entire JSP page. Syntax of JSP page directive 1. Attributes of JSP page directive 1. import 2. contentType 3. extends 4. info 5. buffer 6. language 7. isELIgnored 8. isThreadSafe 9. autoFlush 10. session 11. pageEncoding 12. errorPage 13. isErrorPage 1)import The import attribute is used to import class,interface or all the members of a package.It is similar to import keyword in java class or interface. Example of import attribute 1. 2. 3. 4. 5. Today is: 6. 7. 8. 2)contentType The contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type of the HTTP response.The default value is "text/html;charset=ISO-8859-1". Example of contentType attribute 1. 2. 3. 4. 5. Today is: 6. 7. 8. 3)extends The extends attribute defines the parent class that will be inherited by the generated servlet.It is rarely used. 4)info This attribute simply sets the information of the JSP page which is retrieved later by using getServletInfo() method of Servlet interface. Example of info attribute 1. 2. 3. 4. 5. Today is: 6. 7. 8. The web container will create a method getServletInfo() in the resulting servlet.For example: 1. public String getServletInfo() { 2. return "composed by Sonoo Jaiswal"; 3. } 5)buffer The buffer attribute sets the buffer size in kilobytes to handle output generated by the JSP page.The default size of the buffer is 8Kb. Example of buffer attribute 1. 2. 3. 4. 5. Today is: 6. 7. 8. 6)language The language attribute specifies the scripting language used in the JSP page. The default value is "java". 7)isELIgnored We can ignore the Expression Language (EL) in jsp by the isELIgnored attribute. By default its value is false i.e. Expression Language is enabled by default. We see Expression Language later. 1. //Now EL will be ignored 8)isThreadSafe Servlet and JSP both are multithreaded.If you want to control this behaviour of JSP page, you can use isThreadSafe attribute of page directive.The value of isThreadSafe value is true.If you make it false, the web container will serialize the multiple requests, i.e. it will wait until the JSP finishes responding to a request before passing another request to it.If you make the value of isThreadSafe attribute like: The web container in such a case, will generate the servlet as: 1. public class SimplePage_jsp extends HttpJspBase 2. implements SingleThreadModel{ 3........ 4. } 9)errorPage The errorPage attribute is used to define the error page, if exception occurs in the current page, it will be redirected to the error page. Example of errorPage attribute 1. //index.jsp 2. 3. 4. 5. 6. 7. 8. 9. 10. 10)isErrorPage The isErrorPage attribute is used to declare that the current page is the error page. Note: The exception object can only be used in the error page. Example of isErrorPage attribute 1. //myerrorpage.jsp 2. 3. 4. 5. 6. 7. Sorry an exception occured! 8. The exception is: 9. 10. 11. Jsp Include Directive The include directive is used to include the contents of any resource it may be jsp file, html file or text file. The include directive includes the original content of the included resource at page translation time (the jsp page is translated only once so it will be better to include static resource). Advantage of Include directive Code Reusability Syntax of include directive 1. Example of include directive In this example, we are including the content of the header.html file. To run this example you must create an header.html file. 1. 2. 3. 4. 5. 6. Today is: 7. 8. 9. Note: The include directive includes the original content, so the actual page size grows at runtime. JSP Taglib directive The JSP taglib directive is used to define a tag library that defines many tags. We use the TLD (Tag Library Descriptor) file to define the tags. In the custom tag section we will use this tag so it will be better to learn it in custom tag. Syntax JSP Taglib directive 1. Example of JSP Taglib directive In this example, we are using our tag named currentDate. To use this tag we must specify the taglib directive so the container may get information about the tag. 1. 2. 3. 4. 5. 6. 7. 8. 9. Exception Handling in JSP The exception is normally an object that is thrown at runtime. Exception Handling is the process to handle the runtime errors. There may occur exception any time in your web application. So handling exceptions is a safer side for the web developer. In JSP, there are two ways to perform exception handling: 1. By errorPage and isErrorPage attributes of page directive 2. By element in web.xml file Example of exception handling in jsp by the elements of page directive In this case, you must define and create a page to handle the exceptions, as in the error.jsp page. The pages where may occur exception, define the errorPage attribute of page directive, as in the process.jsp page. There are 3 files:  index.jsp for input values  process.jsp for dividing the two numbers and displaying the result  error.jsp for handling the exception index.jsp 1. 2. No1: 3. No1: 4. 5. process.jsp 1. 2. error.jsp 1. 2. 3. Sorry an exception occured! 4. 5. Exception is: Output of this example: Example of exception handling in jsp by specifying the error-page element in web.xml file This approach is better because you don't need to specify the errorPage attribute in each jsp page. Specifying the single entry in the web.xml file will handle the exception. In this case, either specify exception-type or error-code with the location element. If you want to handle all the exception, you will have to specify the java.lang.Exception in the exception-type element. Let's see the simple example: There are 4 files:  web.xml file for specifying the error-page element  index.jsp for input values  process.jsp for dividing the two numbers and displaying the result  error.jsp for displaying the exception 1) web.xml file if you want to handle any exception 1. 2. 3. 4. java.lang.Exception 5. /error.jsp 6. 7. 8. This approach is better if you want to handle any exception. If you know any specific error code and you want to handle that exception, specify the error-code element instead of exception-type as given below: 1) web.xml file if you want to handle the exception for a specific error code 1. 2. 3. 4. 500 5. /error.jsp 6. 7. 8. 2) index.jsp file is same as in the above example 3) process.jsp Now, you don't need to specify the errorPage attribute of page directive in the jsp page. 1. 2. 4) error.jsp file is same as in the above example JSP Action Tags There are many JSP action tags or elements. Each JSP action tag is used to perform some specific tasks. The action tags are used to control the flow between pages and to use Java Bean. The Jsp action tags are given below. JSP Action Tags Description jsp:forward forwards the request and response to another resource. jsp:include includes another resource. jsp:useBean creates or locates bean object. jsp:setProperty sets the value of property in bean object. jsp:getProperty prints the value of property of the bean. jsp:plugin embeds another components such as applet. jsp:param sets the parameter value. It is used in forward and include mostly. jsp:fallback can be used to print the message if plugin is working. It is used in jsp:plugin. The jsp:useBean, jsp:setProperty and jsp:getProperty tags are used for bean development. So we will see these tags in bean developement. jsp:forward action tag The jsp:forward action tag is used to forward the request to another resource it may be jsp, html or another resource. Syntax of jsp:forward action tag without parameter 1. Syntax of jsp:forward action tag with parameter 1. 2. 3. Example of jsp:forward action tag without parameter In this example, we are simply forwarding the request to the printdate.jsp file. index.jsp 1. 2. 3. this is index page 4. 5. 6. 7. printdate.jsp 1. 2. 3. 4. 5. Example of jsp:forward action tag with parameter In this example, we are forwarding the request to the printdate.jsp file with parameter and printdate.jsp file prints the parameter value with date and time. index.jsp 1. 2. 3. this is index page 4. 5. 6. 7. 8. 9. 10. printdate.jsp 1. 2. 3. 4. 5. 6. 7. 8. jsp:include action tag The jsp:include action tag is used to include the content of another resource it may be jsp, html or servlet. The jsp include action tag includes the resource at request time so it is better for dynamic pages because there might be changes in future. The jsp:include tag can be used to include static as well as dynamic pages. Advantage of jsp:include action tag Code reusability : We can use a page many times such as including header and footer pages in all pages. So it saves a lot of time. Difference between jsp include directive and include action JSP include directive JSP include action includes resource at translation time. includes resource at request time. better for static pages. better for dynamic pages. includes the original content in the generated servlet. calls the include method. Syntax of jsp:include action tag without parameter 1. Syntax of jsp:include action tag with parameter 1. 2. 3. Example of jsp:include action tag without parameter In this example, index.jsp file includes the content of the printdate.jsp file. File: index.jsp 1. this is index page 2. 3. 4. 5. end section of index page File: printdate.jsp 1. JavaBean In any programming language, reusability is the main concern. To achieve the same concern, Java introduced the concept of JavaBean. It is a software component that has been designed to be reusable in a variety of environments. In this section, we will dive into the topic and understand the horizons of concept in this what is JavaBeans, its advantages, disadvantages, Life cycle. In other words, JavaBeans are classes that encapsulate multiple objects into a single object. It also helps in accessing these object from multiple places. It contains several elements like Constructors, getter and setter methods and much more. A JavaBean is a Java class that should follow the following conventions: o Class Definition: They are defined as public classes. o Serializability (Optional): While not mandatory, they often implement the Serializable interface to allow object data to be converted into a stream of bytes for storage or transmission. o No-argument Constructor: JavaBeans must have a public constructor that takes no arguments (often called a no-arg constructor). It simplifies object creation. o Data Encapsulation: They encapsulate data using private member variables (fields) to store the object's state. o Getter and Setter Methods: For each private field, there should be a corresponding public getter and setter method: o Getter methods (usually prefixed with get or is for booleans) retrieve the value of a field. o Setter methods (usually prefixed with set) modify the value of a field. Why use JavaBean? According to Java white paper, it is a reusable software component. A bean encapsulates many objects into one object so that we can access this object from multiple places. Moreover, it provides easy maintenance. Simple Example of JavaBean Class File Name: Employee.java 1. //Employee.java 2. 3. package mypack; 4. public class Employee implements java.io.Serializable{ 5. private int id; 6. private String name; 7. public Employee(){} 8. public void setId(int id){this.id=id;} 9. public int getId(){return id;} 10. public void setName(String name){this.name=name;} 11. public String getName(){return name;} 12. } How to access the JavaBean class? To access the JavaBean class, we should use getter and setter methods. File Name: Test.java 1. package mypack; 2. public class Test{ 3. public static void main(String args[]){ 4. Employee e=new Employee();//object is created 5. e.setName("Arjun");//setting value to the object 6. System.out.println(e.getName()); 7. }} Note: There are two ways to provide values to the object. One way is by constructor and second is by setter method. JavaBean Properties A JavaBean property is a named feature that can be accessed by the user of the object. The feature can be of any Java data type, containing the classes that you define. A JavaBean property may be read, write, read-only, or write-only. JavaBean features are accessed through two methods in the JavaBean's implementation class: Properties of setter Methods 1. It must be public in nature. 2. The return type a should be void. 3. The setter method uses prefix set. 4. It should take some argument. Properties of getter Methods 1. It must be public in nature. 2. The return type should not be void. 3. The getter method uses prefix get. 4. It does not take any argument. For Boolean properties getter method name can be prefixed with either "get" or "is". But recommended to use "is". 1. getPropertyName() For example, if the property name is firstName, the method name would be getFirstName() to read that property. This method is called the accessor. File Name: PropertyNameFinder.java 1. import java.lang.reflect.Field; 2. // Class to find the property name of an object that holds a given value 3. public class PropertyNameFinder { 4. // Method to return the name of the property whose value matches the given value 5. public static String getPropertyName(Object obj, Object value) { 6. // Loop through all declared fields of the object's class 7. for (Field field : obj.getClass().getDeclaredFields()) { 8. // Make the field accessible, allowing access to private fields 9. field.setAccessible(true); 10. try { 11. // Check if the current field's value is equal to the provided value 12. if (field.get(obj).equals(value)) { 13. // Return the name of the field if the value matches 14. return field.getName(); 15. } 16. } catch (IllegalAccessException e) { 17. // Handle the exception if the field is not accessible 18. System.out.println("Access to the field was denied."); 19. } catch (NullPointerException e) { 20. // Handle the case where the field's value is null to avoid crashing the program 21. System.out.println("A field value was null."); 22. } 23. } 24. // Return null if no matching field is found 25. return null; 26. } 27. // Main method to test the getPropertyName method 28. public static void main(String[] args) { 29. // Create an instance of Person 30. Person person = new Person("John Doe", 30); 31. // Try to find the field name that has the value "John Doe" 32. String fieldName = getPropertyName(person, "John Doe"); 33. // Print the result, expected to be "name" 34. System.out.println(fieldName); // Outputs: name 35. // Try to find the field name that has the value 30 36. fieldName = getPropertyName(person, 30); 37. // Print the result, expected to be "age" 38. System.out.println(fieldName); // Outputs: age 39. } 40. // Nested static class Person with private fields 41. static class Person { 42. private String name; 43. private int age; 44. // Constructor to set the name and age of the person 45. public Person(String name, int age) { 46. this.name = name; 47. this.age = age; 48. } 49. } 50. } Output: name age 2. setPropertyName() For example, if the property name is firstName, the method name would be setFirstName() to write that property. This method is called the mutator. File Name: PropertySetter.java 1. import java.lang.reflect.Field; 2. public class PropertySetter { 3. // Method to set the property of an object based on the property name and the value p rovided 4. public static void setPropertyName(Object obj, String propertyName, Object value) { 5. try { 6. // Retrieve the Field object for the specified property from the class of the provide d object 7. Field field = obj.getClass().getDeclaredField(propertyName); 8. // Make the field accessible, even if it is private or protected 9. field.setAccessible(true); 10. // Check if the value is compatible with the field type before setting it 11. if (isCompatible(value, field.getType())) { 12. // Set the field's value for the given object to the specified value 13. field.set(obj, value); 14. } else { 15. // Throw an exception if the value is not compatible with the field type 16. throw new IllegalArgumentException("Incompatible value type provided."); 17. } 18. } catch (NoSuchFieldException e) { 19. // Handle case where the field does not exist in the object 20. System.out.println("Field not found: " + propertyName); 21. } catch (IllegalAccessException e) { 22. // Handle case where the field is inaccessible or final 23. System.out.println("Failed to access or modify the field: " + propertyName); 24. } catch (IllegalArgumentException e) { 25. // Handle other illegal argument issues, such as type incompatibility 26. System.out.println(e.getMessage()); 27. } 28. } 29. // Helper method to check if the provided value is compatible with the field's type 30. private static boolean isCompatible(Object value, Class type) { 31. // Check if value is null (null can be assigned to any non-primitive field) 32. if (value == null) return true; 33. // Check if the value instance matches the field's type or its wrapper class 34. return type.isInstance(value) || (type.isPrimitive() && wrap(type).isInstance(value)); 35. } 36. // Method to wrap primitive types in their corresponding wrapper classes 37. private static Class wrap(Class type) { 38. // Return the wrapper class for int types 39. if (type == int.class) return Integer.class; 40. // Return the wrapper class for double types 41. else if (type == double.class) return Double.class; 42. // Add more primitives if necessary 43. // Return the original type if it's not a primitive needing wrapping 44. return type; 45. } 46. \ public static void main(String[] args) { 47. // Create a new Person object 48. Person person = new Person("John Doe", 30); 49. // Display the person's name before modification 50. System.out.println("Before: " + person.getName()); 51. // Change the person's name using the setPropertyName method 52. setPropertyName(person, "name", "Jane Doe"); 53. // Display the person's name after modification 54. System.out.println("After: " + person.getName()); // Should output: Jane Doe 55. } 56. // Person class with private fields and a constructor 57. static class Person { 58. private String name; 59. private int age; 60. public Person(String name, int age) { 61. this.name = name; 62. this.age = age; 63. } 64. // Getter method for the name field 65. public String getName() { 66. return name; 67. } 68. } 69. } Output: Before: John Doe After: Jane Doe Advantages of JavaBean The following are the advantages of JavaBean: o It is portable, compact, and easy. o The JavaBean properties and methods can be exposed to another application. o It provides an easiness to reuse the software components. Disadvantages of JavaBean The following are the disadvantages of JavaBean: o JavaBeans are mutable. So, it cannot take advantages of immutable objects. o Creating the setter and getter method for each property separately may lead to the boilerplate code. Benefits of Using Beans in Java JavaBeans are a component model in Java, designed to encapsulate many objects into a single object (the bean). They are serializable, have a zero-argument constructor, and allow access to properties using getter and setter methods. The JavaBeans model is a standard for developing and using reusable software components. Here are some of the primary benefits of using JavaBeans: 1. Reusability: JavaBeans are designed with reusability in mind. Once a bean is created, it can be used across different applications. It allows developers to build upon existing components rather than starting from scratch, significantly speeding up the development process. 2. Encapsulation: JavaBeans encapsulate many objects into one, hiding the internal complexity of individual components from other parts of the program. Encapsulation helps in managing complexity by exposing only necessary parts of the functionality. 3. Ease of Use: It can be manipulated visually in a builder tool. Most IDEs support JavaBeans by providing features like dragging and dropping beans into applications, which makes it easier for non-programmers or developers to build applications. 4. Integration and Flexibility: JavaBeans can be integrated into different environments and can communicate with other components provided these components adhere to the Beans' conventions. This flexibility also extends to their capability to operate across different operating systems and platforms. 5. Customization: JavaBeans can be customized easily using property editors and customizers. It allows other developers and software tools to configure a bean to fit their specific environment. 6. Persistence: JavaBeans can be made persistent, meaning their state can be saved to and restored from storage, without the need for the application to understand the beans' internals. This persistence is facilitated by the Serializable interface. 7. Security: Beans provide a security framework that supports features like signing, constraints, and role-based authorization, which can be critical for applications that require high security. 8. Interoperability: Since JavaBeans components are written in Java, they are inherently interoperable with Java applications. However, with appropriate adapters, JavaBeans can also be made to work with components written in other languages, promoting cross-platform interaction. Life Cycle of Java Beans The life cycle of a JavaBean refers to the various stages it goes through from instantiation to destruction. Understanding these stages is crucial for effective bean management, especially in environments where beans are used extensively, such as Java EE or when beans are managed by containers in frameworks like Spring. Here's a detailed look at the typical life cycle of a JavaBean: 1. Instantiation The first stage in the life cycle of a JavaBean is instantiation. During this stage, the JavaBean is created, usually by calling a no-argument constructor. It is a simple creation step where the bean is allocated memory and its initial state is set up. 2. Customization (Optional) After a bean is instantiated, it may undergo customization. It involves configuring the bean's properties and other settings to suit specific needs. Customization typically happens in two ways: o Design Time: Using tools such as IDEs where beans can be configured using property sheets. o Runtime: Programmatically setting properties through setter methods or configuration files (XML, JSON, etc.). 3. Setting Property Values Once the bean is customized, its properties are set. It is often done through setter methods defined in the bean. Property values can be set directly by the application that uses the bean, or by a framework or container that manages the bean. 4. Connection with Other Beans JavaBeans can be connected to other beans. It can involve setting up event listeners and event sources, allowing beans to respond to events triggered by other beans. This step is crucial for the bean to interact within an application or environment, supporting the event-driven programming model. 5. Activation (Optional) For beans that are serialized and later restored, the activation stage involves restoring the bean from its serialized state. Activation may involve re-establishing transient connections or resources that were not saved during serialization. 6. Introspection Introspection is a process where the capabilities of a bean are examined dynamically. Tools and frameworks can inspect a bean to determine its properties, events, and methods. This allows for dynamic configuration and interaction with the bean. 7. Running During this stage, the bean is in use and performing its intended tasks. It may handle data processing, respond to user input, or interact with other components and beans. This phase is generally where the bean spends most of its lifecycle. 8. Passivation (Optional) In environments where beans are managed (like EJB containers), passivation is a stage where a bean's state is temporarily stored to free resources. It usually happens when the bean is not currently needed, but its state needs to be preserved for later activation. 9. Destruction The final stage in the lifecycle of a JavaBean is its destruction. Here, the bean is marked for garbage collection, and any resources it used are released. Before destruction, cleanup methods can be called to ensure that all resources are freed properly, such as closing database connections or releasing file handles. jsp:useBean action tag The jsp:useBean action tag is used to locate or instantiate a bean class. If bean object of the Bean class is already created, it doesn't create the bean depending on the scope. But if object of bean is not created, it instantiates the bean. Syntax of jsp:useBean action tag 1. 4. Attributes and Usage of jsp:useBean action tag 1. id: is used to identify the bean in the specified scope. 2. scope: represents the scope of the bean. It may be page, request, session or application. The default scope is page. o page: specifies that you can use this bean within the JSP page. The default scope is page. o request: specifies that you can use this bean from any JSP page that processes the same request. It has wider scope than page. o session: specifies that you can use this bean from any JSP page in the same session whether processes the same request or not. It has wider scope than request. o application: specifies that you can use this bean from any JSP page in the same application. It has wider scope than session. 3. class: instantiates the specified bean class (i.e. creates an object of the bean class) but it must have no-arg or no constructor and must not be abstract. 4. type: provides the bean a data type if the bean already exists in the scope. It is mainly used with class or beanName attribute. If you use it without class or beanName, no bean is instantiated. 5. beanName: instantiates the bean using the java.beans.Beans.instantiate() method. Simple example of jsp:useBean action tag In this example, we are simply invoking the method of the Bean class. For the example of setProperty, getProperty and useBean tags, visit next page. Calculator.java (a simple Bean class) 1. package com.javatpoint; 2. public class Calculator{ 3. 4. public int cube(int n){return n*n*n;} 5. 6. } index.jsp file 1. 2. 3. download this example jsp:setProperty and jsp:getProperty action tags The setProperty and getProperty action tags are used for developing web application with Java Bean. In web devlopment, bean class is mostly used because it is a reusable software component that represents data. The jsp:setProperty action tag sets a property value or values in a bean using the setter method. Syntax of jsp:setProperty action tag 1. Example of jsp:setProperty action tag if you have to set all the values of incoming request in the bean 1. Example of jsp:setProperty action tag if you have to set value of the incoming specific property 1. Example of jsp:setProperty action tag if you have to set a specific value in the property 1. jsp:getProperty action tag The jsp:getProperty action tag returns the value of the property. Syntax of jsp:getProperty action tag 1. Simple example of jsp:getProperty action tag 1. Example of bean development in JSP In this example there are 3 pages:  index.html for input of values  welocme.jsp file that sets the incoming values to the bean object and prints the one value  User.java bean class that have setter and getter methods index.html 1. 2. Name: 3. Password: 4. Email: 5. 6. process.jsp 1. 2. 3. 4. Record: 5. 6. 7. User.java 1. package org.sssit; 2. 3. public class User { 4. private String name,password,email; 5. //setters and getters 6. } download this example Reusing Bean in Multiple Jsp Pages Let's see the simple example, that prints the data of bean object in two jsp pages. index.jsp Same as above. User.java Same as above. process.jsp 1. 2. 3. 4. Record: 5. 6. 7. 8. 9. Visit Page second.jsp 1. 2. Record: 3. 4. 5. Using variable value in setProperty tag In some case, you may get some value from the database, that is to be set in the bean object, in such case, you need to use expression tag. For example: process.jsp 1. 2. 5. 6. 7. Record: 8. Displaying applet in JSP (jsp:plugin action tag) The jsp:plugin action tag is used to embed applet in the jsp file. The jsp:plugin action tag downloads plugin at client side to execute an applet or bean. Syntax of jsp:plugin action tag 1. = lt le gt ge == != eq ne && and || or ?: Reserve words in EL There are many reserve words in the Expression Language. They are as follows: lt le gt ge eq ne true false and or not instanceof div mod empty null MVC in JSP MVC stands for Model View and Controller. It is a design pattern that separates the business logic, presentation logic and data. Controller acts as an interface between View and Model. Controller intercepts all the incoming requests. Model represents the state of the application i.e. data. It can also have business logic. View represents the presentaion i.e. UI(User Interface). Advantage of MVC (Model 2) Architecture 1. Navigation Control is centralized 2. Easy to maintain the large application If you new to MVC, please visit Model1 vs Model2 first. MVC Example in JSP In this example, we are using servlet as a controller, jsp as a view component, Java Bean class as a model. In this example, we have created 5 pages:  index.jsp a page that gets input from the user.  ControllerServlet.java a servlet that acts as a controller.  login-success.jsp and login-error.jsp files acts as view components.  web.xml file for mapping the servlet. File: index.jsp 1. 2. Name: 3. Password: 4. 5. File: ControllerServlet 1. package com.javatpoint; 2. import java.io.IOException; 3. import java.io.PrintWriter; 4. import javax.servlet.RequestDispatcher; 5. import javax.servlet.ServletException; 6. import javax.servlet.http.HttpServlet; 7. import javax.servlet.http.HttpServletRequest; 8. import javax.servlet.http.HttpServletResponse; 9. public class ControllerServlet extends HttpServlet { 10. protected void doPost(HttpServletRequest request, HttpServletResponse response) 11. throws ServletException, IOException { 12. response.setContentType("text/html"); 13. PrintWriter out=response.getWriter(); 14. 15. String name=request.getParameter("name"); 16. String password=request.getParameter("password"); 17. 18. LoginBean bean=new LoginBean(); 19. bean.setName(name); 20. bean.setPassword(password); 21. request.setAttribute("bean",bean); 22. 23. boolean status=bean.validate(); 24. 25. if(status){ 26. RequestDispatcher rd=request.getRequestDispatcher("login-success.jsp"); 27. rd.forward(request, response); 28. } 29. else{ 30. RequestDispatcher rd=request.getRequestDispatcher("login-error.jsp"); 31. rd.forward(request, response); 32. } 33. 34. } 35. 36. @Override 37. protected void doGet(HttpServletRequest req, HttpServletResponse resp) 38. throws ServletException, IOException { 39. doPost(req, resp); 40. } 41. } File: LoginBean.java 1. package com.javatpoint; 2. public class LoginBean { 3. private String name,password; 4. 5. public String getName() { 6. return name; 7. } 8. public void setName(String name) { 9. this.name = name; 10. } 11. public String getPassword() { 12. return password; 13. } 14. public void setPassword(String password) { 15. this.password = password; 16. } 17. public boolean validate(){ 18. if(password.equals("admin")){ 19. return true; 20. } 21. else{ 22. return false; 23. } 24. } 25. } File: login-success.jsp 1. 2. 3. You are successfully logged in! 4. File: login-error.jsp 1. Sorry! username or password error 2. File: web.xml 1. 2. 6. 7. 8. s1 9. com.javatpoint.ControllerServlet 10. 11. 12. s1 13. /ControllerServlet 14. 15. download this example (developed using eclipse IDE) Output JSTL (JSP Standard Tag Library) The JSP Standard Tag Library (JSTL) represents a set of tags to simplify the JSP development. Advantage of JSTL 1. Fast Development JSTL provides many tags that simplify the JSP. 2. Code Reusability We can use the JSTL tags on various pages. 3. No need to use scriptlet tag It avoids the use of scriptlet tag. JSTL Tags There JSTL mainly provides five types of tags: Tag Name Description The JSTL core tag provide variable support, URL management, flow control, etc. The URL for the core Core tags tag is http://java.sun.com/jsp/jstl/core. The prefix of core tag is c. The functions tags provide support for string manipulation and string length. The URL for the Function tags functions tags is http://java.sun.com/jsp/jstl/functions and prefix is fn. The Formatting tags provide support for message Formatting tags formatting, number and date formatting, etc. The URL for the Formatting tags is http://java.sun.com/jsp/jstl/fmt and prefix is fmt. The XML tags provide flow control, transformation, XML tags etc. The URL for the XML tags is http://java.sun.com/jsp/jstl/xml and prefix is x. The JSTL SQL tags provide SQL support. The URL SQL tags for the SQL tags is http://java.sun.com/jsp/jstl/sql and prefix is sql. For creating JSTL application, you need to load the jstl.jar file. Download the jstl.jar file Download the jstl1.2.jar file JSTL Index JSTL Tutorial o JSTL Tutorial JSTL Core Tags o 14 JSTL Core Tags o 1) c:out o 2) c:import o 3) c:set o 4) c:remove o 5) c:catch o 6) c:if o 7) c:choose o 8) c:when o 9) c:otherwise o 10) c:forEach o 11) c:forTokens o 12) c:param o 13) c:redirect o 14) c:url JSTL Function Tags o 15 JSTL Function Tags o 1) fn:contains() o 2) fn:containsIgnore.. o 3) fn:endsWith() o 4) fn:escapeXml() o 5) fn:indexOf() o 6) fn:trim() o 7) fn:startsWith() o 8) fn:split() o 9) fn:toLowerCase() o 10) fn:toUpperCase() o 11) fn:substring() o 12) fn:substringAfter() o 13) fn:substringBefore() o 14) fn:length() o 15) fn:replace() JSTL Formatting Tags o 9 JSTL Formatting Tags o 1) fmt:parseNumber o 2) fmt:timeZone o 3) fmt:formatNumber o 4) fmt:parseDate o 5) fmt:bundle o 6) fmt:setTimeZone o 7) fmt:setBundle o 8) fmt:message o 9) fmt:formatDate JSTL XML Tags o 9 JSTL XML Tags o 1) x:out o 2) x:parse o 3) x:set o 4) x:choose o 5) x:when o 6) x:otherwise o 7) x:if o 8) x:transform o 9) x:param JSTL SQL Tags o 6 JSTL SQL Tags o 1) sql:setDataSource o 2) sql:query o 3) sql:update o 4) sql:param o 5) sql:dateParam o 6) sql:transaction JSTL Core Tags The JSTL core tag provides variable support, URL management, flow control etc. The syntax used for including JSTL core library in your JSP is: 1. JSTL Core Tags List Tags Description It display the result of an expression, similar to the way c:out tag work. It Retrives relative or an absolute URL and display the contents to c:import either a String in 'var',a Reader in 'varReader' or the page. It sets the result of an expression under evaluation in a 'scope' c:set variable. It is used for removing the specified scoped variable from a c:remove particular scope. It is used for Catches any Throwable exceptions that occurs in the c:catch body. It is conditional tag used for testing the condition and display the c:if body content only if the expression evaluates is true. It is the simple conditional tag that includes its body content if the c:choose, c:when, c:otherwise evaluated condition is true. It is the basic iteration tag. It repeats the nested body content for c:forEach fixed number of times or over collection. It iterates over tokens which is separated by the supplied c:forTokens delimeters. c:param It adds a parameter in a containing 'import' tag's URL. It redirects the browser to a new URL and supports the context- c:redirect relative URLs. c:url It creates a URL with optional query parameters. JSTL Core Tag The tag is similar to JSP expression tag, but it can only be used with expression. It will display the result of an expression, similar to the way < %=...% > work. The < c:out > tag automatically escape the XML tags. Hence they aren't evaluated as actual tags. Let's see the simple example of c:out tag: 1. 2. 3. 4. Tag Example 5. 6. 7. 8. 9. Output: 1. Welcome to javaTpoint JSTL Core Tag The is similar to jsp 'include', with an additional feature of including the content of any resource either within server or outside the server. This tag provides all the functionality of the action and it also allows the inclusion of absolute URLs. For example: Using an import tag the content from a different FTP server and website can be accessed. Let's see the simple example of c:import tag: 1. 2. 3. 4. Tag Example 5. 6. 7. 8. 9. 10. Above example would fetch the complete content from javatpoint.com and would store in a variable "data" which will printed eventually.

Use Quizgecko on...
Browser
Browser