Posts

Showing posts with the label Advanced Java Programming

Write a program to read ID, Name, address, salary of twenty employees from keyboard and write in into the file “emp.doc”. Again read records of the employees and display records of those students whose salary is more than 25000.

   //Employee.java import java.io.RandomAccessFile; import java.util.Scanner; public class Employee { private int id; private String name; private String address; private double salary; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public static void main(String []args) { final int size = 20; int i; Employee e[] = new Employee[size]; Scanner sc = new Scanner(System.in); int id; String n; String a; double s; //setting student objects for(i=0; i<size; i++) { e[i] = new Employee(); System.out.println("Enter id of emp "+(i+1)+":"); id = sc.nextInt(); System.out.println("Enter name:"); n = sc.next(); System.out.pri

How can we access database with servlets?

DATABASE ACCESS WITH SERVLETS Database access with servlets is the same as JDBC. Only the difference is that we have a mysql-connector.jar file in the WEB-INF directory inside our root directory. Example //login.html file <html> <head> <Title> login page </Title> </head> <body> <br><br> <font color=blue size=12> <center> User Authentication page </center></font> <hr color=red size=3> <br><br> <br> <form action="Login" method="post"> <center> <table> <tr> <td> User ID </td> <td> <input type=text name=txtid></td></tr> <tr> <td> Password </td> <td> <input type=password name=txtpass></td></tr> <tr> <td colspan=2 align=center> <input type=submit value=OK> <input type=reset></td></tr> </table> </form> </body> </html> /

Explain getParameterNames() method with example.

 Reading Form Parameters Following is the generic example which uses getParameterNames() method of HttpServletRequest to read all the available form parameters. This method returns an Enumeration that contains the parameter names in an unspecified order. Once we have an Enumeration, we can loop down the Enumeration in the standard manner, using has MoreElements() method to determine when to stop and using nextElement() method to get each parameter name. Example //ReadParams.html file <html> <body> <form action="ReadParams" method="POST" target="_blank"> <input type="checkbox" name="maths" checked="checked"/> Maths <input type="checkbox" name="physics" /> Physics <input type="checkbox" name="chemistry" checked="checked" />Chem <input type="submit" value="Select Subject" /> </form> </body> </html> //R

Explain three ways to create the servlets? How can we write servlets program.

 Writing Servlets Program There are three ways to create the servlet 1. By implementing the Servlet interface 2. By inheriting the GenericServlet class 3. By inheriting the HttpServlet class 1. Servlet Interface Servlet interface provides common behavior to all the servlets. Servlet interface needs to be implemented for creating any servlet (either directly or indirectly). It provides 3 life cycle methods that are used to initialize the servlet, to service the requests, and to destroy the servlet and 2 non-life cycle methods that are used to get servlet information and servlet configurations. Example import java.io.*; import javax.servlet.*; public class ServletInt implements Servlet { ServletConfig config=null; public void init(ServletConfig config) { this.config=config; System.out.println("servlet is initialized"); } public void service(ServletRequest req, ServletResponse res) throws IOException, ServletException { res.setContentType("text/html"); Printwriter out=

Short note on RMI VS COBRA.

Image
                           

Short note on Servlet API.

 Servlet API Two packages javax.servlet and javax.servlet.http contains the classes and interfaces that are required to build servlet. These two packages constitute the servlet API and these are not part of the core packages. Therefore they are not included in Java Software Development Kit (JSDK). The javax.servlet package contains a number of interfaces and classes that establish the framework in which servlets operate.   -  Interfaces defined in javax.servlet package: Servlet, ServletConfig, ServletContext, ServletRequest, ServletResponse   - Classes in javax.servlet packages: GenericServlet, ServletInputStream, ServletOutputStream, ServletException b) The javax.servlet.http package contains a number of interfaces and classes that are commonly used by servlet developers. Its functionality is to make easy to build servlets that work with HTTP requests and responses.         -  Interfaces used in javax.servlet.http package: HttpServletRequest, HttpServletResponse, HttpSession        

Write a simple JSP program to display "Lalitpur, Nepal" 10 times.

 Solution <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/htm; charset=UTF-8"> <title> JSP program to display "Lalitpur, Nepal" 10 times</title> </head> <body> <h1>Displaying "Lalitpur, Nepal" 10 times!!</h1> <table> <% for(int i=1;i<=10; i++){ %> <tr><td> Lalitpur, Nepal</td></tr> <%} %> </table> </body> </html>

Write a simple JSP program to display "Kathmandu, Nepal" 10 times

 <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/htm; charset=UTF-8"> <title> JSP program to display "Kathmandu, Nepal" 10 times</title> </head> <body> <h1> Displaying "Kathmandu, Nepal" 10 times!!</h1> <table> <% for(int i=1;i<=10; i++){ %> <tr><td> Kathmandu, Nepal</td></tr> <%} %> </table> </body> </html>

What is JSP? Discuss with suitable example.

Image
JavaServer Pages simplify the delivery of dynamic Web content. They enable Web application programmers to create dynamic content by reusing predefined components and by interacting with components using server-side scripting. Custom-tag libraries are a powerful feature of JSP that allows Java developers to hide complex code for database access and other useful services for dynamic Web pages in custom tags. Web sites use these custom tags like any other Web page element to take advantage of the more complex functionality hidden by the tag. Thus, Web-page designers who are not familiar with Java can enhance Web pages with powerful dynamic content and processing capabilities. The classes and interfaces that are specific to JavaServer Pages programming are located in packages:- javax.servlet.jsp and javax.servlet.jsp.tagext. A Simple JSP Example JSP expression inserting the date and time into a Web page. //test.jsp <html> <head> <meta http-equiv = "refresh" content

How can we access database using JSP?

 We also access database by using JSP. All JDBC APIs can be accessed from JSP. We have put all codes related to database access within the expression tag. //addbook.html File <html> <head> <Title> E-book Store </Title> </head> <body> <br><center> <h2>Adding New Book</h2> <hr color=blue size=3> <form action="addbook.jsp" method="post"> <table> <tr> <td> ISBN </td> <td><input type=text name=ISBN></td> </tr> <tr> <td> Book Title </td> <td><input type=text name=title></td> </tr> <tr> <td> Authors</td></tr <td><input type=text name=authors></td> </tr>. <tr> <td> Price </td> <td><input type=text name=price></td> </tr> <tr> <td> Publisher </td> <td><input type=text name=pub></td> </tr> &

Explain JSP session tracking with example.

 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. By default, JSPs have session tracking enabled and a new HttpSession object is instantiated for each new client automatically. Disabling session tracking requires explicitly turning it off by setting the page directive session attribute to false as follows: <%@ page session="false" %> Example //index.html File <html> <body> <form action="welcome.jsp"> <input type="text" name="uname"> <input type="submit" value="go"><br/> </form> </body> </html> // welcome.jsp File <html> <body> <% String name=request.getParameter("uname"); out.print("Welcome "+name); session.setAttribute("user", name); %> <a href="second.jsp">second jsp page</a> </body>

Explain different Java Web Frameworks.

 INTRODUCTION TO JAVA WEB FRAMEWORKS Frameworks are large bodies of pre-written code to which you add your own code in order to solve a problem. You make use of a framework by calling its methods, inheritance, and supplying callbacks, listeners, or other implementations of the patterns. A framework will often dictate the structure of an application. Some frameworks even supply so much code that you have to do very little to write your application. Three major java web frameworks are briefly discussed below. Struts: Struts is a Java-based open-sourced framework that helps in developing web application in J2EE. It extends the Java Servlet API and promotes the Model, View, Controller (MVC) architecture. This makes the web applications developed in standard technologies like JSP, JavaBeans, and XML, more maintainable, extensible,and flexible. The framework is designed to streamline the full development cycle, from building, to deploying, to maintaining applications over time. Struts provid

What is meant by Java Bean? How it can be used in JSP scripts? Also Explain jsp:useBean, jsp:setProperty and jsp:getProperty Explain with suitable example.

 JAVA BEANS IN JSP JavaBeans components are Java classes that can be easily reused and composed together into applications. Any Java class that follows certain design conventions is a JavaBeans component. Following are the unique characteristics that distinguish a JavaBean from other Java classes: - It must provide a default, no-argument constructor. - It should be serializable and implement the Serializable interface. It may have a number of properties which can be read or written. - It may have a number of "getter" and "setter" methods for the properties. JavaServer Pages technology directly supports using JavaBeans components with standard JSP language elements. We can easily create and initialize beans and get and set the values of their properties. a) jsp:useBean The use Bean action declares a JavaBean for use in a JSP. Once declared, the bean becomes a scripting variable that can be accessed by both scripting elements and other custom tags used in the JSP. The

How exceptions can be handled in JSP scripts? Explain with suitable JSP script.

 EXCEPTION HANDLING IN JSP An exception is normally an object that is thrown at runtime. Exception Handling is the process to handle runtime errors. There may occur exceptions at any time in our web application. So handling exceptions is a safer side for the web developer. YR gives us an option to specify the Error Page for each JSP. Whenever the page throws an exception, the P container automatically invokes the error page. As we know, the exception is an implicit object of type Throwable class. This object can be used to print the exception. But it can only be used in error pages. To set up an error page, use the <%@ page errorPagexxxp' %> directive. Example //index.jsp File <form action="process.jsp"> <table> <tr> <td>First Number</td> <td><input type="text" name="n1" /></td> </tr> <tr> <td>Second Number</td> <td><input type="text" name="n2" /&

What is meant by scope of JSP objects? Explain different scopes of JSP objects briefly with example.

Image
 SCOPE OF JSP OBJECTS The availability of a JSP object for use from a particular place of the application is defined as the scope of that JSP object. Every object created on a JSP page will have a scope. Object scope in JSP is segregated into four parts and they are page, request, session, and application. a) Page Scope- page scope means, the JSP object can be accessed only from within the same page where it was created. JSP implicit objects out, exception, response, pageContext, config and page have page scope. //Example of JSP Page Scope <jsp:useBean id="employee" class="EmployeeBean" scope="page" /> b) Request Scope- A JSP object created using the request scope can be accessed from any pages that serves that request. More than one page can serve a single request. Implicit object request has the request scope. //Example of JSP Request Scope <jsp:useBean id="employee" class="EmployeeBean" scope="request" /> c) Ses

List the different tags available in JSP. Explain each of the tag with brief description and syntax.

  JSP SYNTAX There are five main tags that all together form JSP syntax. These tags are: Declaration tags, Expression tags, Directive tags, Scriptlet tags, and Action tags. 1 Declaration tag (<%! %>) This tag allows the developer to declare variables or methods. Before the declaration, we must have <%! and at the end of the declaration, we must have %>. Statements placed in this tag must end with a semicolon. Declarations do not generate output so are used with JSP expressions or scriptlets. Example <%! private int counter = 0; private String getAccount( int accountNo); %> %>) 2. Expression tag (<%=  %>) This tag allows the developer to embed any Java expression. It is the short hand form of statement "out.println(" written in servlets. A semicolon should not appear at the end of the statements wriiten inside the tag. For example, to show the current date and time, we can write Date <%= new java.util.Date() %> 3. Directive tag (<%@ directiv

What is meant by JSP implicit objects? Explain different implicit objects provided by JSP briefly.

 JSP IMPLICIT OBJECTS There are several objects that are automatically available in JSP called implicit objects. These objects are available to developers on each page and developers can call them directly without being explicitly declared. JSP Implicit Objects are also called pre-defined variables. There are nine implicit objects defined in JSP container. These objects are described below: out an object- This object is used for writing any data to the buffer. It is the object of the Print Writer class. request object- This is the object of HttpServletRequest class. This object is normally used in looking up parameter values and cookies. response object- This is the object of HttpServletResponse class. Through this object, the JSP programmer can add new cookies or date stamps, HTTP status codes, etc. config object- The config object is an instantiation of ServletConfig class. This object can be used to get an initialization parameter for a particular JSP page. exception object- excepti

Explain JSP access model with suitable diagram.

Image
JSP Access Model When a user goes to a website that is developed by using JSP and tries to access the JSP page by using a web browser, the following steps are performed to process the request and return the result to the user:  1. User sends JSP request to the Web server through a web browser to the webserver with JSP engine. 2.  The Web server recognizes that the file required is a JSP file, therefore passing the JSP file to the JSP Engine. 3. If the JSP file has been called the first time, the JSP file is parsed, otherwise, go to step 5. The JSP engine generates a special servlet file from the JSP file. 4. The servlet file is compiled into an executable class file. JSP engine then forwards the original request to a servlet engine and the servlet is instantiated. 5. The servlet engine loads the servlet class and executes it by calling init and service methods. During execution, the servlet produces an output in HTML format, which is passed to an HTTP response. 6. The web server forwar

Explain advantages of JSP over other server side scripting languages.

 Advantages of JSP over other Technologies Active Server Pages (ASP): ASP is a Microsoft technology. The dynamic part of JSP is written in Java, so it is more powerful and easier to use. Secondly, JSP is platform-independent whereas ASP is not.  Pure Servlets: It is more convenient to write regular HTML than to have println statements that generate HTML. Allows separation of look from the content. In a JSP web designers can design web page separately and servlet programmers can insert the dynamic content separately.  Server-Side Includes (SSI): SSI has widely supported technology for including externally defined pieces into a static web page. JSP is better because it lets you use servlets instead of a separate program to generate that dynamic part. Besides, SSI is really only intended for simple inclusions, not for real programs that use form data, make the database connections.  JavaScript: JavaScript can generate HTML dynamically on the client. However, it can only access the clie

Explain Advantages of JSP over Servlets

Image
 Advantages of JSP over Servlets Servlets use printIn statements for printing an HTML document which is usually very difficult to use. JSP has no such tedious task to maintain. JSP needs no compilation, CLASSPATH setting, and packaging. In a JSP page, visual content and logic are separated, which is not possible in a servlet. There is the automatic deployment of a JSP, recompilation is done automatically when changes are made to JSP pages. Usually, with JSP, Java Beans, and custom tags web application is simplified.                      OR, Advantages of JSP over Servlet There are many advantages of JSP over Servlet. They are as follows: 1) Extension to Servlet JSP technology is an extension of Servlet technology. We can use all the features of the Servlet in JSP. In addition, we can use implicit objects, predefined tags, expression language, and Custom tags in JSP, which makes JSP development easy. 2) Easy to maintain JSP can be easily managed because we can easily separate our busine