Java defines _____ for the listener interfaces having more than one event handling methods.
- AWrapper Classes
- BAbstract Classes
- CConcrete Classes
- DAdapter Classes
Adapter classes give empty implementations of multi-method listener interfaces.
Syllabus: lectures 19–45. Past-paper MCQs are shown first.Syllabus: lecture 19–45. Past paper ki MCQs pehle dikhai gayi hain.
226 MCQs · 382 short · 98 long questions · 226 MCQs from past papers226 MCQs · 382 short · 98 long sawal · 226 MCQs past papers se
Java defines _____ for the listener interfaces having more than one event handling methods.
Adapter classes give empty implementations of multi-method listener interfaces.
Which of the following method is used to move the cursor to given row number?
absolute(int) moves the ResultSet cursor to the given row.
previous() is a method of __________ object.
previous() moves the ResultSet cursor back one row.
Which of the following is NOT a method of ResulSet object?
executeQuery() belongs to Statement, not ResultSet.
getColumnCount() is a method of ________ object.
getColumnCount() returns the number of columns from ResultSetMetaData.
isReadOnly() is a method of _________ object.
The no-argument isReadOnly() is listed in the handout under DatabaseMetaData (ResultSetMetaData has isReadOnly(int column)).
Which of the following method is used to determine whether a database is read only or not?
The DatabaseMetaData method is spelled isReadOnly().
Which of the following statement is true regarding paintComponent() method?
By default paintComponent paints the background, then the custom drawing is done.
Which of the following object is passed as an argument to paintComponent() method?
paintComponent(Graphics g) receives a Graphics object.
Which of the following method of Graphics object is used to draw rectangle?
The Graphics method is drawRect(x, y, width, height).
In an applet class definition, the----------method takes the place of the constructor.
init() is called once after the applet is created, so it does the constructor-like setup.
Which of the following method of an Applet is called every time when page is minimized?
stop() is called when the applet page is left or the browser is minimized.
Which of the following method takes the place of constructor in an Applet?
init() does the one-time setup of an applet.
Which of the following applet method is called once in applet life cycle?
init() runs once when the applet is loaded; start, paint and stop can run many times.
Which of the following is NOT true for applets?
The applet security sandbox blocks access to the client's file system.
Port is a transport address to which processes can ________ for connections request.
A server process listens on a port for connection requests.
What is not true about server socket:
A ServerSocket only listens; communication is done by the normal Socket returned by accept().
Stream is an abstraction of hard drive same as socket is an abstraction of __________.
A socket is the software abstraction of a network connection.
Which method(s) must a serializable class, implement?
Serializable is a marker interface with no methods; implementing it is enough.
The "transient" keyword is used to _______ serialization.
A transient field is not saved when the object is serialized, so transient prevents its serialization.
Which of the following directory is the top level TOMCAT directory that contains all the application deployed on web server?
Tomcat deploys each web application as a folder inside webapps.
Which of the following Environment variable tells the system about the root directory of TOMCAT?
CATALINA_HOME points to the Tomcat installation directory.
In the init(ServletConfig) method of Servlet life cycle, what method can be used to access the ServletConfig object?
getServletConfig() returns the ServletConfig object passed to init().
Which of the following method is called only once in servlet?
init() is called once when the servlet is loaded; service/doGet/doPost run for each request.
By using forward() method of _________ object, the called resource will be able to access the original request object.
RequestDispatcher.forward() passes the same request object to the called resource.
Why we use RequestDispatcher to forward a request to another resource(servlet, html, jsp), instead of using a sendRedirect()?
Forwarding needs no round trip to the client and keeps the same request object.
By using sendRedirect() method of ________ object, a new request is generated which redirects the user to called resource.
sendRedirect() is a method of HttpServletResponse.
By ________, the original request can be forwarded to the next servlet.
RequestDispatcher.forward() passes the same request on; sendRedirect() makes the browser send a new one.
Which one of the following is not a request dispatching method?
forward() and include() are both RequestDispatcher methods, so none of the options is excluded.
In which of the following format does the key in request Dispatching is stored?
request.setAttribute(String name, Object value) stores the attribute under a String key.
A bean class ___________ have any public instance variables/attributes (fields).
Bean fields should be private and reached only through getters and setters.
A bean class ___________ be serializable.
Bean conventions require the class to implement Serializable.
Which of the following is not a Java Bean class?
A JavaBean must not expose public fields; the other options are bean requirements.
JavaBean is a/an _________.
A JavaBean is a Java class that follows special conventions (no-arg constructor, private fields, getters/setters).
A bean class __________ have a zero argument constructor.
JavaBean conventions require a public no-argument constructor.
The following value of JavaBean's scope attribute has local variable.
With page scope the bean is just bound to a local variable for the current page.
JSP action elements allow us to work with _____________.
Action elements such as jsp:useBean, jsp:setProperty and jsp:getProperty work with JavaBeans.
Which of the following is a correct order for Bean scope in JSP page from most visible to least visible?
Application scope is widest, then session, then request, and page is narrowest.
Which of the following is not a correct scope when a JavaBean is used with JSP?
Bean scopes are page, request, session and application; response is not a scope.
Using the following value of JavaBean's scope attribute, the bean object is stored in ServletContext.
Application scope stores the bean in the ServletContext, shared by the whole web application.
JSP ________ action element is used to obtain a reference to an existing JavaBean object.
jsp:useBean locates an existing bean in the given scope or creates one.
The default value of scope attribute in JSP useBean action element is ___________.
If no scope is given, jsp:useBean uses page scope.
Which of the following is a correct order for Bean scope in JSP page from least visible to most visible?
Page is narrowest, then request, session, and application is widest.
From the Following; which we don't include in simple tag while creating JSP custom tags:
A simple custom tag has only a start and end tag, with no body and no attributes.
Which of the following is not included in simple tag while creating JSP custom tags?
A simple custom tag has only a start and end tag, with no body and no attributes.
Which information a Tag Library Descriptor (.tld) file specifies?
A TLD lists library and JSP versions, each tag's name, handler class and attributes.
Tiers represent the _____________ view of application.
Tiers are the physical separation of an application across machines or processes.
Layers represent the _____________ view of application.
Layers are the logical separation of an application into presentation, business and data parts.
The dot operator in Expression Language typically used for accessing the --------------------of an object.
In EL, the dot operator reads a property of an object, such as ${user.name}.
The bracket operator in Expression Language is generally used to retrieve -------------of arrays and collections.
The [] operator retrieves elements of arrays and collections; the dot operator reads properties.
From following; which is the main reason that enters a thread into dead state:
A thread becomes dead either when its run method finishes or when stop() is invoked on it.
From the following; which approach is used in java to create threads,
Threads can be made by implementing Runnable (interface) or by extending Thread (inheritance).
RPC stands for
RPC is the abbreviation of Remote Procedure Call(s).
From the following which one is not a built-in validator?
JSF provides DoubleRange, LongRange and Length validators but no StringValidator.
-------------can be used to specify dynamic attribute values for JSTL actions without using full-blown programming language.
JSTL supports the Expression Language, which gives dynamic attribute values without Java code.
The ___________ represent the state of component.
In MVC the model holds the state (data) of the component.
JSP file is compiled ___________.
A JSP is translated and compiled again only when the JSP file has been modified.
Servlet session and JSP session have ___________ abilities.
A JSP becomes a servlet, so its session handling is the same as a servlet.
Which of the following is not part of http response?
An HTTP response has a result code, header fields and a body; the URI belongs to the request.
In which file do we define a servlet mapping?
Servlet mappings are declared in the deployment descriptor web.xml.
Which of the following is a type of Java web application technologies?
JSP, JSTL and JSF are all Java web application technologies.
Extra information can be appended to URL using ____________.
URL rewriting can add extra path information, added parameters or a custom server-specific change.
Web server is a software which provides services to access _________.
A web server provides access over the Internet, an intranet or an extranet.
When defining a method you must include a ___________ to declare any exception that might be thrown but is not caught in the method.
Checked exceptions that a method does not catch must be declared in its throws clause.
DSN stands for ___________.
DSN means Data Source Name, set up for ODBC database access.
From following classes; which one can't be instantiated?
An abstract class is incomplete, so no object of it can be created.
Converting bigger data types into smaller one is called ----------
Converting a larger type to a smaller type is down casting and needs an explicit cast.
int x = 7/2; value of x is:
Integer division drops the fraction, so 7/2 gives 3.
One application has _________ servlet context(s).
Each web application has exactly one ServletContext shared by all its resources.
In packages, we organize files into different directories according to their ____________.
Packages group files into directories by functionality, usability and category.
Entire JSP page gets translated into a servlet ____________.
A JSP is translated into a servlet once (until modified), and that servlet serves each request.
MVC stands for _____________.
MVC is the Model View Controller design pattern.
Managed Bean is JavaBeans which are defined in ------------------
JSF managed beans are declared in the faces configuration file.
UDDI stands for
UDDI is Universal Description, Discovery and Integration, a registry to publish and find web services.
_____________ is a standard web based application framework.
JavaServer Faces is the standard Java web application framework.
Which of the following is a general purpose container?
JPanel is a general-purpose container; the others are top-level containers.
Which of the following component is/are used in directory Structure of web components?
A web application directory contains pages and images, WEB-INF with web.xml and classes, and lib with jar files.
AWT is also called ______________.
AWT components use native peers, so they are called heavyweight components.
Which of the following is NOT a standard method called as a part of the JSP life cycle?
The JSP life-cycle methods are jspInit(), _jspService() and jspDestroy(); jspService() does not exist.
Initialization parameters of a servlet are defined in __________ file.
Servlet init parameters are declared with <init-param> in web.xml.
The getSession() method of _________ returns HttpSession object.
request.getSession() on HttpServletRequest returns the HttpSession.
Unpack directory structure of J2EE web application is __________
The unpacked (expanded) directory form is mostly used during development; the packed WAR is used to deploy.
Servlet mapping of a servlet is defined in _____________ file.
Servlet mappings are declared in the deployment descriptor web.xml.
A --------in HashMap is associated with each object that is stored.
A HashMap stores each value with an associated key.
Which of the following must be used to compare the values of two strings?
equals() compares string contents; == compares references.
In which file do we define a servlet mapping?
Servlet mappings are declared in the deployment descriptor web.xml.
When a JSP page is compiled, what is it turned into?
A JSP page is translated into a servlet class and compiled.
From which object do you ask for DatabaseMetaData?
Connection.getMetaData() returns the DatabaseMetaData object.
Which of the following is NOT a web technology of Java?
ASP is a Microsoft technology, not a Java one.
Web.xml is a ___________
web.xml is the deployment descriptor (configuration file) of a web application.
Which of the following method call causes the currently executing thread to return to Ready state?
yield() moves the running thread back to the ready state.
Which of the following is NOT true about HTTP?
HTTP is stateless and keeps no session between requests, so option c is false.
Which of the following interface needs to implement while creating threads?
A thread task class implements Runnable and its run() method.
Which of the following method needs to override while handling threads in java?
The thread code is written by overriding run().
Which of the following range of response code signify error by server?
Status codes in the 500s mean a server error.
Which of the following method allows any other thread of same priority to execute?
yield() lets other threads of the same priority run.
HTML form data can be processed by JSP
A JSP can read form data through the request object.
From the following methods, which method cannot be overridden in the JSP page
_jspService() is generated by the container and must not be overridden.
Which of the following object is used for sharing resources among different servlets of same application?
One ServletContext is shared by all servlets of a web application.
getParameters() method returns an array of strings containing the values for a specified servlet parameter.
The method that returns all values of a parameter is getParameterValues().
setAttribute(String, Object) associates a ----------with a name.
setAttribute binds the given Object to the attribute name.
JSP technology is extensible
JSP can be extended with custom tags and tag libraries.
Packages are the way to organize files into different -------------according to their functionality, usability as well as category they should belong to.
Packages map to directories in the file system.
What is the initial contact point for handling a web request in a Page-Centric architecture?
In page-centric design the request first reaches a JSP page.
When JSP page compiled, it is translated into?
A JSP page is translated into a servlet.
From following which code can be used to create session object in the Servlet:
getSession(true) returns the session and creates one if none exists.
From the following indicators; which is added in user session to know the session time out?
The handout example class SessionTimeoutIndicator implements HttpSessionBindingListener.
From the following which ID is transmitted between the client and the server
The session ID travels in a cookie or the URL to identify the session.
To define the error page in JSP we use following tag?
Error pages are declared with the <error-page> element.
Which one is used to collect data when a user navigates between web pages?
Session tracking keeps user data across requests to different pages.
When a session object is invalidated, it can be again refreshed.
An invalidated session cannot be used again; a new session must be created.
Which of the following is NOT a part of HTTP request?
The status code belongs to the response, not the request.
Which of the following problem occurs with lower priority threads?
Lower-priority threads may starve if higher-priority ones never give up the CPU.
Which of the following folder contains configuration file?
web.xml is kept in the WEB-INF folder.
Which of the following approch is used to create threads in java?
Threads can be made by extending Thread or implementing Runnable.
Which of the following range of response code indicates that request was successful?
Status codes in the 200s mean success.
Which of the following statement object is used to execute simple SQL statement?
Statement objects run simple SQL without parameters.
Which of the following function will be used to register event handler with events generators (button)?
A button registers its listener with addActionListener().
WindowsListener interface contains ___________ methods
WindowListener has seven methods.
Servlets are used to
Servlets extend a web server to generate dynamic content.
Servlet mapping is defined in ________
Servlet mappings are declared in web.xml.
getrequest() method gets information from a client and postrequest() method posts data to a client.
There are no such methods; requests are handled by doGet() and doPost().
getAttribute(String) extracts----------- stored value from a session object
getAttribute returns a value that was stored earlier with setAttribute.
To destroy the session in Servlet we use?
invalidate() ends the session.
From the following which session tracking technique is used when new session is started?
For a new session the server sends a cookie and also encodes URLs, since it does not yet know if cookies work.
HttpServletResponse object is created when web server executes the servlet. This object is passes to the servlet service method which passes it to doGet () or doPost().
The container creates the request and response objects and passes them via service() to doGet/doPost.
Which of the following object contains information specific to a servlet?
ServletConfig holds the configuration of one servlet.
Initialization ________ of web application are also called ______________
Initialization parameters of the whole web application are kept in the ServletContext, so they are called context parameters/attributes.
The HTTP response values in the range ________ specify that the request was successful.
HTTP status codes in the 200s (e.g. 200 OK) signal success.
Web services are Web-based enterprise applications that use open, ---------- standards and transport protocols to exchange data with calling clients.
Web services exchange data in XML-based formats such as SOAP and WSDL.
Which of the following is true about concrete class?
A class becomes concrete (instantiable) only when it implements every inherited abstract method.
If a sub class overrides all abstract methods of super class then it becomes ______
Implementing all inherited abstract methods makes the subclass concrete.
Which of the following approach(es) is used to create threads in java?
Threads are created by implementing the Runnable interface or by extending (inheriting) the Thread class.
Which of the following is the best choice as a controller in MVC Model Architecture?
In MVC Model 2 a servlet acts as the controller while JSPs are views.
Which of the following is not a built-in validator?
JSF provides DoubleRange, LongRange and Length validators; there is no StringValidator.
Which of the following is used for comments in JSP?
JSP comments are written as <%-- ... --%>.
DataBaseMetaData object can be derived from ________ object.
DatabaseMetaData is obtained by calling getMetaData() on a Connection object.
Which of the following is FALSE regarding HttpServlet class?
HttpServlet is HTTP-specific (protocol dependent); GenericServlet is the protocol-independent one.
Which of the following is a correct way to create an ArrayList to hold Strings with an initial capacity of 10 items?
The type parameter follows the class name and the initial capacity is passed to the constructor.
Which of the following is a correct syntax for implementing WindowListener and MouseListener interfaces in a class named GUI?
Multiple interfaces are listed once after implements, separated by commas.
The sleep(int time) method causes the currently executing thread to wait for the time specified in -------------
Thread.sleep() takes its argument in milliseconds.
Which of the following is NOT appropriate for Page-centric approach?
Page-centric applications are hard, not easy, to scale.
Managed Bean is JavaBeans which is defined in ________.
JSF managed beans are declared in the faces-config.xml configuration file.
HTTP lies on which of the following layer?
HTTP is an application-layer protocol.
If we want to handle mouse Movement or mouse drag. Which of the following interface do we need to implement?
mouseMoved and mouseDragged events are handled by MouseMotionListener.
Which of the following is the server side error:
5xx status codes are server errors; 4xx codes are client errors.
Tomcat gives its initialization parameters in which of the following:
Initialization parameters are declared in the web.xml deployment descriptor.
Which of the following object has built in hash map?
The HttpSession object stores name/value attributes in a built-in hash map.
Request and response objects are built in which of the following:
request and response are implicit objects available in JSP pages.
An Html file can also be saved with which one of the following extension?
Any HTML page is a valid JSP page, so it can be saved with a .jsp extension.
Which of the following provides global control of JSP?
Directives (<%@ %>) give global control over the JSP page.
Which of the following are not the attributes of page directive?
file is an attribute of the include directive, not the page directive.
ArrayList is also called ________ array.
An ArrayList is a resizable (dynamically growing) array.
With URL rewriting, the information appended to URL can be in the form of ______
With URL rewriting the extra data can be extra path information, added parameters or a custom change.
On every request from the client, the server creates a new ______ and calls the ______ method.
Each request is handled in a new thread that calls service(); init() runs only once.
Which of the following is true about static methods of a class?
A static method can be called through the class name or (less clearly) through an object reference.
Which of the following access modifier is provided by default if no access modifier is written explicitly with data members or methods?
Without a modifier a member gets default (package-private) access, not public.
Which of the following is true regarding an abstract class?
A class may be declared abstract even with no abstract methods; it then simply cannot be instantiated.
The ________ object contains the information relevant to a servlet.
ServletConfig holds a servlet's configuration such as its init parameters.
What will be the result of following statement? System.out.println(6+3);
Both operands are int, so + performs addition and prints 9.
Each event source can have ________ listener/listeners registered on it.
Any number of listeners can be registered on one event source.
Controller centralizes the logic for dispatching requests to the next view based on ________.
The controller chooses the next view using the request URL, input parameters and application state.
WSDL stands for
WSDL is the Web Services Description Language.
Managed Beans have ______ Model
JSF managed beans follow a declarative model: they are declared in the configuration file.
Which is the fastest driver from the following?
Type 4 pure-Java drivers talk the database protocol directly, so they are fastest.
If you are going to implement multithreading in java which of the following interface is required:
Runnable is the interface whose run() method a thread executes.
Which of the following method is called each time a request is made?
service() runs for every request and dispatches to doGet()/doPost(); doGet() runs only for GET requests.
How many servlets are there per web application?
A web application may contain any number of servlets.
Which of the following provides method level access to the variables declared in it in JSP?
Variables declared in a scriptlet become local variables of _jspService(); declarations are class level.
Session is a ________.
A session stores attributes as name/value pairs, like a hash map.
There is/are _____ form(s) of response redirection.
Response redirection has two forms: sendRedirect() and sendError().
High coupling makes classes difficult or impossible to reuse because ___________.
A highly coupled class depends on many other classes, so it cannot be reused without them.
A variable declared as static in a class is a/an _______
A static field belongs to the class itself and is shared by all objects, so it is a class variable.
Which of the following problem most often occurs while scheduling threads using priority scheduling?
With priority scheduling, low-priority threads may never get CPU time, which is starvation.
Consider the following code segment. class CommonErrors { public static void main(String[] args){ String num = "50n"; int x = Integer.parseInt(num);
"50n" is not a valid integer, so Integer.parseInt throws NumberFormatException at run time.
Which of the following statement is TRUE regarding default ResultSet?
The default ResultSet is TYPE_FORWARD_ONLY and CONCUR_READ_ONLY.
The _________ method of ServletConfig object is used to access the initialization parameters of servlet.
ServletConfig.getInitParameter(String name) returns a servlet's init parameter.
Which one of the following is pure java component?
Swing components are written purely in Java, while AWT uses native peers.
Objects are mostly created using the keyword:
Objects are created with the new keyword.
Which adapter class will be used for Action Listener interface:
ActionListener has only one method, so Java provides no adapter class for it.
Implicit objects are present within which of the following?
JSP implicit objects are available in scriptlets and expressions, not in declarations.
When a user wants to access our application through browser which of the following folder of Tomcat does he access?
Web applications are deployed in Tomcat's webapps folder, which the browser accesses.
What does HTTP session uses in its underlying layer?
HttpSession uses cookies, and falls back to URL rewriting when cookies are disabled.
Which of the following comments can be read by taking view source of the webpage?
HTML comments <!-- --> are sent to the browser and appear in view source; JSP comments <%-- --%> are removed on the server.
Which of the following is NOT the method of DataBaseMetaData object?
getColumnCount() belongs to ResultSetMetaData, not DatabaseMetaData.
Static methods can only access ______
A static method has no this reference, so it can directly access only static variables and methods.
Converting smaller data types into bigger one is called ----------
Converting a smaller type to a larger one (widening) is up casting; down casting goes from bigger to smaller.
------------can be used to specify dynamic attribute values for JSTL actions without using full-blown programming language.
EL lets JSTL tags take dynamic attribute values without writing Java code.
In ________, Java is written inside HTML.
In JSP, Java code is embedded inside HTML; in servlets, HTML is written inside Java.
Which object would you use to share user specific information between JSPs?
The session object keeps data for one user across many pages and requests.
Which package contains JOptionPane?
JOptionPane is a Swing class in javax.swing.
If we have created a DSN named as employeeDSN what will be the url of database:
The JDBC-ODBC bridge URL format is jdbc:odbc:<DSN name>.
Identify which of the following statements is DML statement
DELETE is a data manipulation statement; CREATE and DROP are data definition statements.
If we iterate over the cookies of the website and no cookies are found what does it mean?
No cookies from a site means the browser has not stored any for it, i.e. the user is visiting for the first time.
What is not true about cookies?
Cookies are stored on the client (browser) side, not on the server.
In order to run our web application, we should place our application in which of the following folder?
Tomcat runs web applications placed in its webapps folder.
Declaration tag is used to declare variables and methods at ____________ level.
Declarations become members of the generated servlet class, so they are class level.
Which of the following is not provided in standard java class?
Java has no destructors; objects are cleaned up by the garbage collector.
Which of the following is the correct syntax to create ResultSetMetaData object?
ResultSetMetaData is obtained from a ResultSet with rs.getMetaData(); con.getMetaData() returns DatabaseMetaData.
Which of the following is TRUE regarding pack directory structure of J2EE web application?
The packed form (a WAR file) is used to deploy a web application; the unpacked form is used in development.
Which of the following is a valid constructor for a class named VU?
A constructor has the class name and no return type, not even void.
JVM assigns CPU to the threads based on __________
The JVM scheduler chooses which thread to run based on thread priorities.
Which of the following stream will be directly connected with keyboard?
A node stream connects directly to a source such as the keyboard; filter streams wrap other streams.
Identify those classes that are not GUI based
Vector is a collection class in java.util, not a GUI class.
Which of the following method we should override while painting?
For custom drawing on Swing components, override paintComponent().
What does the following code draw? g.setColor(Color.black); g.drawLine(10, 10, 10, 50); g.setColor(Color.RED); g.drawRect(100, 100, 150, 150);
The line is drawn in black from y=10 to y=50 (40 pixels), then the colour changes to red for the 150x150 rectangle.
__________ allow the websites to store information on a client machine and later retrieve it.
Cookies are small pieces of data stored on the client by the browser and sent back to the site.
Consider the following code segment. ArrayList al = new ArrayList(); Person p = new Person(); al.add(p); What will be the syntax to get an object from the first index of ArrayList?
The first index is 0 and a raw ArrayList returns Object, so a cast to Person is needed.
Adapter classes have been defined for listener interfaces having ______ methods.
Adapters exist only for listener interfaces with more than one method, so unused ones need not be written.
WEB-INF folder consists of __________
WEB-INF holds web.xml plus the classes and lib directories.
Identify which one is up casting?
Converting int to the wider double type happens implicitly (widening).
What is not correct about Adapters:
Adapters are classes, and Java does not allow extending more than one class at a time.
What method must appear in the following declaration? public class abc extends JFrame implements ActionListener
Implementing ActionListener requires defining actionPerformed(ActionEvent).
With the help of __________ we can better organize our files into different directories.
Packages map to directories and group related classes.
If we do not handle exception while using I/O files then it will lead to ______
I/O methods throw checked IOExceptions, which must be caught or declared or the code will not compile.
Which of the following object is passed as an argument to the paint() method?
paint(Graphics g) receives the Graphics context to draw on.
Servlets handle requests sent by the user (clients) and generates __________ response.
Servlets build responses dynamically at request time.
Which of the following tag is used for defining initialization parameters of a servlet?
Servlet init parameters are declared with <init-param> inside <servlet> in web.xml.
Which one of the following is NOT true for "Anonymous Inner Class"?
An anonymous inner class by definition has no name.
Identify which one is web brochure.
A brochure site mainly presents static information, like a university site; the others are interactive applications.
Which package contains ArrayList?
ArrayList is in java.util.
From which database this driver belongs? JdbcOdbcDriver
The JDBC-ODBC bridge driver is the one used with MS Access through an ODBC DSN.
Timer is initialized by which of the following method?
A javax.swing.Timer begins firing events when start() is called.
Yield is used in which of the following scheduling?
yield() voluntarily gives up the CPU, which is how threads share time under cooperative (non-preemptive) scheduling.
Which of the following protocol based server do we need to have while forwarding emails?
Email is sent and forwarded by SMTP servers.
When the JSP file compiles In which of the following format does it changes?
A JSP page is translated into a servlet, which is then compiled.
No MCQs match this filter.Is filter mein koi MCQ nahi.
Write the XML tags for the following scripting elements in JSP? Comments: Declaration:
Comments: there is no special JSP XML tag; an ordinary XML comment <!-- ... --> is used. Declaration: <jsp:declaration> ... </jsp:declaration> (Similarly, expression: <jsp:expression> ... </jsp:expression> and scriptlet: <jsp:scriptlet> ... </jsp:scriptlet>.)
What impact a JavaBeans object can produce when it is stored in Servlet Request object?
With request scope the bean is stored in the ServletRequest object. It is available to the current page and to every servlet or JSP to which the same request is forwarded or included. When the response is sent and the request ends, the bean is no longer available; a new request does not see it.
What invokes a thread's run() method?
The JVM invokes run(). The program calls start() on the Thread object; start() registers the thread with the scheduler, and when the thread gets the CPU the JVM calls its run() method. Calling run() directly would just execute it as a normal method in the current thread.
What is the significance of error page?
An error page is a JSP (marked with isErrorPage="true") or a page configured in web.xml with <error-page>, to which control goes when an uncaught exception or HTTP error occurs. It shows a friendly, customized message instead of a raw stack trace, hides internal details from the user, keeps a consistent look and feel, and can use the implicit exception object to log or display the error. Pages name it with the errorPage attribute of the page directive.
Which type of information can be appended to URL?
In URL rewriting, data that must pass between client and server is appended to the URL. It can be: (1) extra path information, (2) added request parameters (name=value pairs, for example a session ID), or (3) some custom, server-specific URL change. The server reads it back by parsing the URL.
Differentiate between Sequential Execution and multithreading.
Sequential execution: the program has one thread of control; statements run one after another, and a long task (a loop, a method call, I/O) blocks everything after it until it finishes. Multithreading: a program has several threads that run concurrently (in parallel on several processors or by time sharing on one). While one thread waits (for I/O or sleep), another can use the CPU, so long tasks do not block the rest of the program, responsiveness improves and resources are used better.
What is Package? How Packages are organized?
A package is a named group of related classes and interfaces, like a library. It gives a namespace (avoids name clashes), access control (package access) and easier reuse. Packages are organized as directories: each package name maps to a folder and sub-packages to sub-folders, for example package edu.vu.cs506 is stored in edu/vu/cs506. A source file declares its package with "package name;" as the first statement, and other classes use it with "import". Files are grouped by functionality, usability and category.
How can we read cookies from client?
Call request.getCookies(), which returns an array of Cookie objects sent by the browser (null if none). Then loop through the array and use getName() to find the needed cookie and getValue() to read its value: Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals("user")) { String value = cookies[i].getValue(); } } }
How can we use FileReader and FileWriter streams to print on console?
Attach them to the standard file descriptors instead of a file name: new FileReader(FileDescriptor.in) reads from the keyboard (console input) and new FileWriter(FileDescriptor.out) writes to the console. They are character streams, so they read and write characters. Example: FileWriter fw = new FileWriter(FileDescriptor.out); fw.write("Hello"); fw.flush();
Write the name of three types of Custom Tags?
1. Simple tag (no attributes, no body). 2. Tag with attributes. 3. Tag with body.
Differentiate between encodeURL() and encodeRedirectURL()?
Both are HttpServletResponse methods that add the session ID to a URL when cookies are not available (URL rewriting). encodeURL(url) is used for URLs written into the page (links, form actions). encodeRedirectURL(url) is used for the URL passed to response.sendRedirect(), because the rules for deciding whether to add the session ID can differ for redirects.
What are advantages of jsp over PHP?
JSP uses Java, a full object-oriented language with a very large set of libraries (JDBC, networking etc.), so complex business logic can be reused through JavaBeans and custom tags. JSP pages are compiled into servlets, so they run fast after the first request, and they are portable to any server and platform that supports Java. JSP also fits into the J2EE architecture (servlets, EJB, MVC).
Why use client side validation?
Client-side validation (for example with JavaScript) checks input in the browser before the form is sent. It gives the user immediate feedback, avoids a round trip to the server for simple mistakes, and reduces server load and network traffic. It must still be repeated on the server because the user can bypass it.
Character oriented vs. byte oriented stream?
Byte-oriented streams (classes with "Stream" in the name, such as FileInputStream/FileOutputStream) read and write data as 8-bit bytes and suit any binary data such as images. Character-oriented streams (classes with "Reader" or "Writer" in the name, such as FileReader/FileWriter) read and write 16-bit Unicode characters and handle character encoding, so they are suited to text.
Does JSP support run time exception handling if yes then how?
Yes. A JSP is declared as an error page with <%@ page isErrorPage="true" %>; it can then use the implicit exception object. Other pages are linked to it with <%@ page errorPage="error.jsp" %>. When an uncaught runtime exception occurs, control goes to that error page. Error pages can also be configured in web.xml with <error-page>, and try/catch can be used inside scriptlets.
Advantages of JSP over servlet?
JSP lets you write normal HTML with small amounts of Java, so the presentation is easy to write and maintain without many println() statements. Designers can work on the HTML while developers write the Java in beans and tags, giving separation of presentation and logic. JSP is compiled and deployed automatically when changed, and it supports JavaBeans, custom tags, EL and JSTL. Since a JSP becomes a servlet it keeps all servlet abilities.
Difference between variable declared inside declaration part and scriplet part?
A variable declared in a declaration (<%! int x = 0; %>) becomes an instance variable of the generated servlet class. It is created once and shared by all requests (and threads), so its value persists between requests. A variable declared in a scriptlet (<% int y = 0; %>) becomes a local variable inside _jspService(); it is created again for every request and is not shared.
Why not use = = operator to compare string object of equal value?
For objects, == compares the references (addresses), so two different String objects with the same characters give false. The equals() method of String compares the actual characters (contents). So to check equal values use s1.equals(s2) (or equalsIgnoreCase()).
Why need expression languages?
Expression Language (${...}) lets a JSP read data (bean properties, request parameters, scoped attributes, collections) without writing Java scriptlets. It makes pages shorter and easier for designers to maintain, separates presentation from Java code, handles nulls and type conversion automatically, and gives dynamic attribute values to JSTL and custom tags.
write any two implicit objects
Any two of: request (HttpServletRequest), response (HttpServletResponse), out (JspWriter), session (HttpSession), application (ServletContext), config, pageContext, page, exception.
describe servlet context
ServletContext is an object that represents the whole web application. There is only one per application, shared by all its servlets and JSPs. It lets them communicate with the container (MIME types, logging, request dispatching), read context init parameters from web.xml, and share data as attributes (setAttribute/getAttribute). It is obtained with getServletContext().
why this keyword is used if we not use it then what will be he problems
this is a reference to the current object. It is used to refer to instance variables when a parameter or local variable has the same name (this.name = name), to pass the current object to another method (for example addActionListener(this)), to call another constructor of the same class (this(...)), and to return the current object. Without it, when a local variable or parameter has the same name as a field, the local name hides the field, so an assignment like name = name changes only the parameter and the field is never set.
3 stages of servlet life cycle
1. Initialization: the container loads the servlet, creates one instance and calls init() once. 2. Service: for every request the container calls service(), which calls doGet(), doPost() etc. 3. Destruction: before removing the servlet the container calls destroy() once to release resources, then the object is garbage-collected.
why the expression language is used
Expression Language (${...}) lets a JSP read data (bean properties, request parameters, scoped attributes, collections) without writing Java scriptlets. It makes pages shorter and easier to maintain, separates presentation from Java code, handles nulls and type conversion automatically, and gives dynamic attribute values to JSTL and custom tags.
for what purpose the c:remove is used in JSTL
<c:remove> removes a scoped variable. Example: <c:remove var="name" scope="page"/> removes the variable name from page scope; if no scope is given it is removed from all scopes.
Why we use servlets in the place of JSP controller?
In MVC (Model 2) the controller handles requests, reads parameters, calls the business logic (beans) and decides which view to show. This is pure Java processing with no HTML output, so a servlet is better suited: the code is clean Java, easier to debug and maintain. JSPs are better suited for views (presentation). Using a JSP as controller would fill it with scriptlets.
Differentiae between page centric approach and page with bean approach ?
Both are page-centric (Model 1) designs where the request goes first to a JSP page. Page-with-Java (pure page-centric): all presentation, business and data-access code is written as scriptlets inside the JSP. Code becomes a mixture, is duplicated across pages and maintenance is very hard. Page-with-bean: the JSP still handles the request and presentation, but business logic and data access move into JavaBeans used through <jsp:useBean>, <jsp:setProperty> and <jsp:getProperty>. There is less Java in pages, better reuse and easier maintenance.
Why we use taglib?
The taglib directive, <%@ taglib uri="..." prefix="..." %>, tells the JSP which tag library (custom tags or JSTL) it uses, where the tag library descriptor is (uri) and which prefix identifies its tags. It lets pages use custom tags instead of Java code, so logic is reused and pages stay clean.
Why we use JSP action elements and what are there formats?
Action elements are XML-style tags that make the container perform an action at request time, such as working with JavaBeans, including or forwarding to other resources and passing parameters, without Java code. Format: <jsp:actionName attribute="value" ... /> or with a body <jsp:actionName ...> ... </jsp:actionName>. Examples: <jsp:useBean>, <jsp:setProperty>, <jsp:getProperty>, <jsp:include>, <jsp:forward>, <jsp:param>, <jsp:plugin>.
Why we use JSP directive and describe its format?
Directives give high-level information to the container about the servlet that will be generated from the JSP; they produce no output. Format: <%@ directive attribute="value" %>. Types: page (for example imports, content type, errorPage, isErrorPage, session, extends, isThreadSafe), include (<%@ include file="..." %>, inserts a file at translation time) and taglib (declares a tag library and its prefix). With the page directive you control which classes are imported, which class the servlet extends, the MIME type, how multithreading is handled, whether the page uses sessions and which page handles errors.
Differentiate between encode URL() and redirect URL()?
Both are HttpServletResponse methods that add the session ID to a URL when cookies are not available (URL rewriting). encodeURL(url) is used for URLs written into the page (links, form actions). encodeRedirectURL(url) is used for the URL passed to response.sendRedirect(), because the rules for deciding whether to add the session ID can differ for redirects.
What are hidden form fields?
Hidden form fields are <input type="hidden" name="..." value="..."> elements in an HTML form. They are not shown on the page and do not change its appearance, but their name/value pairs are sent to the server with the form. They can carry information such as a session ID between pages to maintain a session; they only work with forms and the user can see them in the page source.
Write the procedure for adding information in clients's URL?
This is URL rewriting. The data to be kept is appended to every URL that the server sends to the client, in the form of extra path information, added parameters (for example ?sessionid=123&user=ali), or some custom server-specific change. When the user clicks the link, the information comes back in the request and the server reads it (getParameter(), getPathInfo()). With the servlet API, response.encodeURL(url) adds the session ID automatically.
What is the difference between Request Dispatcher forward , and Request dispatcher Include?
forward(): passes the request completely to another resource (servlet, JSP or HTML) in the same context, and that resource creates the whole response. It is transparent to the client (URL does not change), the request object stays available, headers can be set before forwarding but no output may be written before it. include(): inserts the output of another resource into the current response and then control returns to the first servlet. Data can be written before and after the include, and the first servlet finishes the response.
Built an interface in which an button and label is shown on first click it shows "My name is Omer" on second click it shows "My age is 20 years old" on third click it again shows "My name is Omer" and cycle goes on.
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ClickCycle implements ActionListener { JFrame frame; JButton button; JLabel label; int clicks = 0; public ClickCycle() { frame = new JFrame("Click Cycle"); Container c = frame.getContentPane(); c.setLayout(new FlowLayout()); button = new JButton("Click"); label = new JLabel(""); button.addActionListener(this); c.add(button); c.add(label); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 100); frame.setVisible(true); } public void actionPerformed(ActionEvent e) { clicks++; if (clicks % 2 == 1) { label.setText("My name is Omer"); } else { label.setText("My age is 20 years old"); } } public static void main(String[] args) { new ClickCycle(); } }
Why we use session tracking
HTTP is stateless, so the server does not remember earlier requests from the same user. Session tracking links a user's successive requests into one session so data such as login status or a shopping cart can be kept across pages. It is done with cookies, URL rewriting, hidden form fields or HttpSession.
What are page error and how it handle in JSP
An error page is a JSP shown when an uncaught exception occurs in another page; it gives a friendly, consistent message instead of a raw stack trace. It is handled by declaring the error page with <%@ page isErrorPage="true" %> (it can use the implicit exception object) and naming it in other pages with <%@ page errorPage="error.jsp" %>, or by configuring <error-page> in web.xml.
web service according to W3C
According to W3C, a web service is a software system designed to support interoperable machine-to-machine interaction over a network. It has an interface described in a machine-processable format (WSDL), and other systems interact with it in the way its description prescribes using SOAP messages, typically sent over HTTP with XML and other web standards.
For what purpose c:remove tag is used.
<c:remove> removes a scoped variable. Example: <c:remove var="name" scope="page"/> removes the variable name from page scope; if no scope is given it is removed from all scopes.
What are advantages of jsp over Servlets
JSP lets you write normal HTML with small amounts of Java, so the presentation is easy to write and maintain without many println() statements. Designers can work on the HTML while developers write the Java in beans and tags, giving separation of presentation and logic. JSP is compiled and deployed automatically when changed, and it supports JavaBeans, custom tags, EL and JSTL. Since a JSP becomes a servlet it keeps all servlet abilities.
EJBs and JSP/servlet run on which server?
JSP and servlets run in a web server (web container, for example Tomcat). EJBs need an application server with an EJB container (for example JBoss, GlassFish, WebLogic). An application server usually contains a web container as well, so all can run on it.
What is impact a java bean object can produce when it is stored in an application
With scope="application" the bean is stored in the ServletContext. It is shared by all users, all sessions and all pages and servlets of the web application, and it stays available until the application is stopped or the bean is removed. Changes made by one user are seen by everyone, so it suits shared data such as counters or configuration.
Diff b/w serialized and deserializaed
Serialization converts an object (its state) into a stream of bytes so it can be saved to a file or sent over a network, using ObjectOutputStream.writeObject(); the class must implement Serializable. Deserialization is the reverse: it reads the byte stream with ObjectInputStream.readObject() and rebuilds a copy of the original object in memory.
How JSP pages are informed about error pages?
By setting the errorPage attribute of the page directive, for example <%@ page errorPage="error.jsp" %>. The error page itself is marked with <%@ page isErrorPage="true" %>.
What happens if a class does not provide a constructor in a class?
The compiler adds a default constructor: a public (same access as the class) no-argument constructor that only calls super(). The class compiles and objects can be created with new ClassName(). Fields get their default values. If the class defines any constructor, no default constructor is added.
What are two ways of request dispatching? Explain.
Using a RequestDispatcher (from request.getRequestDispatcher() or the ServletContext): 1. forward(request, response): sends the request to another resource, which generates the whole response; transparent to the client. 2. include(request, response): includes the output of another resource in the current response, then control returns to the calling servlet.
What type of problems persists with struts framework?
Struts is an action-based MVC framework without a standard UI component and event model: pages are still written with low-level HTML and tags, there is no rich reusable component set, and the code is tied to the request/response cycle. Configuration (struts-config.xml) is large and complex and it is a non-standard framework. These limits led to the standard JSF framework.
What are the participants of MVC model and what are their responsibilities?
Model: holds the state (data) of the application and the methods (business logic) to work on it, independent of how it is shown. View: renders the model data for the user and decides how it is presented. Controller: receives user actions (in web apps, GET/POST requests), translates them into actions on the model and selects the view to show.
Can an arraylist contain heterogeneous objects? If yes then why?
Yes. A non-generic ArrayList stores its elements as Object references, and every class inherits from Object, so objects of different types (String, Integer, user classes) can be stored in the same list. A cast is needed when reading elements back. (A generic ArrayList<T> restricts it to one type.)
EJBs and JSP/Servlets run on which type of server?
JSP and servlets run in a web server (web container, for example Tomcat). EJBs need an application server with an EJB container. An application server usually contains a web container as well.
What are the three stages of Servlet Lifecycle?
1. Initialization: the container loads the servlet, creates one instance and calls init() once. 2. Service: for every request the container calls service(), which calls doGet(), doPost() etc. 3. Destruction: before removing the servlet the container calls destroy() once to release resources.
Why is direct call of paint() method not recommended?
Painting is controlled by the system: it calls paint() (through update/paintComponent) when needed and supplies the correct Graphics object. If the program calls paint() directly it must get a Graphics object itself, may paint at the wrong time, outside the event thread or in conflict with system repainting, and Swing double buffering and the painting of borders and children may be skipped. Instead the program should call repaint(), which asks the system to schedule a proper repaint as soon as possible.
Which Five operators are used in Expression Language
Any five, for example: the dot operator (.) and [] operator to access properties and elements; arithmetic operators (+, -, *, / or div, % or mod); relational operators (== or eq, != or ne, < or lt, > or gt, <= or le, >= or ge); logical operators (&& or and, || or or, ! or not); the empty operator; and the conditional operator (?:).
Why do we need Expression language?
Expression Language (${...}) lets a JSP read data (bean properties, request parameters, scoped attributes, collections) without writing Java scriptlets. It makes pages shorter and easier to maintain, separates presentation from Java code, handles nulls and type conversion automatically, and gives dynamic attribute values to JSTL and custom tags.
Why Client side Validation Good?
Client-side validation checks input in the browser (for example with JavaScript) before the form is submitted. It gives instant feedback to the user, avoids a round trip to the server for simple errors and reduces server load and network traffic. Because it can be bypassed, server-side validation is still needed.
Why do we use session tracking in HTTP servlets?
HTTP is stateless, so the server does not remember earlier requests from the same user. Session tracking links a user's successive requests into one session so data such as login status or a shopping cart can be kept across pages. It is done with cookies, URL rewriting, hidden form fields or the HttpSession API.
How MVC work with JSP page,servlet,Html
In MVC (Model 2) a servlet acts as the controller: every request from the HTML page or form goes to the servlet, which reads the parameters, calls JavaBeans (the model) to do business logic and data access, stores the results in request or session scope, and forwards the request with a RequestDispatcher to a JSP page. The JSP (the view) only displays the model data as HTML. In Model 1, by contrast, the browser goes directly to JSP pages that use beans and decide the next page themselves.
How can we use a existing Database by using JDBC write the steps?
1. Import java.sql.*. 2. Load the driver: Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); (or the database's own driver). 3. Get a connection: Connection con = DriverManager.getConnection("jdbc:odbc:myDSN", "user", "password"); 4. Create a statement: Statement st = con.createStatement(); 5. Execute the query: ResultSet rs = st.executeQuery("SELECT * FROM Person"); (executeUpdate() for INSERT, UPDATE, DELETE). 6. Process the results: while (rs.next()) { String name = rs.getString("name"); } 7. Close the ResultSet, Statement and Connection, and handle SQLException.
What is abstract classes
An abstract class is declared with the keyword abstract and gives only part of an implementation, so it cannot be instantiated. It can have abstract methods (without bodies) as well as instance variables, constructors and fully implemented methods. A subclass must implement all abstract methods to become concrete. A reference of the abstract class type can point to subclass objects, which supports polymorphism.
Name nay two logical layers of we application?
Any two of: presentation layer, business layer, data (data access) layer.
Write briefly 2 characteristic of EL?
Any two: it accesses data with simple ${...} syntax instead of Java code; it reads bean properties, collections and scoped attributes using the dot and [] operators; it has implicit objects such as param, header, sessionScope; it converts types and treats null safely (shows nothing instead of an exception); it supports arithmetic, relational, logical and empty operators.
3 Paint methods which are used to paint swing component
paintComponent(Graphics g), paintBorder(Graphics g) and paintChildren(Graphics g), called in that order by paint().
thread States?
New (created but not started), Ready/Runnable (started and waiting for the CPU), Running (executing), Blocked/Waiting (sleeping, waiting for I/O, a lock or notify), and Dead (run() finished or stopped).
Significance of error Pages?
Error pages show a friendly, customized message when an uncaught exception or HTTP error occurs instead of a raw stack trace. They hide internal details, keep a consistent look and feel and can log the error using the implicit exception object.
features that JSP provide?
Main features: HTML-based pages with embedded dynamic content; scripting elements (scriptlets, expressions, declarations); directives; implicit objects; easy use of JavaBeans through action elements; custom tags, JSTL and EL; automatic translation into servlets and compilation when changed; platform independence and the full Java API; separation of presentation from logic.
how can we encode URL which is sent to Client?
Use response.encodeURL(url) for links and form actions written into the page, and response.encodeRedirectURL(url) for URLs passed to sendRedirect(). They append the session ID to the URL when the browser does not accept cookies (URL rewriting), for example out.println("<a href=\"" + response.encodeURL("next.jsp") + "\">Next</a>");
types of layers?
Presentation layer (user interface), business layer (business logic) and data layer (data access and storage).
Operators of EL?
Dot (.) and [] for access; arithmetic (+, -, *, / div, % mod); relational (== eq, != ne, < lt, > gt, <= le, >= ge); logical (&& and, || or, ! not); empty; and conditional (?:).
java include Directives?
The include directive, <%@ include file="relativeURL" %>, inserts the content of another file (JSP, HTML) into the current JSP at translation time, before it is compiled, so the result is one servlet. It is used for common parts such as headers and footers. (Unlike the <jsp:include> action, which includes the output at request time.)
How does JSF provide navigation?
JSF has a navigation model defined in faces-config.xml with <navigation-rule> elements. Each rule has a <from-view-id> and one or more <navigation-case> entries with a <from-outcome> and <to-view-id>. A command component returns an outcome string, either fixed in its action attribute (action="success") or returned by an action method (action="#{bean.login}"), and the navigation handler uses the matching rule to show the next page.
Declare a private integer variable into JSP declaration tag.
<%! private int count = 0; %>
Write a scriptlet that is equivalent to the following fragment of code <c: out value ="${param,id}"default="null"/>
<% String id = request.getParameter("id"); if (id == null) { id = "null"; } out.print(id); %> (The tag is meant as <c:out value="${param.id}" default="null"/>: print the request parameter id, or the text "null" if it is missing.)
Write three session tracking techniques.
1. Cookies. 2. URL rewriting. 3. Hidden form fields. (The HttpSession API uses cookies or URL rewriting internally.)
Why we use args[] array in main method of java?
args (String[] args) receives the command-line arguments passed when the program is started, e.g. java Test ali 20 gives args[0] = "ali" and args[1] = "20". The program can use these values as input parameters; args.length tells how many were passed.
Web Pages Vs Web Services
A web page has a user interface, interacts with a human user and is viewed in a web browser. A web service has no GUI; it is a web-based component that interacts with other applications, exchanging data through open XML-based standards and protocols, and can be used by any type of client program.
Custom tags type
1. Simple tag (no attributes, no body), e.g. <my:hello/> 2. Tag with attribute(s), e.g. <my:hello name="ali"/> 3. Tag with body, e.g. <my:bold>text</my:bold>
Alternative name of business class:
The business layer is also called the application layer (business logic layer). It contains only the application-specific functionality: business rules and business tasks.
Methods of paintComponent() any 3 ?
The three Swing paint methods called from paint() are: protected void paintComponent(Graphics g) protected void paintBorder(Graphics g) protected void paintChildren(Graphics g)
Data sorted as HTML comment and JSP comment?
An HTML comment <!-- comment text --> is sent to the browser as part of the page, so it can be seen with View Source. A JSP comment <%-- comment text --%> is ignored by the JSP-to-servlet translator, so it is never sent to the browser.
Does EL support the automatic type conversion? support your ans
Yes. EL converts values automatically to the type needed by the expression: strings such as request parameters are converted to numbers for arithmetic or comparison (e.g. ${param.age + 1}), and primitives are automatically wrapped/unwrapped into/from their wrapper classes. Null values are also treated sensibly (e.g. as 0 in arithmetic) instead of causing errors.
What is Boxing and un-boxing
Boxing is automatic conversion of a primitive value into its wrapper object, e.g. int to java.lang.Integer. Unboxing is the reverse conversion of a wrapper object into its primitive, e.g. Integer to int (or Byte to byte). Example: Integer i = 5; int j = i;
Why JSP takes time to run when it runs 1st time.
On the first request the JSP container translates the JSP page into a servlet Java file, compiles it into a class and loads and initializes it. Later requests use the already loaded servlet, so they are fast. The page is translated again only when the JSP file is changed.
Absolute method help to us to move cursor to any specific row in result set. If we call absolute method and give value-1 as argument which row our cursor will point after calling absolute(-1)?
absolute(-1) moves the cursor to the last row (negative values count from the end; absolute(-2) is the second-last row). It needs a scrollable ResultSet; with TYPE_FORWARD_ONLY it throws an SQLException.
Write impact a java beans can produce when it is stored in page scope?
A bean in page scope is stored in the PageContext of that JSP. It is available only on the same page during the current request; it is not available to pages that are forwarded to or included, nor in later requests. It is discarded when the page finishes, so a new bean is created on every request of that page.
Advantages of updatable and/or scrollable ResultSet? Any two.
1. The cursor can move forward and backward and jump to any row (previous(), absolute(), first(), last()). 2. Rows can be inserted, updated or deleted directly through the ResultSet (updateXXX(), updateRow(), insertRow(), deleteRow()) without writing separate SQL.
Custom tag?
A custom tag is a user-defined JSP tag (component) that performs a certain action. Its behaviour is written in a Java tag handler class, it is described in a TLD file, and it is used in JSP through a taglib directive, e.g. <mytag:hello/>.
List of names scopes under EL implicit objects.
pageScope, requestScope, sessionScope, applicationScope
How to track a user session in Servlet?
Using cookies, URL rewriting or hidden form fields, or the Servlet API’s HttpSession object (request.getSession()), which itself uses a cookie or URL rewriting to keep the session ID.
Read data into buffer code example?
Socket s = new Socket("localhost", 2222); InputStream is = s.getInputStream(); // convert the byte stream into a buffered character stream InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line = br.readLine(); // read a line from the buffer
Comments of HTML and JSP?
HTML comment: <!-- comment text --> (sent to browser, visible in page source). JSP comment: <%-- comment text --%> (removed during translation, not sent to browser).
Java Beans actions elements example codes?
<jsp:useBean id="p" scope="page" class="vu.PersonInfo" /> <jsp:setProperty name="p" property="name" value="ali" /> <jsp:getProperty name="p" property="name" />
Can EL supports automatic type conversion? Support your answer?
Yes; EL converts strings to numbers and wraps/unwraps primitives automatically as the expression needs, e.g. ${param.age + 1}.
What is the difference between java beans and EJB's?
A JavaBean is an ordinary reusable Java class that follows design conventions (zero-argument constructor, private properties with getters/setters, serializable); it runs in any JVM, e.g. inside a JSP/web container. An EJB (Enterprise JavaBean) is a server-side component that encapsulates business logic and runs inside an EJB container of an application server, which provides services such as transactions, security, scalability and remote access.
JavaBeans Design Conventions
1. A bean class must have a zero-argument constructor. 2. It should not have public instance variables (fields). 3. Private properties are accessed through getter and setter methods (getXxx/setXxx, isXxx for boolean). 4. A bean class must be serializable.
JSP vs. Servlet
A servlet is a Java class in which HTML is generated with out.println() statements, so Java code contains the presentation. A JSP is an HTML page with embedded Java/JSP elements, so presentation is written easily and changed without recompiling by hand. A JSP is translated into a servlet automatically on first request. Servlets suit processing/controller logic; JSPs suit presentation (view).
What is expression language Nuggets?
The main features of EL: EL expression syntax and identifiers; arithmetic, logical and relational operators; automatic type conversion; access to beans, arrays, lists and maps; and access to a set of implicit objects.
If we do nit set any scope element which scope element will be set as default scope element
page scope. If the scope attribute of jsp:useBean is omitted, it defaults to page.
Write format of EL (expression language)
${ validExpression } e.g. ${param.name}
Difference between static and non static inner class?
A non-static inner class object is tied to an outer class object and can use its instance members; a static nested class is not tied to any outer object and can be created alone, using only static members of the outer class directly.
What is the alternate name of business layer?
Application layer (business logic layer).
Write any six EL(Expression Language) relational operators?
== or eq != or ne < or lt > or gt <= or le >= or ge
What is package and who to organize?
A package is a group of related classes and interfaces kept together in one directory under one name; it organizes files by functionality and avoids name collisions. To organize: write package mypack; as the first statement of each source file, place the files in a folder with the same name (sub-packages in sub-folders, e.g. vu.cs506 -> vu/cs506), compile them, and use them from other classes with import mypack.*; (the package root folder must be on the CLASSPATH).
Value Binding:
In JSF a value binding expression #{bean.property} connects a UI component’s value to a property of a managed bean. It can automatically create the bean and place it in request/session scope, set/override bean values through its setter methods, read Map, List and array contents from the bean, and keep form contents synchronized with value objects across requests. Example: <h:inputText value="#{customer.name}"/>
Method Binding:
A method binding expression does not refer to an accessor (getter/setter) but to an action method of a bean that is invoked, e.g. an event handler or validator. Example: <h:commandButton value="Login" actionListener="#{customer.loginActionListener}"/>
Reading Cookies from the Client:
Get all incoming cookies from the request and search for the required one by name: Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals("visit")) { String value = cookies[i].getValue(); } } }
Correct the following object code cookie c=new cookie ("visit",10)
Cookie c = new Cookie("visit", "10"); The class name is Cookie (capital C) and both constructor arguments must be Strings, so 10 must be written as "10".
Write Scope in order
From narrowest to widest: page, request, session, application.
identify the following tag: <studenttagstudy> </studenttagstudy>
It is written with a start tag and an end tag, which is the form of a tag with body (the body content goes between the two tags; here it is empty). It has no attributes.
write EL conditional operator
The conditional (ternary) operator: ${ condition ? value1 : value2 }, e.g. ${ param.marks >= 50 ? "Pass" : "Fail" }
Write a code statement to remove the value associated with the "amazonsession"of object "session"
session.removeAttribute("amazonsession");
Write any three features of java which are not presented in c/c++?
1. Automatic garbage collection (no manual delete/destructors). 2. No pointers (no pointer arithmetic). 3. Platform independence through bytecode run by the JVM (write once, run anywhere). Also: no multiple inheritance of classes (interfaces instead), no operator overloading, built-in multithreading and array bounds checking.
The following JSP tag is equivalent to which action element? <jspforward page="vu.jsp">
It is the jsp:forward action element: <jsp:forward page="vu.jsp" />. It forwards the request to vu.jsp and is equivalent to the scriptlet: <% RequestDispatcher rd = request.getRequestDispatcher("vu.jsp"); rd.forward(request, response); %>
Why we do session tracking in httpServlets?
HTTP is a stateless protocol: each request is independent and the server forgets the client after responding. Session tracking lets the servlet recognize the same user across many requests and keep that user’s data (e.g. login information or a shopping cart) between pages.
You have your web project file in .WAR format inside dest directory. Explain how will you deploy your web application?
Copy the .war file from the dest directory into Tomcat’s %CATALINA_HOME%/webapps folder and start (or restart) Tomcat. Tomcat automatically expands the archive into a folder with the same name and deploys it. The application is then opened at http://localhost:8080/<war-file-name>/ (it can also be uploaded through Tomcat’s manager page).
Explain why JAVA applets are better than Active-X components?
Applets are downloaded as platform-independent bytecode and run on any browser/OS with a JVM, while ActiveX controls are native Windows binaries. Applets also run in a security sandbox (no local file access etc.), whereas ActiveX controls get full access to the machine, so applets are safer.
How many logic layer possible in one tire?
One tier can hold one or more layers; all three logical layers (presentation, business, data) can reside on a single tier. Tiers are physical separations, layers are logical ones.
Why java has remove pointers? give solid reason
Pointers allow direct memory access and pointer arithmetic, which causes hard-to-find errors (dangling pointers, memory leaks, corrupting memory) and security risks. Java removed explicit pointers for safety, security and simplicity: objects are accessed only through references, the JVM checks array bounds, and memory is managed by the garbage collector.
What is Servlet Problem generating html pages?
In a servlet the HTML is produced with many out.println() statements inside Java code. This mixes presentation with business logic, makes the page hard to write, read and maintain, means web designers cannot use normal HTML tools, and every change in the HTML requires editing and recompiling the servlet. JSP was introduced to solve this.
impact of object in java beans when using application scope?
A bean in application scope is stored in the ServletContext. Only one object is created and it is shared by all users, all sessions and all JSPs/servlets of the same web application; it lives until the application is stopped/reloaded. Any change made by one user is seen by all, so it suits common data (e.g. a hit counter) and access to it should be thread-safe.
In catch block any other exception catch before IOException? if no give reason
Yes, but only a subclass of IOException (e.g. FileNotFoundException) or an unrelated exception type. A superclass such as Exception cannot be caught before IOException: catch blocks are checked in order, so the later IOException block could never be reached and the compiler reports an error. More specific exceptions must come first.
Jsp:useBean equivalent to which of the java code?
It is equivalent to creating (or finding) an object in a scriptlet, e.g. <% MyBean m = new MyBean(); %> is the same as <jsp:useBean id="m" scope="page" class="vu.MyBean" /> (useBean first looks for an existing bean with that id in the given scope and creates a new one only if none exists).
Advantages of collections over array
No need to know the size in advance (grows/shrinks automatically) and ready-made methods for adding, removing and searching objects.
Try block?
A try block encloses the statements that may throw an exception. It must be followed by one or more catch blocks (which handle the exceptions) and/or a finally block (which always runs): try { // code that may throw an exception } catch (IOException e) { // handle it } finally { // cleanup }
Does EL support the automatic type conversion?
Yes; EL automatically converts types (e.g. strings to numbers, wrapping/unwrapping primitives).
Being a java front end developer, write the characteristics of tag with body custom tag and also give example?
A tag with body has a start tag and an end tag, may have attributes, and has body content enclosed between the tags that the tag handler can process (e.g. with getJspBody().invoke(null)). Example: <vu:bold>Welcome to VU</vu:bold>
if we call the following methods in the following sequence and we refresh our page one time will the session expire? Support your answer with the reason. (i) Session.setMaxAge(160) (ii) Session.invalidate()
Yes. invalidate() ends the session immediately and unbinds all objects stored in it, whatever timeout was set before. When the page is refreshed, the old session (and its data) is gone; request.getSession() creates a new, empty session. (For HttpSession the timeout method is setMaxInactiveInterval(); setMaxAge() belongs to Cookie.)
In which situation executeQuery() and executeUpdate methods of statement object can be used for SQL?
executeQuery() is used for SELECT statements that return data; it returns a ResultSet. executeUpdate() is used for statements that change data or structure (INSERT, UPDATE, DELETE, CREATE, DROP); it returns the number of rows affected.
What are the two options through which we can assign unique session id to each user?
1. Cookies: the server sends a cookie (e.g. JSESSIONID) holding the unique session ID, and the browser returns it with each request. 2. URL rewriting: the session ID is appended to every URL (response.encodeURL()) and read back from the URL of the next request.
What information can be appended to URL.
With URL rewriting the following can be appended to a URL: extra path information, added parameters (name=value pairs in the query string), or some custom, server-specific URL change. Usually it is just a unique session ID.
Write an expression language equivalent to 1. Out implicit object of JSP 2. Request.getParameter("id");
1. ${pageContext.out} 2. ${param.id}
Write a single line to include a page "vuHome.java" using custom tags. You can use any name for tag but mention which you have chosen for which tag element.
Chosen names: prefix vh, tag name vuhome, handler class vu.VuHomeTag (declared in the TLD under <tag><name>vuhome</name><tag-class>vu.VuHomeTag</tag-class><body-content>empty</body-content></tag>). After the taglib directive <%@ taglib uri="/WEB-INF/tlds/customtags.tld" prefix="vh" %>, the single line is: <vh:vuhome />
Being a java developer you have given a task define two initialization parameters. Define first parameter for text file (out.txt) and other for DSN (studentDSN). You are required to write only necessary code.
<!-- inside the <servlet> element of web.xml --> <init-param> <param-name>out</param-name> <param-value>out.txt</param-value> </init-param> <init-param> <param-name>DSN</param-name> <param-value>studentDSN</param-value> </init-param>
Being a java developer you have given a task read two initialization parameters. Read first parameter for text file (out) and other for DSN (studentDSN). You are required to write only necessary code.
String fileName; String dsn; public void init(ServletConfig config) throws ServletException { super.init(config); fileName = config.getInitParameter("out"); // "out.txt" dsn = config.getInitParameter("DSN"); // "studentDSN" }
Write the purpose of hash maps in session tracking through cookies?
The server keeps each user’s session data in a HashMap (attribute name -> value), and these maps are stored in another HashMap keyed by a unique session ID. Only the session ID is sent to the browser in a cookie. On each request the server reads the session ID from the cookie and uses it to look up that user’s HashMap, so the user’s data can be retrieved quickly.
What is other technique to remove server side over head while maintaining the state of user?
Keep the state on the client side instead of the server: store the data itself in cookies, or carry it in hidden form fields or appended URL parameters (URL rewriting) that are sent back with every request, so the server does not have to store session data.
Being a java web developer you know each tag handler class must inherit from another class. What is the name of that class?
SimpleTagSupport (javax.servlet.jsp.tagext.SimpleTagSupport), which already implements the SimpleTag interface; the handler overrides doTag().
What is use of [] operator in EL? Give one example?
The [] operator accesses elements of arrays and Lists by index, e.g. ${personList[2]} gives the 3rd element, and values of Maps by key, e.g. ${myMap["id"]}. It can also access bean properties, e.g. ${person["name"]}.
Is it necessary that every try block must be followed by a catch block given reason to support your answer?
No. A try block must be followed by at least one catch block or a finally block (or both). try-finally without catch is valid: the finally code (cleanup) always runs and the exception is passed to the caller, so a checked exception must then be declared in the method’s throws clause.
How many types of comments are used in JSP?
Two: JSP comments <%-- comment --%>, which are not sent to the browser, and HTML comments <!-- comment -->, which are sent and visible in the page source.
What are the drawbacks of Page-centric approach?
Presentation, business and data-access code are mixed in the JSPs; a lot of code is duplicated; maintenance and upgrading become a nightmare; and the application is hard to scale.
What steps will we take in order to test whether the tomcat server is running or not?
Start Tomcat (e.g. startup.bat in %CATALINA_HOME%/bin, with JAVA_HOME and CATALINA_HOME set), then open a browser and go to http://localhost:8080/. If Tomcat’s default welcome page appears, the server is running.
Write the forms of Standard Directory Structure; which is used for the development of the web components?
webapps/myapp/ - root: HTML, JSP, images webapps/myapp/WEB-INF/ - web.xml (deployment descriptor) webapps/myapp/WEB-INF/classes/ - compiled servlet and other .class files (in package folders) webapps/myapp/WEB-INF/lib/ - .jar library files
Which four tag libraries are combined to form a single JSTL?
Core (prefix c), XML (x), Internationalization/Formatting (fmt) and SQL/database (sql).
What is the difference between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?
ServletRequest.getRequestDispatcher() accepts a relative path (relative to the current request’s path) as well as a path starting with "/". ServletContext.getRequestDispatcher() accepts only a path that begins with "/", interpreted relative to the context root of the web application.
What impact a JavaBeans object can produce when it is stored in Page scope?
It is available only within that page for the current request and is discarded afterwards.
Why do we use doTag() method in tag handler class?
doTag() is the method of a simple tag handler (SimpleTagSupport) in which the tag's functionality is written. We override it, and the JSP container calls it when it processes the custom tag in the page, so whatever doTag() writes (for example through getJspContext().getOut()) appears in place of the tag.
Differentiate between Layers and Tiers.
Layers are the logical grouping of an application's software components (for example presentation, business and data layers). Tiers are the physical machines or processes on which those layers are deployed. So layers give the logical view of an application and tiers give its physical view; one tier can hold several layers.
What is the preferred size of a component?
The preferred size of a component is the width and height it would like to have to display its contents properly (for example a button's size based on its label and font). It is returned by getPreferredSize() and can be set with setPreferredSize(); layout managers such as FlowLayout use it when laying out components.
Name three stages of servlet life cycle.
1. Initialize: init() is called once when the servlet is first loaded. 2. Service: service() (doGet()/doPost()) is called for every client request. 3. Destroy: destroy() is called once before the servlet is unloaded, to release resources.
What is the difference between variable declared inside a declaration part and variable declared in scriplet part?
A variable declared in a JSP declaration (<%! int x; %>) becomes an instance variable of the generated servlet class. It is created once, keeps its value between requests and is shared by all requests. A variable declared in a scriptlet (<% int x; %>) becomes a local variable of the _jspService() method, so it is created again for every request and is visible only inside that method.
Disadvantage of Page-centered approach
In the page-centric approach the code becomes a mixture of presentation, business and data access logic, so maintenance and upgrading become very difficult. Much code is duplicated across pages and the application is hard to scale.
Methods of session tracking
Common session tracking methods are: 1. Cookies 2. URL rewriting 3. Hidden form fields The Servlet API also provides HttpSession, which is built on these.
What does finalization mean?
Finalization means running an object's finalize() method before garbage collection. If a class defines finalize(), the Java runtime calls it when it is about to reclaim an object of that class, giving the object a chance to release resources.
What does error 404 display?
HTTP status code 404 (Not Found) means the requested resource (page or file) is not available on the server; the browser shows a "404 Not Found" error page.
JSP directive.
JSP directives give special processing information to the JSP container and affect the overall structure of the servlet generated from the page. Syntax: <%@ directive attribute="value" %>. They are used to specify page settings (page directive), include content of other files at translation time (include directive), and declare custom tag libraries (taglib directive).
Difference of forward and send redirect.
forward() (RequestDispatcher) passes the same request and response to another resource on the server. It happens inside the web container, the client is not informed, the URL in the browser does not change and request attributes remain available. sendRedirect() (HttpServletResponse) sends a response telling the browser to request a new URL. The browser makes a completely new request, the URL changes, request attributes are lost, it can point to another server, and it is slower because of the extra round trip.
What is the format in which the source code of Java converted after compilation?
Java source code (.java files) is compiled by the Java compiler into Java bytecode, which is stored in .class files. The bytecode is then executed by the Java Virtual Machine on any platform.
Write briefly two characteristics of Expression Language?
1. Multiple EL expressions can be combined and mixed with static text, for example "Hello ${user.firstName} ${user.lastName}". 2. If an object or identifier is null, EL does not throw a NullPointerException; it simply shows an empty value. EL also converts types automatically.
Why yield() method used?
yield() makes the currently running thread give up the CPU so that other threads of the same priority can run; the thread moves to the end of the queue for its priority. If all waiting threads have lower priority, the yielding thread continues to run. It is used in long-running loops so that equal-priority threads get a fair chance.
Which method is used to read an object through serialization?
The readObject() method of ObjectInputStream is used to read (deserialize) an object; the result is cast to the original class.
Explain in your words that how Java bean is intended for use in some type of building tool?
A JavaBean is a reusable software component written to standard conventions (no-argument constructor, properties accessed by getters/setters, serializable). Because of these conventions, a builder tool can inspect a bean (introspection), show its properties, let the developer set them visually and connect beans together without writing code. A bean does not have to be visual; for example a database-access bean adds nothing to the GUI but can still be configured in the tool and connected to other beans.
What are expression language Nuggets?
The main features ("nuggets") of EL are: - EL syntax ${expression} - expressions and identifiers - arithmetic, logical and relational operators - automatic type conversion - access to beans, arrays, lists and maps - access to a set of implicit objects
What are the benefits of using Packages? Explain.
Packages organize related classes and interfaces into directories according to their functionality, usability and category. Benefits: related classes are easy to find and maintain; name collisions are avoided because the same class name can exist in different packages; access can be controlled with package-level access; and code can be reused by importing packages.
What is the purpose of wait(), notify(), notifyAll() methods?
wait(), notify() and notifyAll() are Object methods used for communication between threads sharing a resource. They must be called inside synchronized code. wait() makes the current thread release the object's lock and wait until another thread calls notify() or notifyAll() on that object. notify() wakes up one waiting thread and notifyAll() wakes up all threads waiting on that object.
Write 2 Characteristics of Expression Language.
1. Multiple EL expressions can be combined and mixed with static text, for example "Hello ${user.firstName} ${user.lastName}". 2. If an object or identifier is null, EL does not throw a NullPointerException; it simply shows an empty value. EL also converts types automatically.
What is the hidden comment in JSP?
A hidden comment is a JSP comment that documents the JSP page but is not sent to the client. The JSP container ignores it during translation, so it does not appear in the page source in the browser. Syntax: <%-- comment text --%> Example: <%-- This part shows the user list --%>
Which method of ResultSetMetaData object is used to return the suggested column label for print out?
The getColumnLabel(int column) method of ResultSetMetaData returns the suggested column title for printouts and displays.
Advantages of using Custom Tags?
Advantages of custom tags: - They separate processing logic from presentation and remove scriptlets from JSP pages. - They have an HTML-like syntax that page designers can use without knowing Java. - They are reusable in many pages, which saves development and testing time. - They can be customized with attributes and body content. - They have access to JSP implicit objects such as out and request.
Name any two logical layers of web application?
Any two of: presentation layer, business layer, data layer.
How JSP pages are informed about the error?
A JSP page is told about its error page with the errorPage attribute of the page directive, for example <%@ page errorPage="error.jsp" %>. If an uncaught exception occurs, the request is forwarded to that page. The error page itself declares <%@ page isErrorPage="true" %> so it can use the exception implicit object.
Write advantages of JSP over Servlet?
Advantages of JSP over servlets: - JSP is a more convenient way to create HTML: the page is mostly HTML instead of many println() statements. - Standard HTML and web design tools can be used to build JSP pages. - JSP helps separate presentation from business logic, so designers and developers can work separately. - JSP pages are translated and compiled automatically by the container when they change.
Write features that JSP provide?
Features of JSP: - Mostly regular HTML with Java code marked by special tags, so dynamic pages are easy to write. - Uses Java as the language for the dynamic part, so it is portable to many servers and operating systems (better than ASP or ColdFusion). - Better language and tool support than PHP. - Compared with servlets, a more convenient way to generate HTML, standard web tools can be used, and presentation is separated from business logic. - The page is translated into a servlet once and the servlet handles each request.
What are the types of layers?
A web application is usually divided into three logical layers: 1. Presentation layer: provides the user interface. It collects and validates user input, shows the results and controls the screen flow (for example JSP pages). 2. Business layer (application layer): implements the application-specific functionality and business rules, for example opening an account or transferring a balance in a banking system (for example JavaBeans or EJBs). 3. Data layer: manages data and data sources such as databases, XML or files, and holds the data retrieval and storage logic (for example JDBC code).
All time you will not get same thread priority as you expect. Why? Identify the predefined constant used to assign thread priority.
Thread priority is only a hint to the thread scheduler. Java maps priorities to the priorities of the underlying operating system, and the scheduling policy depends on the JVM and OS, so a thread does not always get the exact priority behaviour we expect. The predefined constants of the Thread class are Thread.MIN_PRIORITY (1), Thread.NORM_PRIORITY (5, the default) and Thread.MAX_PRIORITY (10); they are used with setPriority().
Why thread is called light weight?
Threads are called lightweight because they need fewer resources than processes. Threads of one process share the same address space, memory and resources, so creating, destroying and switching between threads is much cheaper than for processes, and threads can share data directly.
Syntax of EL language.
EL syntax: ${expression}, for example ${param.name} or ${user.address.city}.
Why JSP supports run time exception handling?
JSP supports run-time exception handling so that an uncaught exception in a page does not show an ugly error to the user. With the errorPage attribute of the page directive, uncaught run-time exceptions are automatically forwarded to an error page: <%@ page errorPage="error.jsp" %> error.jsp declares <%@ page isErrorPage="true" %> and can use the exception object to show a proper message.
EJBs and JSP run in which servers?
JSP and servlets run in a web server (web container, for example Tomcat), while EJBs need an application server (EJB container). An application server generally also contains a web server.
What impact a java bean object produces when it is stored in servlet request object?
When the bean is stored in request scope, besides being bound to a local variable it is placed in the ServletRequest object for the duration of the current request. It stays available as long as the request is forwarded to other JSPs/servlets (or they are included), and it is removed when the request ends.
What happens when join() method is called in thread?
When thread2.join() is called, the currently running thread waits (blocks) until thread2 finishes its run() method, and then continues. It is used when one thread must wait for another to complete. join() can throw InterruptedException, so it is called in a try-catch block.
Define type of <jsp:studenttag.study> </jsp:studenttag.study>
It is a custom tag with prefix and name, written with an opening and a closing tag, but it has no attributes and no body content, so it is used like a simple tag (without attributes or body).
Differentiate b/w java classes and servlet?
An ordinary Java class is a general class; a standalone program starts from main() and the class is created and called by our own code. A servlet is a special Java class that implements the Servlet interface (usually by extending HttpServlet); it has no main(), runs inside a web container on the server, its life cycle (init, service, destroy) is managed by the container, and it handles HTTP requests and produces responses.
Code for creating user session?
// 1. get the user's session object (create it if it does not exist) HttpSession sess = request.getSession(true); // 2. store information in the session sess.setAttribute("sessionid", "123"); // 3. read information from the session String sid = (String) sess.getAttribute("sessionid"); // 4. terminate the session sess.invalidate();
Why HTTP is stateless protocol? Give example.
HTTP is stateless because every request is treated independently: after the server sends the response, the connection and all information about that request are forgotten, and the server keeps no memory of earlier requests from the same client. The protocol was designed this way to be simple and scalable. Example: a user logs on to an online bookshop, adds books to a cart on page 1, enters a billing address on page 2 and submits the order on page 3. HTTP itself does not remember the choices made on page 1 when page 3 is requested, so session tracking (cookies, URL rewriting, hidden fields, HttpSession) is needed.
Write any 6 EL operators?
Any six of: + (addition), - (subtraction), * (multiplication), / or div (division), % or mod (remainder), == or eq, != or ne, < or lt, > or gt, <= or le, >= or ge, && or and, || or or, ! or not, empty.
JSP code for action element <jsp:setProperty name = "name" value = "raza"/>
<jsp:setProperty> calls the setter method of the bean, so the equivalent scriptlet is <% name.setXxx("raza"); %>, where name is the bean id and Xxx is the property. The given tag is missing the required property attribute, for example <jsp:setProperty name="name" property="studentName" value="raza"/> is equivalent to <% name.setStudentName("raza"); %>.
Write JavaBean code which passes two variables name and address?
package vu; import java.io.Serializable; public class PersonBean implements Serializable { private String name; private String address; public PersonBean() { name = ""; address = ""; } public void setName(String n) { name = n; } public String getName() { return name; } public void setAddress(String a) { address = a; } public String getAddress() { return address; } }
Which layer supports applet and servlet?
Applets run on the client side, so they support the client (presentation) tier/layer in the browser. Servlets run on the server, so they support the server-side presentation layer (web tier) and can control the flow of the application.
Difference between applet and servlet
An applet is a Java program that is downloaded and runs inside the web browser on the client machine, has a GUI, and runs in a security sandbox (life cycle init, start, stop, destroy). A servlet is a Java program that runs on the server inside a web container, has no GUI, handles HTTP requests and sends responses (usually HTML) back to the client (life cycle init, service, destroy).
Write code of join thread.
class Worker implements Runnable { public void run() { for (int i = 0; i < 5; i++) { System.out.println("worker " + i); } } } public class JoinEx { public static void main(String args[]) { Thread t = new Thread(new Worker()); t.start(); try { t.join(); // main waits until t finishes } catch (InterruptedException e) { System.out.println(e); } System.out.println("worker finished, main continues"); } }
403 error code
HTTP status code 403 (Forbidden) means the server understood the request but access to the requested resource is denied.
Nuggets of EL expression
The main features ("nuggets") of EL are: - EL syntax ${expression} - expressions and identifiers - arithmetic, logical and relational operators - automatic type conversion - access to beans, arrays, lists and maps - access to a set of implicit objects
Get a number in scriptlet, take its square and show the result in expression.
<% int n = Integer.parseInt(request.getParameter("num")); int square = n * n; %> Square of <%= n %> is <%= square %>
Difference between template and non template
Non-template technologies (CGI programs and servlets) generate the whole HTML page from program code, for example with println() statements, so page design is mixed into the code. Template-based technologies (ASP, PHP, JSP) write the page mainly as an HTML template and embed code only in the dynamic parts, which makes it easier to design complex pages.
What is the alternative of constructor in servlet?
init() is used instead of a constructor. A servlet is created by the container, so we do not write initialization in a constructor; init() is executed once when the servlet is first loaded, not for each request, so it is the place for one-time initialization such as loading resources or reading parameters.
What does 200 code indicate?
HTTP status code 200 (OK) means the request was successful and everything is fine. Codes in the 200s mean success.
What is other name of business layer?
The business layer is also called the application layer.
Write methods used to get values from HTML page?
HttpServletRequest methods used to read HTML form data: - getParameter(String name): returns the value of one parameter as a String. - getParameterValues(String name): returns a String array of all values of a parameter (for example checkboxes). - getParameterNames(): returns an Enumeration of all parameter names. Example: String n = request.getParameter("id");
What is alternative code of jsp special tag useBean?
<jsp:useBean id="m" scope="page" class="vu.MyBean" /> is equivalent to creating the object in a scriptlet: <% vu.MyBean m = new vu.MyBean(); %> (useBean also stores the object in the given scope and reuses an existing one if found.)
Write path of JAVA_HOME variable?
JAVA_HOME must point to the root (base installation) directory of the JDK, not to its bin subdirectory, for example C:\Program Files\Java\jdk1.8.0 . Tomcat uses it to find Java.
How servlet is more efficient than CGI?
Servlets are more efficient than CGI because a CGI program starts a new operating-system process for each request, while a servlet is loaded once and stays in memory, and each request is handled by a lightweight thread inside the same JVM. Servlets can keep data and resources (such as database connections) between requests, share data with other servlets, and are portable because they are written in Java.
Write an EL expression which checks that x is greater than or equal to 5 and less than 10.
${x >= 5 && x < 10}
As a java developer you have to keep record of visiting users who add contents to your site. How you will do it?
Use session tracking. When a user logs in or first visits, create a session (request.getSession(true)) or a cookie that identifies the user, and store the user's ID in it. Whenever the user adds content, read the user ID from the session, and save the record (user ID, content, date and time) in a database with JDBC. Later the stored records can be read to see which users visited and what they added.
Write tag library of these: EL based internationalization; RT based xml
EL-based internationalization (formatting) library: <%@ taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt" %> RT-based XML library: <%@ taglib uri="http://java.sun.com/jstl/xml_rt" prefix="x_rt" %>
Why controller is implemented as servlet?
The controller only processes requests: it reads input, calls the model (JavaBeans) and selects the next view, and it has no presentation of its own. JSPs are meant for presentation (views), so they are not a good place for such logic. Servlets are Java classes made for processing, so the controller is implemented as a servlet.
HTTP is a stateless protocol, what do we need to do in order to make it possible for it to maintain states?
Because HTTP is stateless, we must use session tracking. Typical solutions are cookies, URL rewriting and hidden form fields (and the HttpSession API built on them).
Correct the following path for setting JAVA_HOME variable: C:\program files\java\JDK-Root-Directory\bin
JAVA_HOME should point to the JDK root directory, not to bin: C:\program files\java\JDK-Root-Directory
Give one advantage and two disadvantages of page centric approach
Advantage: the page-centric approach is simple and easy to implement, so it is easy to get started with web application development. Disadvantages (any two): 1. The code becomes a mixture of presentation, business and data access logic. 2. Maintenance of the application becomes a nightmare. 3. A lot of code is duplicated, and scaling is difficult.
What problem can arise if a process A that needs 20 iterations to execute has highest priority while process B needs 5 iterations but has lowest priority? Explain with reason
Starvation. The scheduler always prefers the highest-priority runnable thread, so process A (highest priority) keeps the CPU until it finishes, sleeps, waits or yields. Process B (lowest priority) gets no chance to run while A is running, even though B needs only a few iterations; if A runs for a long time or never gives up the CPU, B starves. This is avoided if the high-priority thread calls sleep() or yield() regularly, or if priorities are used carefully.
Which HttpServletRequest object methods are used to read the HTML form data submitted by user?
HttpServletRequest methods used to read HTML form data: - getParameter(String name): returns the value of one parameter as a String. - getParameterValues(String name): returns a String array of all values of a parameter (for example checkboxes). - getParameterNames(): returns an Enumeration of all parameter names. Example: String n = request.getParameter("id");
Web Service and web pages difference
Web page: - has a user interface (GUI) - interacts with a human user - works with a web browser client Web service: - has no GUI - interacts with other applications, using XML messages over standard protocols - works with any type of client application A web application can use several web services to do its work.
Write the method (syntax) of writing an action element of JSP.
JSP action elements are written in XML syntax: <jsp:actionElement attribute="value" ...> body </jsp:actionElement> or, without a body: <jsp:actionElement attribute="value" ... /> Example: <jsp:useBean id="p" class="vu.PersonBean" scope="page" />
Differentiate between MVC1 and MVC2 with respect to view.
MVC Model 1: JSP pages receive the requests, act as controllers and also produce the response (view); JavaBeans hold the business logic. Presentation and flow-control logic are mixed in JSPs, which is fine for small applications. MVC Model 2: a servlet acts as the controller that receives all requests, calls the model (JavaBeans) and selects the view; JSP pages are used only for presentation (views) to show the response. This gives clear separation of presentation, business and control logic and is better for large applications.
What is the disadvantage of threading using inheritance?
If we create a thread by extending the Thread class, our class cannot extend any other class, because Java supports only single inheritance. It also couples the task with the thread mechanism. Implementing Runnable avoids this.
Write the two ways to read initialization parameters from servlet?
1. Servlet initialization parameters, defined with <init-param> inside the servlet's <servlet> tag in web.xml, are read through ServletConfig: getServletConfig().getInitParameter("name") (or getInitParameter("name") directly in the servlet). 2. Context initialization parameters, defined with <context-param> in web.xml for the whole application, are read through ServletContext: getServletContext().getInitParameter("name").
What is difference b/w EJB and JavaBeans?
JavaBeans are ordinary reusable Java classes that follow simple design conventions (no-argument constructor, getters/setters, serializable). They run in the same JVM as the code that uses them (for example JSPs and servlets in a web container) and get no special services. EJBs (Enterprise JavaBeans) are server-side components that encapsulate business logic and run in an EJB container in an application server. The container gives them services such as transactions, security, remote access, persistence and scalability, so they are used to build large distributed enterprise applications.
How to declare functions and variables in JSP action elements?
Variables and methods are declared with the JSP declaration element <%! ... %>, which is a scripting element, not an action element. In the XML syntax it is written as <jsp:declaration> int count = 0; public int add(int a, int b) { return a + b; } </jsp:declaration>. Declared variables become instance variables and methods become methods of the generated servlet.
How JSF does provide Navigation?
JSF navigation decides which page is shown next. JSF provides a default navigation handler that is configured with navigation rules in faces-config.xml. Each rule has a from-view-id and navigation cases; a navigation case maps an outcome string (from-outcome), returned by a command component's action or by an action method of a managed bean, to the next page (to-view-id). A fixed outcome gives static navigation, and an outcome returned by a method gives dynamic navigation. Tools can also define these rules visually.
What is the advantage of JSP over PHP?
Advantages of JSP over PHP: JSP uses Java, which is a better, more powerful language for the dynamic part, and JSP has better tool support. It is also portable across servers and operating systems and can use the full Java API.
What are implicit objects? List any two.
Implicit objects are variables that the JSP container creates automatically and that can be used directly in expressions and scriptlets without declaring them. Examples: request and response (also out, session, application, config, pageContext, page and exception).
Garbage collection.
Garbage collection is the automatic process by which the JVM frees memory used by objects that are no longer referenced by the program. The programmer does not free objects explicitly; System.gc() can only request it.
In which situation expression language can be used?
EL can be used in JSP pages (JSP 2.0 and later) in template text and in attributes of standard and custom tags, for example ${param.name}, to read request parameters, scoped attributes, bean properties, collections and implicit objects and to do simple operations, instead of writing Java expressions and scriptlets.
Expression language nuggets.
The main features ("nuggets") of EL are: - EL syntax ${expression} - expressions and identifiers - arithmetic, logical and relational operators - automatic type conversion - access to beans, arrays, lists and maps - access to a set of implicit objects
Write the lifecycle of servlet?
The servlet container controls the servlet life cycle: 1. Loading and instantiation of the servlet class. 2. Initialize: init() is called once, for one-time setup. 3. Service: service() is called for each request and passes it to doGet()/doPost(). 4. Destroy: destroy() is called once before the servlet is removed, to release resources; then it is garbage collected.
What does servlet context mean?
ServletContext is an object created by the container for each web application. All servlets and JSPs of that application share it, so it is used to share resources and attributes among them, read application-wide context parameters from web.xml, and get RequestDispatchers.
What is meant by hidden comment?
A hidden comment is a JSP comment that documents the JSP page but is not sent to the client. The JSP container ignores it during translation, so it does not appear in the page source in the browser. Syntax: <%-- comment text --%> Example: <%-- This part shows the user list --%>
What is socket?
A socket is one endpoint of a two-way communication link between two programs running on a network. It is identified by an IP address and a port number.
What is JSP scriptlet?
A JSP scriptlet is a block of Java code inside a JSP page, written as <% Java statements %>. The code is placed in the _jspService() method of the generated servlet and runs for every request.
What types of web services are available?
Types of web services: - Data providers, for example a service providing stock quotes. - Business-to-business process integration, for example purchase orders. - Enterprise application integration, where different applications work together by adding a web service wrapper.
Hidden comments in JSP
A hidden comment is a JSP comment that documents the JSP page but is not sent to the client. The JSP container ignores it during translation, so it does not appear in the page source in the browser. Syntax: <%-- comment text --%> Example: <%-- This part shows the user list --%>
W3C definition (of web service)
According to W3C, a web service is a software application identified by a URI whose interfaces and bindings can be defined, described and discovered by XML artifacts, and which supports direct interactions with other software applications using XML-based messages over Internet-based protocols.
What is meant by keyword transient?
The transient keyword marks a field that must not be serialized. When the object is written with ObjectOutputStream the field is skipped, and after deserialization it gets its default value.
What are basic features of HTTP?
Basic features of HTTP: - It is a request/response protocol between a client (browser) and a server. - It is stateless: each request is independent and the server keeps no memory of earlier requests. - It is connectionless at the application level: the client sends a request, gets a response and the exchange ends. - It is media independent: any type of data can be sent if both sides know its content type. - It runs over TCP (port 80 by default) and uses methods such as GET and POST and status codes such as 200 and 404.
Request Dispatching methods.
Request dispatching lets a servlet forward a request to another resource or include another resource's output. A RequestDispatcher is obtained with getRequestDispatcher(path), and it has two methods: forward(request, response) and include(request, response).
Sequential Execution and Multi Threading.
In sequential execution a program has a single thread, so instructions run one after another: a statement starts only after the previous one (or a called function or loop) is finished. In multithreading a program has several threads that run concurrently, so different tasks (for example reading input and doing a calculation) can progress at the same time and the program can use the CPU better and stay responsive.
Checked and Unchecked Exceptions.
Checked exceptions are subclasses of Exception other than RuntimeException (for example IOException). They must be caught or declared in a throws clause, otherwise the compiler gives an error. Unchecked exceptions are RuntimeException, Error and their subclasses (for example NullPointerException). The compiler does not require them to be handled.
JSF Navigation.
JSF navigation decides which page is shown next. JSF provides a default navigation handler that is configured with navigation rules in faces-config.xml. Each rule has a from-view-id and navigation cases; a navigation case maps an outcome string (from-outcome), returned by a command component's action or by an action method of a managed bean, to the next page (to-view-id). A fixed outcome gives static navigation, and an outcome returned by a method gives dynamic navigation. Tools can also define these rules visually.
main() with static and without static
main() is declared static so that the JVM can call it without creating an object of the class (the JVM has no object yet when the program starts), and there is only one copy per class. If static is removed, the class still compiles, but on JDK versions that require a static main the launcher reports an error that main must be static, because it would need an object to call an instance method.
2 steps of painting strategy
1. Subclass JPanel (or another JComponent). 2. Override its paintComponent(Graphics g) method and do the drawing there (calling super.paintComponent(g) first).
When run() method is invoked?
run() is invoked by the JVM after the thread's start() method is called. start() creates the new thread and the JVM then calls run() in that thread. Calling run() directly does not start a new thread; it just runs as a normal method in the current thread.
Difference b/w encodeURL and encodeRedirectURL
encodeURL() is used for URLs embedded in the page that the servlet generates, for example links: String eURL = response.encodeURL("/servlet/sessiontracker"); out.println("<a href=\"" + eURL + "\">Next</a>"); encodeRedirectURL() is used for URLs passed to sendRedirect(): String eURL = response.encodeRedirectURL("/servlet/sessiontracker"); response.sendRedirect(eURL); Both add the session ID to the URL only when it is needed (cookies disabled).
What are the disadvantages of URL rewriting?
Disadvantages of URL rewriting: - If the user bookmarks a page, the stored URL contains old session data, and the problem gets worse if the server does not assign unique session IDs. - Unlike cookies, the state stored in the URL is not persistent. - It limits client interaction with the server to HTTP GET requests (every link must be rewritten), and the data is visible in the URL.
What are java beans?
A JavaBean is a reusable Java class that follows certain design conventions: a public no-argument constructor, private properties accessed through public getter and setter methods, and it is usually serializable. Such classes can be easily reused and composed together in an application.
Define web service according to W3C
According to W3C, a web service is a software application identified by a URI whose interfaces and bindings can be defined, described and discovered by XML artifacts, and which supports direct interactions with other software applications using XML-based messages over Internet-based protocols.
Can we overload main method?
Yes, main can be overloaded with different parameter lists. But the JVM starts the program only with the standard public static void main(String[] args); the other versions are ordinary methods that must be called explicitly.
When thread’s run() method is invoked?
run() is invoked by the JVM after the thread's start() method is called. start() creates the new thread and the JVM then calls run() in that thread. Calling run() directly does not start a new thread; it just runs as a normal method in the current thread.
Which listener interfaces are used to handle mouse events?
Two listener interfaces handle mouse events: - MouseListener: mouseClicked(), mousePressed(), mouseReleased(), mouseEntered() and mouseExited(MouseEvent e). - MouseMotionListener: mouseMoved() and mouseDragged(MouseEvent e), for events generated when the mouse is moved or dragged. (MouseWheelListener handles mouse wheel events, and MouseAdapter can be used instead of implementing all methods.)
Why client side validation is used?
Client-side validation (for example with JavaScript) is used because it is fast: input is checked in the browser before the form is submitted, without a round trip to the server, which also reduces server load. It can show one error at a time and focus the wrong field, helping the user fill in all the required details correctly. (Server-side validation is still needed for security.)
Write three types of custom tags
Three types of custom tags: 1. Simple tag: a tag without body and without attributes, for example <mytag:hello/>. 2. Tag with attributes, for example <mytag:hello name="ali"/>. 3. Tag with body, for example <mytag:hello>body text</mytag:hello>.
Differentiate sleeping and yielding in threads
sleep(ms) makes the current thread stop for the given time even if no other thread is waiting; the thread does not use the CPU during that time, it can be interrupted (InterruptedException), and lower-priority threads can also run. yield() only gives up the CPU for a moment so other runnable threads of the same priority can run; if none is waiting, the thread continues immediately.
Why session tracking is used in HttpServlets?
HTTP is a stateless protocol, so an HTTP servlet cannot remember a user between requests. Session tracking is used to associate a series of requests from the same user and keep the user's state, for example a logged-in user or the items in a shopping cart in an e-commerce application.
What are streams?
A stream is an abstraction that represents a data source or destination (file, network, memory) as an object that produces or receives data in sequence. Java I/O uses input streams to read data and output streams to write data (byte streams and character streams).
Differentiate layers and tiers
Layers are the logical grouping of an application's software components (for example presentation, business and data layers). Tiers are the physical machines or processes on which those layers are deployed. So layers give the logical view of an application and tiers give its physical view; one tier can hold several layers.
What is the difference between getRequestDispatcher(String path) method using javax.servlet.ServletRequest or using ServletContext?
The getRequestDispatcher(String path) method of ServletRequest accepts a relative path, interpreted relative to the current request; a path starting with "/" is relative to the context root. The method of ServletContext does not accept relative paths: the path must start with "/" and is interpreted relative to the context root.
Which containers use a border layout as their default layout?
Window, Frame and Dialog (and their Swing versions JWindow, JFrame and JDialog, whose content panes) use BorderLayout as their default layout.
How can one swap two variables without a third variable?
class Swap { public static void main(String args[]) { int a = 1; int b = 2; System.out.println("Before swap: a=" + a + " b=" + b); a = a ^ b; b = a ^ b; a = a ^ b; System.out.println("After swap: a=" + a + " b=" + b); } } (With arithmetic: a = a + b; b = a - b; a = a - b;)
How and why we use JSP include directive?
The include directive inserts the content of another file (HTML, JSP, text) into the JSP page at translation time: <%@ include file="header.jsp" %> It is used to reuse common parts, such as headers, footers and menus, in many pages, so they are written once and maintained in one place. Because inclusion happens at translation time, the included content becomes part of the generated servlet.
Why we need tiers as we already have layers?
Layers are only a logical separation. Tiers are the physical separation of these layers onto different machines or processes. Tiers are needed for scalability, performance, security and maintenance: layers are spread across tiers (two or more layers can be on one tier), so parts of the application can be distributed and scaled separately. Layers help in building the tiered architecture.
Why we use expression language?
Expression Language (EL) simplifies JSP pages. It gives a short syntax ${...} to read objects and their properties (beans, request parameters, scoped attributes, collections) and to do simple arithmetic, logical and relational operations without Java scriptlets. It removes most Java code from pages, makes them easier for page designers, and does not throw NullPointerException for null values.
Define web service by W3C?
According to W3C, a web service is a software application identified by a URI whose interfaces and bindings can be defined, described and discovered by XML artifacts, and which supports direct interactions with other software applications using XML-based messages over Internet-based protocols.
List any two scopes of the Java Bean?
Any two of the four scopes of a JavaBean (used in jsp:useBean): page, request, session and application.
How JSF navigation works?
JSF navigation decides which page is shown next. JSF provides a default navigation handler that is configured with navigation rules in faces-config.xml. Each rule has a from-view-id and navigation cases; a navigation case maps an outcome string (from-outcome), returned by a command component's action or by an action method of a managed bean, to the next page (to-view-id). A fixed outcome gives static navigation, and an outcome returned by a method gives dynamic navigation. Tools can also define these rules visually.
List implicit objects?
JSP implicit objects: request, response, out, session, application, config, pageContext and page; exception is also available in error pages.
Name any four container classes?
Any four of: JFrame (Frame), JDialog (Dialog), JWindow (Window), JPanel (Panel), JApplet (Applet), ScrollPane/JScrollPane, FileDialog.
What is the difference between variable declared inside a declaration part and variable in scriplet part?
A variable declared in a JSP declaration (<%! int x; %>) becomes an instance variable of the generated servlet class. It is created once, keeps its value between requests and is shared by all requests. A variable declared in a scriptlet (<% int x; %>) becomes a local variable of the _jspService() method, so it is created again for every request and is visible only inside that method.
Which types of web services are available?
Types of web services: - Data providers, for example a service providing stock quotes. - Business-to-business process integration, for example purchase orders. - Enterprise application integration, where different applications work together by adding a web service wrapper.
What is meant by statement “classes implement interfaces”?
When a class implements an interface, it promises to provide bodies for all the abstract methods declared in that interface. The interface specifies the behaviour (what methods objects of the class have), and the class provides the implementation. Objects of the class can then be used wherever the interface type is expected.
Which technology is used in java to support the following layers? Presentation layer, Business Layer, Data Layer
Java technologies for each layer: - Presentation layer: JSP, servlets, JSF (and HTML/JavaScript, applets or Swing on the client). - Business layer: JavaBeans or Enterprise JavaBeans (EJB). - Data layer: JDBC (and related data access technologies).
Difference b/w web page and web service
Web page: - has a user interface (GUI) - interacts with a human user - works with a web browser client Web service: - has no GUI - interacts with other applications, using XML messages over standard protocols - works with any type of client application A web application can use several web services to do its work.
How to include classes in JSP?
Classes are imported in a JSP page with the import attribute of the page directive, for example <%@ page import="java.util.List, vu.MyClass" %>; classes from packages are then used in scriptlets. (User classes must be in a package and placed in WEB-INF/classes.)
Features of JSF
Features of JSF: - Standard component-based web framework for building user interfaces. - Rich set of reusable UI components, and custom components can be created. - Event handling on the server (action and value-change events). - Managed beans with value binding and method binding (#{...}). - Built-in validators and converters for user input. - Navigation rules defined in a configuration file (faces-config.xml). - Independent of the rendering device, and supported by visual tools.
Difference between MVC1 and MVC2
MVC Model 1: JSP pages receive the requests, act as controllers and also produce the response (view); JavaBeans hold the business logic. Presentation and flow-control logic are mixed in JSPs, which is fine for small applications. MVC Model 2: a servlet acts as the controller that receives all requests, calls the model (JavaBeans) and selects the view; JSP pages are used only for presentation (views) to show the response. This gives clear separation of presentation, business and control logic and is better for large applications.
Difference between normal beans and EJBs
JavaBeans are ordinary reusable Java classes that follow simple design conventions (no-argument constructor, getters/setters, serializable). They run in the same JVM as the code that uses them (for example JSPs and servlets in a web container) and get no special services. EJBs (Enterprise JavaBeans) are server-side components that encapsulate business logic and run in an EJB container in an application server. The container gives them services such as transactions, security, remote access, persistence and scalability, so they are used to build large distributed enterprise applications.
How we can overcome starvation in priorities?
Starvation of low-priority threads is overcome by making the high-priority threads give up the CPU from time to time with sleep() (or yield(), wait()), so that lower-priority threads get a chance to run. Using fair scheduling, avoiding very different priorities, or gradually raising the priority of threads that have waited long (aging) also helps.
EL version and RT version
JSTL has two versions of its libraries: - EL version: tag attributes take EL expressions, for example <c:out value="${param.name}"/>; it is used with JSP 2.0 and later. - RT (request-time) version: tag attributes take JSP request-time expressions, for example <c_rt:out value="<%= request.getParameter(\"name\") %>"/>; it is compatible with earlier JSP versions that do not support EL. They use different taglib URIs (for example .../jstl/core and .../jstl/core_rt).
Write page directive syntax
<%@ page attribute="value" %>, for example <%@ page import="java.util.*" contentType="text/html" %>
Write web.xml where name is welcome
<?xml version="1.0" encoding="UTF-8"?> <web-app> <servlet> <servlet-name>welcome</servlet-name> <servlet-class>welcome</servlet-class> </servlet> <servlet-mapping> <servlet-name>welcome</servlet-name> <url-pattern>/welcome</url-pattern> </servlet-mapping> </web-app>
Information present in .tld file?
A tag library descriptor (.tld) is an XML document that describes a custom tag library for the JSP container. It contains, for example: - tag library version (tlib-version) - JSP version (jsp-version) - short name of the library - each tag's name - tag handler class name (tag-class) - body content type - attribute names and whether they are required.
Benefits of a custom tag
Advantages of custom tags: - They separate processing logic from presentation and remove scriptlets from JSP pages. - They have an HTML-like syntax that page designers can use without knowing Java. - They are reusable in many pages, which saves development and testing time. - They can be customized with attributes and body content. - They have access to JSP implicit objects such as out and request.
Why cookies are better than URL rewriting?
Cookies are better than URL rewriting because the state is kept by the browser and sent automatically with every request, so every link does not need to be rewritten. Cookies can persist after the browser is closed (setMaxAge), they work with GET and POST, and the data does not appear in the URL, so it is not exposed and bookmarking pages does not cause problems.
Name of action elements in java bean
JSP action elements for JavaBeans: - <jsp:useBean /> finds or creates a bean object. - <jsp:setProperty /> sets a property of the bean. - <jsp:getProperty /> gets a property value of the bean and writes it to the output.
Syntax of EL
EL syntax: ${expression}, for example ${param.name} or ${user.address.city}.
Disadvantage of page centric approach
In the page-centric approach the code becomes a mixture of presentation, business and data access logic, so maintenance and upgrading become very difficult. Much code is duplicated across pages and the application is hard to scale.
Declare a private integer variable in JSP declaration tag
<%! private int id; %>
Three session tracking techniques
Common session tracking methods are: 1. Cookies 2. URL rewriting 3. Hidden form fields The Servlet API also provides HttpSession, which is built on these.
What does response code 403 indicate?
HTTP status code 403 (Forbidden) means the server understood the request but access to the requested resource is denied.
Why JSP is considered better than ASP?
JSP is considered better than ASP because it uses Java, a more powerful and widely supported language for the dynamic part, and JSP is portable to many servers and operating systems, while classic ASP works mainly on Microsoft IIS/Windows. JSP pages also become servlets, so they get Java's performance, security and reuse of JavaBeans and custom tags.
Page centric approach advantage
Advantage of the page-centric approach: it is simple and easy to implement, so it is quick to get started with web application development.
Where to use yield() method in multithreading?
yield() makes the currently running thread give up the CPU so that other threads of the same priority can run; the thread moves to the end of the queue for its priority. If all waiting threads have lower priority, the yielding thread continues to run. It is used in long-running loops so that equal-priority threads get a fair chance.
Difference between doGet and doPost
doGet() handles HTTP GET requests: parameters are appended to the URL as a query string, so they are visible, the amount of data is limited, and the request can be bookmarked; it is used for small, non-sensitive data such as search queries. doPost() handles HTTP POST requests: parameters are sent in the body of the request, not in the URL, so large amounts of data can be sent and they are not visible in the URL; it is used for form submissions and sensitive data such as login ID and password.
Expression Language
The Expression Language (EL) is not a programming or scripting language; it gives a simple way to write expressions in JSP (JSP 2.0 and later). It is geared towards looking up objects and their properties and doing simple operations on them, and is inspired by ECMAScript and XPath. - Syntax: ${expression}, which can be mixed with static text. - Can read request parameters, scoped attributes, bean properties, arrays, lists and maps (with . and [] operators). - Has arithmetic, relational, logical and empty operators. - Gives implicit objects such as param, header, cookie, pageScope, requestScope, sessionScope and applicationScope. - Converts types automatically and does not throw NullPointerException for null values. It removes most Java code from JSP pages.
Why threads are called light weight?
Threads are called lightweight because they need fewer resources than processes. Threads of one process share the same address space, memory and resources, so creating, destroying and switching between threads is much cheaper than for processes, and threads can share data directly.
Name of techniques for client and server side validation
Client-side validation: JavaScript code in the browser checks the form fields before the form is submitted. Server-side validation: the input is checked on the server, for example in servlets/JSP code, JavaBeans, or with JSF validators (built-in or custom).
Difference between cooperative and preemptive multithreading
In cooperative multithreading, a running thread keeps the CPU until it voluntarily gives up control (for example by yielding) or blocks. In preemptive multithreading, the scheduler (JVM/OS) can stop a running thread at any time and give the CPU to another thread, for example a higher-priority thread or after its time slice ends.
Every java class should fulfill some requirements to become java bean. What are these requirements?
Requirements (design conventions) for a JavaBean: - It must have a public no-argument (zero-argument) constructor. - It should not have public instance variables; fields are private. - Private values are accessed through public getter and setter methods (getXxx()/setXxx(); isXxx() for boolean properties). - It should implement java.io.Serializable.
Ways to read initialization parameters of servlet (servlet context init parameters, servlet init parameters)
1. Servlet initialization parameters, defined with <init-param> inside the servlet's <servlet> tag in web.xml, are read through ServletConfig: getServletConfig().getInitParameter("name") (or getInitParameter("name") directly in the servlet). 2. Context initialization parameters, defined with <context-param> in web.xml for the whole application, are read through ServletContext: getServletContext().getInitParameter("name").
Why HTTP protocols are stateless?
HTTP is stateless because every request is treated independently: after the server sends the response, the connection and all information about that request are forgotten, and the server keeps no memory of earlier requests from the same client. The protocol was designed this way to be simple and scalable. Example: a user logs on to an online bookshop, adds books to a cart on page 1, enters a billing address on page 2 and submits the order on page 3. HTTP itself does not remember the choices made on page 1 when page 3 is requested, so session tracking (cookies, URL rewriting, hidden fields, HttpSession) is needed.
Write code to set thread priority to maximum
Thread t = new Thread(new Worker()); t.setPriority(Thread.MAX_PRIORITY); t.start(); (For the current thread: Thread.currentThread().setPriority(Thread.MAX_PRIORITY);)
Code for multiplication and addition using EL (Expression Language)
Using EL, with num1 and num2 sent as request parameters: Sum is: ${param.num1 + param.num2} Product is: ${param.num1 * param.num2}
Core Tags formats
The JSTL core library is included with <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>. Its main tags and formats: - <c:set var="name" scope="page" value="expression"/> sets a scoped variable - <c:out value="${expression}" default="..."/> displays a value - <c:remove var="name" scope="page"/> removes a scoped variable - <c:if test="${condition}"> ... </c:if> conditional - <c:choose>, <c:when test="...">, <c:otherwise> for multiple conditions - <c:forEach var="item" items="${list}"> ... </c:forEach> iteration - <c:forTokens>, <c:import>, <c:url>, <c:param>, <c:redirect>, <c:catch>
Hidden form field
A hidden form field is an HTML input element that is not shown on the page but is sent to the server with the form, for example: <input type="hidden" name="sessionid" value="123"> It does not affect the appearance of the page. Because HTTP is stateless, hidden fields can carry information such as a session ID from page to page, so they are one technique of session tracking. They work only when pages are submitted through forms, and the value can be seen in the page source.
Which information is present in (.tld) file? Write any five.
A tag library descriptor (.tld) is an XML document that describes a custom tag library for the JSP container. It contains, for example: - tag library version (tlib-version) - JSP version (jsp-version) - short name of the library - each tag's name - tag handler class name (tag-class) - body content type - attribute names and whether they are required.
Write a servlet to show 3 lines, e.g. name, heading
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ShowServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html><body>"); out.println("<h1>Heading</h1>"); out.println("<p>Name</p>"); out.println("<p>Third line</p>"); out.println("</body></html>"); out.close(); } }
Cookies retrieving code
Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { Cookie c = cookies[i]; String name = c.getName(); String value = c.getValue(); out.println(name + " = " + value); } }
What is a Servlet?
A servlet is a Java class that runs on the server inside a web container and extends the capabilities of the server. It receives client requests (usually HTTP), processes them, and generates responses such as HTML pages. HTTP servlets extend javax.servlet.http.HttpServlet and override doGet()/doPost().
Why we use declaration tag?
The declaration tag <%! ... %> is used to declare variables and methods in a JSP page. Its code is placed in the generated servlet class outside the _jspService() method, so declared variables become instance variables that are created once and keep their values across requests, and declared methods can be called from scriptlets and expressions.
What is the difference between page-with-bean and MVC1?
In the VU handouts the page-with-bean approach is the same as MVC Model 1: the application is a collection of JSPs and JavaBeans, where the business and data logic is in beans and the JSPs (one of which may act as controller) handle the requests and display the results. The difference from page-centric is that logic moves into beans; the difference from MVC Model 2 is that no servlet controller is used.
As a web developer how you will read data from two different parameters?
Use getParameter() of the request object once for each parameter, for example: String name = request.getParameter("name"); String id = request.getParameter("id"); (getParameterValues() is used when one parameter has several values.)
Ways to read initialization parameter of servlet
1. Servlet initialization parameters, defined with <init-param> inside the servlet's <servlet> tag in web.xml, are read through ServletConfig: getServletConfig().getInitParameter("name") (or getInitParameter("name") directly in the servlet). 2. Context initialization parameters, defined with <context-param> in web.xml for the whole application, are read through ServletContext: getServletContext().getInitParameter("name").
Steps required to send cookies to a browser
Steps to send a cookie to the browser: 1. Create a Cookie object with a name and a value: Cookie c = new Cookie("name", "value"); 2. Set cookie attributes if needed, for example how long it lasts (in seconds); by default it lasts only for the current browser session: c.setMaxAge(60); 3. Add the cookie to the HTTP response, otherwise it is not sent: response.addCookie(c);
Benefits of partitioning an application in logical layers
Benefits of partitioning an application into logical layers: - Separation of concerns: presentation, business and data logic are kept apart. - Easier maintenance: a change in one layer (for example the database) affects the others little. - Reuse of business and data components by different user interfaces. - Different people can work on different layers in parallel. - Layers can be placed on different tiers for scalability and security.
Purpose of error page
Error pages let an application show a user-friendly message instead of a raw exception or stack trace when an error occurs. They keep error handling in one place: a page marks itself with isErrorPage="true", and other pages point to it with errorPage="..." in the page directive (or web.xml maps status codes and exception types to error pages).
Difference b/w web server and web application
A web server is software that hosts websites and applications: it accepts HTTP requests from clients and returns responses, for example Apache Tomcat or IIS. A web application is a program (for example a collection of servlets, JSPs, HTML pages, classes and web.xml) that is deployed on a web server and performs a task for users through the browser.
Problem with servlet regarding HTML
In servlets, HTML has to be generated with many out.println() statements inside Java code. This is hard to write, read and maintain, any change in page design needs a change in Java code and recompilation, and page designers cannot use HTML tools. Presentation and business logic get mixed. JSP was introduced to solve this.
Which package contains servlet related classes?
The javax.servlet package (generic servlet classes and interfaces such as Servlet, GenericServlet, ServletRequest, ServletResponse, ServletContext, RequestDispatcher) and the javax.servlet.http package (HTTP-specific classes such as HttpServlet, HttpServletRequest, HttpServletResponse, HttpSession, Cookie).
Web service or web page
Web page: - has a user interface (GUI) - interacts with a human user - works with a web browser client Web service: - has no GUI - interacts with other applications, using XML messages over standard protocols - works with any type of client application A web application can use several web services to do its work.
Disadvantages of using interfaces
Disadvantages of interfaces: - A class that implements an interface must provide bodies for all its abstract methods, even ones it does not need. - Interfaces (as taught in the course) contain no implementation and no instance variables, so code cannot be reused through them. - If a new method is added to an interface later, all classes that implement it must be changed.
What is the value of scope attribute in JSP?
The scope attribute of <jsp:useBean> can have one of four values: page, request, session or application. If the scope attribute is omitted, the default value is page.
Implicit object variables are 8: response, request, out and 5 others were to be written.
JSP implicit objects: request, response, out, session, application, config, pageContext and page; exception is also available in error pages.
Tell the difference between two statements: 1) import java.util.ArrayList; 2) import java.util.*;
import java.util.ArrayList; imports only the ArrayList class from java.util (single-type import). import java.util.*; imports all public classes and interfaces of the java.util package that are used in the file (on-demand import), for example ArrayList, Date, Vector. It does not import sub-packages. Neither form changes the size or speed of the compiled program.
When we set CATALINA_HOME while configuration, what does this refer to?
CATALINA_HOME refers to the root (installation) directory of Tomcat, for example C:\jakarta-tomcat-5.5.9 . Tomcat scripts use it to find Tomcat's files.
What is use of dot (.) operator in EL (expression language)? Give one example.
The dot (.) operator in EL accesses a property of a bean or a value of a map by name. For example ${student.name} calls getName() on the student bean, and ${param.id} reads the id request parameter. ${student.address.city} accesses a nested property.
How do we define and use error pages in JSP?
An error page is defined by a JSP that declares <%@ page isErrorPage="true" %>; it can use the exception implicit object, for example <%= exception.getMessage() %>. Other pages use it by setting the errorPage attribute of the page directive: <%@ page errorPage="error.jsp" %>. If an unhandled exception is thrown in such a page, the request is forwarded to the error page.
Write a single line to include a page “vuHome.java” using custom tags. You can use any name for tags but mention which name you have chosen for which tag element.
For example: <vu:include page="vuHome.java" /> Here vu is the prefix (declared with the taglib directive), include is the tag name, and page is the attribute that gives the file to include.
Suppose you are to develop a program that keeps watching on the new files shared by the user so that we may verify and add them in required destination. For keep watching which approach you will use? Briefly explain how you will use this?
Use multithreading. Create a separate background thread (implement Runnable or extend Thread) whose run() method checks the shared folder in a loop for new files, verifies them and moves or copies them to the destination, then calls Thread.sleep() for some time before checking again. This way the watching runs continuously without blocking the main program.
In JSP useBean action element an attribute scope is used. What are possible values of scope attribute? If we omit scope attribute then which default value will be used?
The scope attribute of <jsp:useBean> can have one of four values: page, request, session or application. If the scope attribute is omitted, the default value is page.
How web services communicate with each other?
Web services communicate by exchanging XML messages over standard Internet protocols, mostly HTTP. The messages are usually SOAP envelopes, the service interface is described in WSDL (Web Services Description Language), and services can be published and found through UDDI registries. Because everything is XML and standard protocols, services written in different languages and on different platforms can talk to each other.
Explain MVC2 with diagram
MVC Model 2 architecture: Browser -> (1) request -> Controller (servlet) -> (2) creates/uses Model (JavaBeans, database) -> (3) forwards to View (JSP) -> (4) response to browser. - Controller: a servlet receives all requests, reads input, calls the model and selects which view to show (using RequestDispatcher forward). - Model: JavaBeans contain the business logic and data access and hold the data. - View: JSP pages only present the data from the model to the user. This separates control, business and presentation logic, making large applications easier to maintain.
Initialize two parameters: one for text (file.txt) and other for DSN (studentDSN)
<servlet> <servlet-name>MyServlet</servlet-name> <servlet-class>MyServlet</servlet-class> <init-param> <param-name>fileName</param-name> <param-value>file.txt</param-value> </init-param> <init-param> <param-name>dsn</param-name> <param-value>studentDSN</param-value> </init-param> </servlet> In the servlet they are read with getInitParameter("fileName") and getInitParameter("dsn").
How pages know about errors?
A JSP page is told about its error page with the errorPage attribute of the page directive, for example <%@ page errorPage="error.jsp" %>. If an uncaught exception occurs, the request is forwarded to that page. The error page itself declares <%@ page isErrorPage="true" %> so it can use the exception implicit object.
Write 1 advantage and 2 disadvantages of JSPs.
Advantage: JSP makes it easy to create dynamic HTML pages, because the page is mainly HTML with Java code only in some places, and HTML tools can be used. Disadvantages (any two): - Java code in scriptlets mixes presentation with business logic, so large pages become hard to maintain. - Errors are harder to find because the page is translated into a servlet, and the first request is slower because of translation and compilation.
If Process A needs 19 iterations but has highest priority and process B needs only 2 iterations but has lowest priority, what problem will arise? Explain with example.
Starvation. The scheduler always prefers the highest-priority runnable thread, so process A (highest priority) keeps the CPU until it finishes, sleeps, waits or yields. Process B (lowest priority) gets no chance to run while A is running, even though B needs only a few iterations; if A runs for a long time or never gives up the CPU, B starves. This is avoided if the high-priority thread calls sleep() or yield() regularly, or if priorities are used carefully.
Write java code that sets priority of a process to the highest
Thread t = new Thread(new Worker()); t.setPriority(Thread.MAX_PRIORITY); t.start(); (For the current thread: Thread.currentThread().setPriority(Thread.MAX_PRIORITY);)
Explain the working of MVC1 with diagram
MVC Model 1 working: Browser -> request -> JSP page (acts as controller and view) -> uses JavaBeans (model) -> database; the JSP then generates the response for the browser. - The JSP receives the request, reads the input and calls JavaBeans for business logic and data access. - The beans return the data, and the same JSP (or another JSP it links to) displays it. Flow control and presentation are both in JSPs, so this suits small applications.
What is package?
A package is a group of related classes and interfaces stored in one directory. It organizes files according to functionality, avoids name collisions and controls access. It is declared with the package statement at the top of a source file, for example package vu.cs506;, and used with import.
Write a servlet which displays “Hello world i am a student”.
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html><body>"); out.println("Hello world i am a student"); out.println("</body></html>"); out.close(); } }
What is alternative name of business layer?
The business layer is also called the application layer.
What is difference b/w HTML and JSP?
HTML is a markup language for static pages; the content is fixed and the browser displays it directly. JSP is a server-side technology: a JSP page contains HTML plus Java code, tags and EL, which run on the server to generate dynamic HTML for each request. JSP needs a web container (it is translated into a servlet), while HTML can be served by any web server.
D/b MVC1 and MVC2
MVC Model 1: JSP pages receive the requests, act as controllers and also produce the response (view); JavaBeans hold the business logic. Presentation and flow-control logic are mixed in JSPs, which is fine for small applications. MVC Model 2: a servlet acts as the controller that receives all requests, calls the model (JavaBeans) and selects the view; JSP pages are used only for presentation (views) to show the response. This gives clear separation of presentation, business and control logic and is better for large applications.
D/b EJBs and Beans
JavaBeans are ordinary reusable Java classes that follow simple design conventions (no-argument constructor, getters/setters, serializable). They run in the same JVM as the code that uses them (for example JSPs and servlets in a web container) and get no special services. EJBs (Enterprise JavaBeans) are server-side components that encapsulate business logic and run in an EJB container in an application server. The container gives them services such as transactions, security, remote access, persistence and scalability, so they are used to build large distributed enterprise applications.
What do setText() method and getText() do?
setText(String) sets (replaces) the text shown by a Swing component such as a JTextField, JLabel or JButton. getText() returns the component's current text as a String, e.g. to read what the user typed in a text field.
How JSP's are efficient?
A JSP page is translated into a servlet and compiled only once (on the first request or when it changes). Later requests are served by the already loaded compiled servlet, each handled by a lightweight thread rather than a new process, so JSPs are as fast as servlets while being easier to write and maintain.
If we do not want to include a controller in our application. Which layer of three layer architecture will control screen flow?
The presentation layer. Without a controller (page-centric / Model 1 approach) the JSP pages themselves decide the flow from one screen to the next.
If you want to send an error redirect to a web page. What method you will use for it. Write complete code syntax of required method.
Use sendError() of HttpServletResponse: public void sendError(int statusCode, String message), e.g. response.sendError(HttpServletResponse.SC_NOT_FOUND, "Page not found"); (to send the user to another page instead, response.sendRedirect("error.jsp") is used).
What is the advantage of having HTTP session?
HTTP is stateless, so an HTTP session lets the server identify the same user across several requests or visits. Data for that user (e.g. login details, shopping cart) is kept on the server in the session object as name/value attributes; only a session ID travels to the client, so sensitive data stays on the server, and the servlet API manages the ID through cookies or URL rewriting automatically.
Write a statement to use tag library "StudentInfo.tld" with prefix "student".
<%@ taglib uri="/WEB-INF/tlds/StudentInfo.tld" prefix="student" %>
What is the difference between web server and application server?
A web server receives HTTP requests and returns HTTP responses, mainly serving static content (HTML, images) and optionally running servlets/JSP through a web container. An application server is a complete server that provides the web container plus an environment for business components (e.g. EJBs) with services such as transactions, security, connection pooling and messaging. So an application server includes web-server capabilities but supports full enterprise applications.
Is it necessary that each try block must be followed by a catch block? Give reasons to support your answer.
No. A try block must be followed by at least one catch block or a finally block (or both). try-finally is legal: the exception is not handled there but propagates to the caller, while the finally block still runs for clean-up.
What is the purpose of hash maps in session tracking through cookies?
Each user's data (e.g. items selected) is kept in that user's own HashMap on the server. A global HashMap stores these per-user HashMaps against a unique session ID. The session ID is sent to the browser as a cookie and returned with every request, so the servlet uses it as the key to fetch the right user's HashMap.
If we will not give width and height in applet tag then which one will get true? - Applet will not run - Applet will run but not visible - Applet will run and visible
The applet will run but will not be visible. width and height give the applet's display area; without them the area has no size, so nothing is shown on the page.
When we use Page centric approach?
The page-centric approach is used for small, simple web applications with little business logic, such as prototypes or applications that will not grow. JSP pages handle requests directly, which is quick to build, but for larger applications maintenance and scaling become difficult because presentation, business and data-access code are mixed.
Write java code syntax which will create a cookie object c.
Cookie c = new Cookie("name", "value"); The Cookie constructor takes the cookie name and the cookie value.
Write a statement to call an error page along with the "source not found" message using request dispatching technique.
request.setAttribute("msg", "source not found"); RequestDispatcher rd = request.getRequestDispatcher("error.jsp"); rd.forward(request, response); The error page reads the message with request.getAttribute("msg").
Write any six features that JSF provide?
JSF provides: representing UI components; managing their state; handling events; input validation; data binding; automatic conversion; defining page navigation; supporting internationalization and accessibility.
Suppose you have two (index.jsp and error.jsp) files. You want, when index.jsp file generate any exception user should automatically jump error.jsp page. What you will write in page directive of index.jsp page to jump error.jsp page automatically. Also what you will write in page directive of error.jsp page to make it error page.
In index.jsp: <%@ page errorPage="error.jsp" %> In error.jsp: <%@ page isErrorPage="true" %> The second directive also makes the implicit exception object available in error.jsp.
What are advantages of hash tables?
A hash table stores key/value pairs and finds a value directly from its key, so insert, search and delete are very fast (about constant time on average). It grows automatically as entries are added, and java.util.Hashtable is synchronized, so it can be shared safely between threads.
Being a java front end web developer, write the characteristics of tag with body custom tag and also give example.
A tag with body has a start tag and an end tag with content between them; the tag handler can include, skip or process that body (and may also take attributes). Example: <mytag:bold>Hello</mytag:bold>, where the handler prints the body text in bold.
Why do we use Session Tracking in HttpServlet?
HTTP is stateless, so the server cannot tell that several requests come from the same user. Session tracking (cookies, URL rewriting, hidden fields or HttpSession) lets the servlet recognise the user across requests and keep user data such as login state or a shopping cart.
Write any three limitations of default ResultSet object.
1. It is not updatable (read-only, CONCUR_READ_ONLY), so data cannot be changed through it. 2. It is forward-only (TYPE_FORWARD_ONLY): the cursor moves only forward, once, and cannot go back or jump to a row. 3. Because it is not scrollable, methods such as previous(), absolute() or last() cannot be used, and it does not reflect changes made by others.
What refers to "this" in following statement and what is the meaning of following line in both cases if it returns true or false ? onsubmit="return validate_Form(this)"
Here this refers to the form object itself, which is passed to the JavaScript function validate_Form. If the function returns true, the form is submitted to the server; if it returns false, submission is cancelled and the user stays on the page to correct the input.
Suppose a web page is sending phone number and address of a student to server. Write servlet code which will read both values at server end. If any of value is blank show message "please enter value". Note: assume boxes names are phnumber and address. You are not required to write complete code. Write code that can perform required task.
String phone = request.getParameter("phnumber"); String address = request.getParameter("address"); PrintWriter out = response.getWriter(); if (phone == null || phone.trim().equals("") || address == null || address.trim().equals("")) { out.println("please enter value"); } else { out.println("Phone: " + phone + " Address: " + address); }
What is the purpose of try block in java program?
The try block encloses code that may throw an exception. If an exception occurs inside it, normal flow stops and control passes to the matching catch block (and then finally), so the program can handle the error instead of terminating.
How do we know which methods does web service provide?
A web service describes itself in a WSDL (Web Services Description Language) XML document, which lists its operations (methods), their parameters and return types, and where to call it. Clients can find the service and its WSDL through a UDDI registry.
See the code given below and convert scriptlet tag to equivalent jsp useBean action element. Consider StudentBean class is in package academic. <% StudentBean bean = new StudentBean(); %>
<jsp:useBean id="bean" class="academic.StudentBean" />
In term of coding event handling is three steps process. Writes these steps in correct order.
1. Create the components that can generate events (event generators), e.g. a JButton. 2. Build objects that can handle the events (event handlers) by implementing the listener interface, e.g. ActionListener with actionPerformed(). 3. Register the handler with the generator, e.g. button.addActionListener(handler).
Make three hidden fields for name, id and marks with any values you want?
<input type="hidden" name="name" value="Student" /> <input type="hidden" name="id" value="1" /> <input type="hidden" name="marks" value="80" /> (placed inside a form; the values are sent with the form and are not shown on the page)
The code given below is an ordinary java class. Convert it from ordinary java class to java bean class. public class StudentBean { String email; String address; // zero argument constructor public StudentBean( ){ email = ""; address = ""; } // standard setter public void setEmail(String n) { email = n; } // standard getter public String getEmail( ) { return email; } // standard setter public void setAddress(String n) { address = n; } // standard getter public String getAddress( ) { return address; } }//end class
The class already has a zero-argument constructor and getters/setters; to make it a proper bean, make the fields private and implement Serializable: import java.io.Serializable; public class StudentBean implements Serializable { private String email; private String address; public StudentBean() { email = ""; address = ""; } public void setEmail(String n) { email = n; } public String getEmail() { return email; } public void setAddress(String n) { address = n; } public String getAddress() { return address; } }
In which situation we can use Expression Language?
EL is used in JSP pages to read data without Java code: inside template text, e.g. ${param.name}; in attribute values of standard and custom/JSTL tags, e.g. <c:out value="${user.name}"/>; and to access scoped attributes, request parameters, headers, cookies, bean properties and collection elements, and to do simple arithmetic, logical and empty checks. It cannot be used inside scriptlets, expressions or declarations.
When do we need to make abstract class?
We make a class abstract when it represents a general concept that should not be instantiated, but should give common data and behaviour to its subclasses, and when some methods can only be declared (abstract methods) because each subclass must give its own implementation. Example: an abstract Shape class with an abstract calculateArea() method that Circle and Rectangle implement.
How clients find web services?
Clients find web services through a registry such as UDDI (Universal Description, Discovery and Integration). Providers publish their services there; a client searches the registry, gets the service's WSDL description (operations, messages, location) and then calls the service, normally with SOAP messages over HTTP.
Request of one page can be dispatched to other page using two methods. Write the code syntax of both methods.
Both use a RequestDispatcher: RequestDispatcher rd = request.getRequestDispatcher("next.jsp"); rd.forward(request, response); // forward: control passes fully to next.jsp RequestDispatcher rd = request.getRequestDispatcher("header.jsp"); rd.include(request, response); // include: output of header.jsp is added, then control returns
How we write include directive in JSP page. Write only JSP code syntax.
<%@ include file="relativeURL" %> For example: <%@ include file="header.jsp" %>
Write a method drawJava() that chooses random color from the standard RGB colors and prints "Hello" at 100 different locations with the specified color.
public void drawJava(Graphics g) { Random r = new Random(); for (int i = 0; i < 100; i++) { g.setColor(new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256))); int x = r.nextInt(400); int y = r.nextInt(400); g.drawString("Hello", x, y); } } (Needs import java.awt.*; and import java.util.Random; the method can be called from paintComponent()/paint() with its Graphics object.)
Does java support automatic type conversion? Support your answer.
Yes. Java automatically converts a value to another type when the conversion is widening and safe, i.e. the target type is compatible and larger, for example byte -> short -> int -> long -> float -> double: int i = 10; double d = i; // automatic conversion Narrowing conversions that may lose data (e.g. double to int) are not automatic and need an explicit cast: int j = (int) d;
Custom tags have three forms. Write the name of each form.
1. Simple tag (a tag without body and without attributes), e.g. <mytag:hello /> 2. Tag with attributes, e.g. <mytag:hello name="ali" /> 3. Tag with body, e.g. <mytag:hello> some body </mytag:hello>
What is the difference between client socket and server socket?
A client socket (java.net.Socket) is created on the client and connects to a given server host and port; it is then used for communication (reading and writing streams). A server socket (java.net.ServerSocket) runs on the server, binds to a port and only listens for incoming connection requests; when accept() receives a request it returns a new ordinary Socket that is used to communicate with that client. The server socket itself is not used for data communication.
What is tag library?
A tag library is a collection of custom tags (actions) packaged together and described by a Tag Library Descriptor (.tld) file, which maps each tag name to its tag handler class and attributes. A JSP page uses it with the taglib directive, e.g. <%@ taglib uri="..." prefix="c" %>, so that it can use tags instead of Java code. JSTL is a standard tag library.
EL (expression language) uses four different scopes to search an object or property. Write the name of each scope.
pageScope, requestScope, sessionScope and applicationScope (searched in that order: page, request, session, application).
Define polymorphism with respect to DryFruits, Fruits and FreshFruits?
Polymorphism means one interface, many behaviours: a superclass reference can point to subclass objects (is-a relationship), and the method that runs is chosen at run time (late binding) from the actual object. Here Fruits is the superclass (it can be abstract) and DryFruits and FreshFruits are subclasses that override its methods, e.g. a method describe() or price(). Code such as Fruits f = new DryFruits(); f.describe(); f = new FreshFruits(); f.describe(); calls the DryFruits version first and the FreshFruits version second, although the reference type is Fruits.
Why HTTP is made stateless protocol? Explain with example.
HTTP is stateless: each request is independent and the server keeps no memory of earlier requests from the same client. It was designed this way to keep servers simple, fast and scalable: a server can answer very many clients without storing information about each one, and a lost connection does not leave stale state. Many applications still need conversational state; for example, in a shopping cart the server must remember items added on earlier pages, so session tracking (cookies, URL rewriting, hidden form fields or HttpSession) is used on top of HTTP.
What impact a JavaBeans object can produce when it is stored in an Application?
When a bean is stored in application scope (<jsp:useBean ... scope="application"/>) it is saved as an attribute of the ServletContext. Only one object is created for the whole web application, it is shared by all pages, servlets, users and sessions, and it lives until the application is stopped or the attribute is removed. Any change made by one user is visible to all users, so it suits global data (e.g. a hit counter or common settings), access to it may need synchronization, and it keeps using memory for the whole life of the application.
Why do we use client side validation?
Client-side validation (usually JavaScript in the browser) checks form input before it is sent to the server. It gives the user immediate feedback (e.g. a required field is empty or an email format is wrong) without a round trip, reduces unnecessary requests and server load, and can focus on the wrong field so the user corrects it. It does not replace server-side validation, because it can be bypassed.
Which technology is used in JAVA to support following layers? 1. Presentation Layer 2. Business Layer 3. Data Layer
Presentation layer: client side HTML, JavaScript and applets; server side servlets, JSP (with JSTL/EL) and JSF. Business layer: JavaBeans and Enterprise JavaBeans (EJB), also web services. Data layer: JDBC, used through Data Access Objects (DAO) and connectors (for example J2EE Connector Architecture) to databases and other data sources.
How cookies are sent to a client?
Three steps: 1. Create a Cookie object with a name and a value: Cookie c = new Cookie("name", "value"); 2. Set its attributes if needed, for example its lifetime in seconds (otherwise it is deleted when the browser closes): c.setMaxAge(60); 3. Place the cookie in the HTTP response headers: response.addCookie(c); The browser receives it in a Set-Cookie header, stores it and sends it back with later requests to the same server.
What are the characteristics of web services?
A web service is a software component that other applications can call over a network using standard protocols. Main characteristics: - Interoperable: based on open standards (XML, SOAP, WSDL, UDDI, HTTP), so clients and services written in different languages and running on different platforms can work together. - Loosely coupled: client and service only share the published interface (WSDL). - Self-describing: the interface is described in WSDL. - Discoverable: services can be published and found through registries such as UDDI. - Accessible over the web: they use HTTP and usually pass firewalls. - Economical and reusable: existing functionality is reused instead of rebuilt. - Automatic (machine-to-machine): programs call them without human interaction. - Available and scalable: they can run on many servers and serve many clients.
What is the usage of sleep (int time) method?
Thread.sleep(ms) makes the currently running thread stop for the given time in milliseconds. - Sleeping is efficient (non-busy) waiting: the thread does not use the processor while it sleeps. - The thread comes out of sleep when the time expires or when another thread interrupts it (InterruptedException, so the call is placed in try/catch). - After sleeping it goes to the ready state and runs again when the scheduler gives it the processor. - High-priority threads can call sleep() to give lower-priority threads a chance to run and avoid starvation. - It is also used simply to create a delay, for example in animations. Example: try { Thread.sleep(1000); } catch (InterruptedException e) { }
Differentiate between yielding and sleeping?
yield(): the running thread voluntarily gives up the CPU and goes straight back to the ready state, so other threads of the same priority get a chance to run; it may be chosen again immediately and no time is given. sleep(ms): the thread stops for at least the given milliseconds and goes to the blocked (sleeping) state; it cannot run during that time even if the CPU is free; it then returns to ready. sleep() can throw InterruptedException, yield() cannot.
I am making a java application, and I need to force the garbage collection, how can I achieve that, if not why?
Garbage collection cannot be forced in Java. The JVM runs the garbage collector itself when it decides memory is needed. A program can only request it with System.gc() (or Runtime.getRuntime().gc()), which is a hint that the JVM may ignore. The programmer can help by removing references to unused objects (for example setting them to null) so that they become eligible for collection, but the time of collection is not guaranteed because memory management is the JVM's job.
How can a GUI component handle its own events?
The component class itself acts as the listener: extend the component class (or the frame/panel that owns the component), implement the required listener interface (for example ActionListener) in the same class, register itself with addXxxListener(this), and write the handler method. Example: public class MyButton extends JButton implements ActionListener { public MyButton(String label) { super(label); addActionListener(this); // component listens to itself } public void actionPerformed(ActionEvent e) { setText("Clicked"); } } (An inner or anonymous class inside the component class can also be used.)
Write the code for a javabean class, "MyBean" with an attribute "name" of String datatype.
import java.io.Serializable; public class MyBean implements Serializable { private String name; public MyBean() { // zero-argument constructor name = ""; } public void setName(String n) { name = n; } public String getName() { return name; } } It is serializable, has a public no-argument constructor, a private field and public getter/setter methods, as bean conventions require.
What technology is used in Java, that supports the following; Presentation Layer Business Layer Data Layer
Presentation layer: client side HTML, JavaScript and applets; server side servlets, JSP (with JSTL/EL) and JSF. Business layer: JavaBeans and Enterprise JavaBeans (EJB), also web services. Data layer: JDBC, used through Data Access Objects (DAO) and connectors to databases and other data sources.
What does it means method or class abstract?
An abstract method is declared with the keyword abstract and has no body (only its signature); a subclass must give its implementation. An abstract class is declared with abstract and gives only part of an implementation, so it cannot be instantiated. It can still have instance variables, constructors and fully implemented methods. Any class that has an abstract method must be declared abstract, but a class can be abstract without abstract methods. A subclass that overrides all abstract methods becomes concrete; otherwise it must also be abstract. A reference of an abstract class type can point to objects of its concrete subclasses (polymorphism).
Why need JSP as we have servlet?
Servlets are good for reading form data and headers, setting status codes, using cookies and sessions and sharing data. But generating HTML from a servlet needs many out.println() statements, which are hard to write and maintain, and mixes presentation with Java code so web designers cannot easily work on it. JSP solves this: the page is written mostly in normal HTML with special tags for the dynamic parts. The whole JSP is translated into a servlet once and that servlet serves each request, so we get servlet power with easy presentation and better separation of content and logic.
What impact have java bean object can produce when it store in session objects?
With scope="session" the bean is bound to a local variable and also stored in the HttpSession of the current user. It stays available to every page and servlet that the same user visits, across many requests, whether the request is forwarded or a new request is made, until the session ends (timeout or invalidate()). Other users have their own session, so they get their own bean.
Difference between page centric and page with beans approach?
Both are page-centric (Model 1) designs where the request goes first to a JSP page. Page-with-Java (pure page-centric): all presentation, business and data-access code is written as scriptlets inside the JSP. Code becomes a mixture, is duplicated across pages and maintenance is very hard. Page-with-bean: the JSP still handles the request and presentation, but business logic and data access move into JavaBeans used through <jsp:useBean>, <jsp:setProperty> and <jsp:getProperty>. The application is a collection of JSPs and beans, so there is less Java in pages, better reuse and easier maintenance, though control flow is still decided inside the pages.
why session tracking is necessary
HTTP is a stateless protocol: each request is independent and the server does not remember earlier requests from the same user. Many applications need to remember the user across requests, for example a shopping cart, a logged-in user, or a multi-page form. Session tracking associates a series of requests with one user and keeps his data on the server. It is done with cookies, URL rewriting, hidden form fields or the HttpSession API.
describe twin libraries
JSTL comes in two versions (twin libraries) for different skill sets: 1. EL version: dynamic attribute values are given with the Expression Language, ${expression}. Example: <c:out value="${param.name}"/>. URIs such as http://java.sun.com/jsp/jstl/core (prefix c). 2. RT (request time) version: dynamic attribute values are given with JSP expressions, <%= expression %>. Example: <c_rt:out value="<%= name %>"/>. URIs such as http://java.sun.com/jsp/jstl/core_rt (prefix c_rt). Both provide the same core, xml, fmt (formatting) and sql tag libraries.
why there is no global variable in java
Java is purely object-oriented: every variable and method must be inside a class, so there is nothing outside a class that could be global. Global variables break encapsulation, can be changed by any part of the program, cause name clashes and make code hard to debug and maintain. Java gives the same effect in a controlled way with static (class) variables, optionally public and final for constants, accessed through the class name, and packages prevent name clashes.
explain the JSP life cycle
Translation: the container translates the JSP into a servlet source file (first request or after the JSP is changed). Compilation: the servlet source is compiled into a class. Loading and instantiation: the class is loaded and an object created. Initialization: jspInit() is called once (it can be overridden). Request processing: for every request _jspService() is called, which generates the response; it cannot be overridden. Destruction: jspDestroy() is called once when the JSP is removed (it can be overridden) to free resources.
What are validators? and there types
In JSF, validators check that the value entered in a UI component is correct before it is stored in the model; if validation fails, an error message is queued and the page is shown again. Types: 1. Built-in standard validators: <f:validateLength> (LengthValidator), <f:validateLongRange> (LongRangeValidator) and <f:validateDoubleRange> (DoubleRangeValidator); also the required attribute. 2. Custom validators: a class implementing javax.faces.validator.Validator, registered in faces-config.xml and used with <f:validator>. 3. Validator methods: a method in a managed bean referenced with the validator attribute.
How streams handle in Java
Java does I/O with streams, ordered sequences of data from a source (input stream) or to a sink (output stream); the classes are in java.io. By data type they are byte-oriented (InputStream/OutputStream classes) or character-oriented (Reader/Writer classes). By function they are node streams, which connect directly to the source or sink (for example FileReader fr = new FileReader("input.txt");), and filter streams, which wrap another stream to add features such as buffering (for example BufferedReader br = new BufferedReader(fr);). The program opens the stream, reads or writes in a loop, handles IOException and closes the stream.
Write down java code to create a dialogue box.
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class DialogTest implements ActionListener { JFrame frame; JButton hello; public DialogTest() { frame = new JFrame(); Container cont = frame.getContentPane(); cont.setLayout(new FlowLayout()); hello = new JButton("Hello"); hello.addActionListener(this); cont.add(hello); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(150, 150); frame.setVisible(true); } public void actionPerformed(ActionEvent event) { JOptionPane.showMessageDialog(null, "Hello is pressed"); // dialog box } public static void main(String args[]) { new DialogTest(); } } JOptionPane.showMessageDialog() shows a modal message dialog; a custom JDialog could also be created with new JDialog(frame, "Title", true).
What is package? How are they organized?
A package is a named group of related classes and interfaces, like a library. It gives a namespace (avoids name clashes), access control (package access) and easier reuse. Packages are organized as directories: each package name maps to a folder and sub-packages to sub-folders, for example package edu.vu.cs506 is stored in edu/vu/cs506. A source file declares its package with "package name;" as the first statement, and other classes use it with "import". Files are grouped by functionality, usability and category.
Differentiate between value binding and method binding.
Both are JSF expressions written with #{...}. Value binding: binds a component's value to a property of a managed bean through its getter/setter, for example <h:inputText value="#{customer.name}"/>. It can create the bean in its scope, set and read its values, read Map/List/array contents and keep form data in sync with the bean. Method binding: binds a component attribute to a bean method that is invoked, not a property accessor, for example an action, actionListener or validator: <h:commandButton action="#{customer.login}" actionListener="#{customer.loginActionListener}"/>.
What is expression in JSP?
A JSP expression is written as <%= expression %>. The Java expression is evaluated at request time, converted to a String and inserted into the output at that place; it ends without a semicolon. It becomes out.print(expression) in _jspService(). Example: Current time: <%= new java.util.Date() %>. Its XML form is <jsp:expression>...</jsp:expression>.
What is Expression in JSP? Give an example.
A JSP expression is written as <%= expression %>. The Java expression is evaluated at request time, converted to a String and inserted into the output at that place; it ends without a semicolon. It becomes out.print(expression) in _jspService(). Example: Current time: <%= new java.util.Date() %>, or Hello <%= request.getParameter("name") %>.
What are action elements of JSP? How these are written.
Action elements are XML-style tags that make the container do something at request time, such as working with JavaBeans, including or forwarding to other resources and passing parameters, without Java code. They are written as <jsp:actionName attribute="value" ... /> or with a body <jsp:actionName ...> ... </jsp:actionName>. Examples: <jsp:useBean id="m" class="vu.MyBean" scope="session"/> <jsp:setProperty name="m" property="name" value="ali"/> <jsp:getProperty name="m" property="name"/> <jsp:include page="header.jsp"/> <jsp:forward page="next.jsp"/> <jsp:param name="id" value="1"/>
Explain the "include" method of "Request Dispatcher" with the help of diagram.
RequestDispatcher.include(request, response) lets a servlet include the output of another resource (servlet, JSP or HTML) in its own response. Flow: Client -> Servlet1 (writes part of the response) -> include -> Servlet2/JSP (adds its output to the same response) -> control returns to Servlet1 -> Servlet1 writes the rest and finishes -> response to Client. Data can be written before and after the include, the included resource cannot change status codes or headers, and the first servlet finishes the response. Code: RequestDispatcher rd = request.getRequestDispatcher("second"); rd.include(request, response);
Explain MVC Model2 with the help of diagram.
In MVC Model 2 the request handling is split into three parts. Flow: Browser -> (1) request -> Controller servlet -> (2) creates/uses JavaBeans (Model), which access the database -> (3) controller forwards the request to a JSP (View) -> (4) the JSP reads data from the beans -> (5) HTML response to the browser. The controller servlet is the single entry point that handles requests and chooses the view, the model beans hold data and business logic, and the JSP view only presents data. This separates presentation from logic and makes the application easier to maintain and extend.
Java bean Class
import java.io.Serializable; public class PersonInfo implements Serializable { private String name; private String id; // zero-argument constructor public PersonInfo() { name = ""; id = ""; } public void setName(String n) { name = n; } public String getName() { return name; } public void setId(String i) { id = i; } public String getId() { return id; } }
Difference b/w Page-centric approach and page-with-bean approach.
Page-centric approach: the web application is only a collection of JSPs, each containing presentation, business and data-access code together. It is easy to start with, but code gets mixed and duplicated, and maintenance and scaling become very difficult. Page-with-bean approach (MVC Model 1): the business logic is moved into JavaBeans and JSPs use these beans, so the application is a collection of JSPs and JavaBeans. This gives better reuse and separation, but the JSPs still control flow and presentation, so the separation is not complete.
What you know about EL(Expression Language)?Describe briefly.
The Expression Language is not a programming or scripting language; it is a simple language used in JSP to simplify expressions. It is used to look up objects and their properties and perform simple operations on them, inspired by ECMAScript and XPath. Syntax: ${ expression }. It gives easy access to scoped variables and beans (${person.name}), request parameters (${param.id}), arrays, lists and maps (${list[0]}, ${map["key"]}), implicit objects (pageContext, param, header, cookie, initParam, pageScope ... applicationScope), arithmetic, relational, logical, empty and conditional operators, and automatic type conversion, so scriptlets/expressions are no longer needed in pages.
Participants and Responsibilities of MVC:
Model: represents the state (data) of the application and the methods/business logic to manipulate it, independent of how it is displayed. View: renders the contents of the model and specifies how the data is presented; one model can have several views. Controller: translates user interaction with the view (in web applications, GET/POST requests) into actions performed by the model, e.g. activating business processes or changing model state, and then selects the appropriate view for the response.
EL based XML and RT based XML
JSTL comes in two versions. In the EL (Expression Language) based version, dynamic attribute values of JSTL tags are given with EL expressions, e.g. <c:out value="${param.name}"/>. In the RT (Request Time) based version, dynamic attribute values are given with JSP expressions, e.g. <c_rt:out value="<%= request.getParameter("name") %>"/>. Each version has its own tag-library URIs and prefixes (for XML: x for EL based, x_rt for RT based); the EL version is simpler and preferred.
write the name of five event listener interface which are sub interface of java utility event listener interface
ActionListener, MouseListener, MouseMotionListener, KeyListener, WindowListener (others: ItemListener, FocusListener, TextListener).
Write program to read from file "file1.txt" following data Welcome to Virtual University Hello World CS506 is very easy subject then write to another file in reverse order it should look like this:- CS506 is very easy subject Hello World Welcome to Virtual University
import java.io.*; import java.util.*; public class ReverseLines { public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new FileReader("file1.txt")); ArrayList<String> lines = new ArrayList<String>(); String line; while ((line = br.readLine()) != null) { lines.add(line); } br.close(); PrintWriter pw = new PrintWriter(new FileWriter("file2.txt")); for (int i = lines.size() - 1; i >= 0; i--) { pw.println(lines.get(i)); } pw.close(); } catch (IOException e) { System.out.println(e); } } }
What are the requirement which a java should full fill to be javabeans.
It must have a zero-argument constructor, no public instance variables, private properties accessed through getters and setters, and it must implement Serializable.
Why destructor has been eliminated in java?explain.
A destructor’s main job in C++ is to free an object’s memory when it is no longer needed. Java has automatic garbage collection: the JVM itself finds objects that are no longer referenced and frees their memory, so programmers do not deallocate memory manually and destructors are not needed. Other resources (files, connections) are released explicitly with close() calls, usually in finally blocks.
write jsp page for the amount "amount" get from another page calculate zakat and display it. note:use screplet,jsp coment,HTML coment
<html> <body> <!-- HTML comment: this page calculates and shows zakat --> <%-- JSP comment: amount is sent by the previous page --%> <% String amountStr = request.getParameter("amount"); double amount = Double.parseDouble(amountStr); double zakat = amount * 2.5 / 100; // zakat is 2.5% of the amount %> <h3>Amount: <%= amount %></h3> <h3>Zakat: <%= zakat %></h3> </body> </html>
Write a code which shows the number of cookies that how many times that page been accessed ?
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class VisitCounterServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int visits = 0; Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals("visits")) { visits = Integer.parseInt(cookies[i].getValue()); } } } visits++; Cookie c = new Cookie("visits", String.valueOf(visits)); c.setMaxAge(60 * 60 * 24 * 365); // keep the cookie for one year response.addCookie(c); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html><body>"); out.println("You have accessed this page " + visits + " time(s)."); out.println("</body></html>"); out.close(); } }
What type of information present in(.tld) file? Mension any five.
A TLD (tag library descriptor) is an XML file that describes a tag library: 1. tlib-version (library version), 2. short-name (preferred prefix), 3. uri of the library, and for each tag: 4. name of the tag, 5. tag-class (fully qualified handler class), 6. body-content (empty, scriptless, tagdependent), 7. attribute entries with name, required and rtexprvalue, plus description and jsp-version.
Instance speaker{} Abstract class Teacher implements Speaker { } Do you find any problem in the above code? Explain your answer.
Yes, it does not compile: 1. "Instance" is not a Java keyword; an interface is declared with the keyword interface. 2. "Abstract" must be written in lowercase (abstract). 3. Java is case-sensitive, so the interface named speaker is not the same as Speaker used after implements. Corrected: interface Speaker { } abstract class Teacher implements Speaker { } After correction there is no problem: an abstract class may implement an interface without implementing its methods; its concrete subclasses must implement them.
Write java code that show output "Welcome to Web Design And Development Course"
public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Web Design And Development Course"); } }
What impact a JavaBeans object can produce when it is stored in Session object?
A bean in session scope is stored in the user’s HttpSession. It is available to all JSPs and servlets that the same user visits during that session, across many requests, until the session times out or is invalidated. Each user gets a separate copy, so it suits user-specific data such as login information or a shopping cart; it also uses server memory for every active session.
What are the advantages of Cookies over URL rewriting?
1. Cookies can be persistent (setMaxAge), so data survives after the browser is closed; URL rewriting data is lost when the session ends. 2. Cookies work with GET and POST and with static pages; URL rewriting needs every link and form to be rewritten (encodeURL) on dynamically generated pages. 3. The session ID does not appear in the URL, so bookmarking or sharing a link does not expose or break the session. 4. Less coding and processing: the browser sends cookies automatically with each request.
What is validator? Discuss built-in-validators.
A validator is a JSF component that checks the value entered in an input component before it is stored in the model. If the value is invalid, an error message is queued and the page is shown again. JSF provides standard (built-in) validators, and developers can also write their own: - LengthValidator (<f:validateLength minimum=".." maximum=".."/>): checks that the length of a String value is within a range. - LongRangeValidator (<f:validateLongRange>): checks that a value convertible to long is between minimum and maximum. - DoubleRangeValidator (<f:validateDoubleRange>): checks that a numeric value is between minimum and maximum. The required="true" attribute of input components also checks that a value is entered.
JSP page directive?
The page directive gives high-level information about the servlet that will be generated from the JSP page. Syntax: <%@ page attribute="value" %> (XML form <jsp:directive.page attribute="value"/>). It can control: - which classes are imported (import="java.util.*") - which class the servlet extends (extends) - the MIME type generated (contentType="text/html") - how multithreading is handled (isThreadSafe) - whether the page takes part in a session (session="true") - buffering (buffer, autoFlush) - which page handles unexpected errors (errorPage) and whether this page is an error page (isErrorPage). Example: <%@ page import="java.util.*" contentType="text/html" errorPage="error.jsp" %>
Request dispatcher’s include method?
include(request, response) of RequestDispatcher lets a servlet include the output of another resource (servlet, JSP or HTML) in its own response. Flow: the user sends a request to Servlet1; Servlet1 gets a RequestDispatcher for Servlet2 and calls include(request, response); Servlet2 writes its output, and control returns to Servlet1, which can add more content and finally sends the complete response to the user. Differences from forward(): data can be written to the response before and after an include, and the first servlet that received the request is the one that finishes the response. Example: RequestDispatcher rd = request.getRequestDispatcher("servlet2"); rd.include(request, response);
Why J2EE is called multi-tiered?
J2EE uses a multi-tiered distributed application model. Application logic is divided into components according to their function, and these components are installed on different machines (tiers): - Client tier components (browser, applets, application clients) run on the client machine. - Web tier components (servlets, JSP) run on the J2EE server. - Business tier components (EJBs) run on the J2EE server. - Enterprise information system (EIS) tier (databases, legacy systems) runs on the EIS server. Because the parts of an application are spread across these physical tiers, J2EE is called multi-tiered.
Types of layers? Briefly explain each.
A web application is usually divided into three logical layers: 1. Presentation layer: provides the user interface. It collects and validates user input, shows the results and controls the screen flow (for example JSP pages). 2. Business layer (application layer): implements the application-specific functionality and business rules, for example opening an account or transferring a balance in a banking system (for example JavaBeans or EJBs). 3. Data layer: manages data and data sources such as databases, XML or files, and holds the data retrieval and storage logic (for example JDBC code).
Why tracking is necessary?
HTTP is stateless: every request is independent, and the server does not remember earlier requests from the same client. Many applications need a series of requests from one user to be linked, for example a shopping cart that must keep its items across pages, or a login that must be remembered. Session tracking is therefore needed to keep this conversational state. Servlets support it through cookies, URL rewriting, hidden fields and the HttpSession API.
Difference between ServletContext and ServletConfig?
ServletConfig: - One object per servlet, created by the container when the servlet is initialized. - Gives that servlet its own init parameters, defined with <init-param> inside its <servlet> tag in web.xml. - Obtained with getServletConfig(); its parameters are not visible to other servlets. ServletContext: - One object per web application, shared by all servlets and JSPs of that application. - Gives application-wide parameters, defined with <context-param> in web.xml, and can share attributes between servlets. - Obtained with getServletContext() (also available through ServletConfig).
Different steps to write code for thread creation using interface.
Steps to create a thread using the Runnable interface: 1. Implement the Runnable interface: class Worker implements Runnable { ... } 2. Provide an implementation of the run() method: public void run() { /* task code */ } 3. Create a Thread object, passing the Runnable object to its constructor: Worker w = new Worker(); Thread t = new Thread(w); 4. Start the thread by calling start(): t.start();
Explain literals of EL.
EL literals: - Boolean: true and false - Integer: for example 10, -5 - Floating point: for example 3.5, 1.2E4 - String: text in single or double quotes, for example 'hello' or "hello" - Null: null
Write the names of JSP scopes in EL. What happens if these scopes are missed?
JSP scopes in EL are accessed with the implicit objects pageScope, requestScope, sessionScope and applicationScope, for example ${sessionScope.user}. If the scope is not written, for example ${user}, EL searches the attribute in page, request, session and application scope in that order and uses the first one found; if it is not found in any scope, the result is null and nothing is displayed (no exception).
What do you know about EL (expression language)?
The Expression Language (EL) is not a programming or scripting language; it gives a simple way to write expressions in JSP (JSP 2.0 and later). It is geared towards looking up objects and their properties and doing simple operations on them, and is inspired by ECMAScript and XPath. - Syntax: ${expression}, which can be mixed with static text. - Can read request parameters, scoped attributes, bean properties, arrays, lists and maps (with . and [] operators). - Has arithmetic, relational, logical and empty operators. - Gives implicit objects such as param, header, cookie, pageScope, requestScope, sessionScope and applicationScope. - Converts types automatically and does not throw NullPointerException for null values. It removes most Java code from JSP pages.
What steps are performed to make an application in tomcat?
Steps to make a web application (for example myapp) in Tomcat: 1. Create a folder myapp inside Tomcat's webapps folder; this name appears in the URL, for example http://localhost:8080/myapp/index.html. 2. Put JSP and HTML files in the main application folder (webapps/myapp). 3. Create a folder WEB-INF (case-sensitive) inside myapp; configuration files such as web.xml go here. 4. Create a folder classes inside WEB-INF; servlets and JavaBeans (class files, in package folders) go here. JAR libraries go in WEB-INF/lib. 5. Write web.xml with servlet and servlet-mapping entries, start Tomcat and open the application in the browser.
What happens if: We set true as request.getSession(true); We set false as request.getSession(false);
request.getSession(true) returns the current session of this request, or if the request has no session, creates a new one and returns it. Whether the session is new can be checked with isNew(). request.getSession(false) returns the current session if one exists; if there is no session, it does not create one and returns null.
Write a script that validates the phone number field in the form in such a way that if user leaves it empty it receives a message “phone number is required. It can’t be left empty”
<html> <head> <script type="text/javascript"> function validateForm(thisform) { if (thisform.phone.value == null || thisform.phone.value == "") { alert("Phone number is required. It can't be left empty"); thisform.phone.focus(); return false; } return true; } </script> </head> <body> <form action="register" method="post" onsubmit="return validateForm(this)"> Phone: <input type="text" name="phone"> <input type="submit" value="Submit"> </form> </body> </html>
What is the hidden comment in JSP? Explain this syntax
A hidden comment is a JSP comment that documents the JSP page but is not sent to the client. The JSP container ignores it during translation, so it does not appear in the page source in the browser. Syntax: <%-- comment text --%> Example: <%-- This part shows the user list --%>
Write a web.xml for the servlet whose name is “MyFirstServlet” and its id is “VFirstServlet”. This servlet is accessed through url name “ViewServlet”
<web-app> <servlet> <servlet-name>MyFirstServlet</servlet-name> <servlet-class>VFirstServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>MyFirstServlet</servlet-name> <url-pattern>/ViewServlet</url-pattern> </servlet-mapping> </web-app>
You have to add two numbers getting from html fields; declare a variable result in declaration tag, write the remaining code in scriptlets and write result in expression tag.
<%! int result; public int sum(int op1, int op2) { return op1 + op2; } %> <% int num1 = Integer.parseInt(request.getParameter("num1")); int num2 = Integer.parseInt(request.getParameter("num2")); result = sum(num1, num2); %> Sum is: <%= result %>
Write full code of using custom tag, overriding doTag() method, which will print “welcome to custom tag.”
Tag handler class (WEB-INF/classes/vu/WelcomeTagHandler.java): package vu; import java.io.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class WelcomeTagHandler extends SimpleTagSupport { public void doTag() throws JspException, IOException { JspWriter out = getJspContext().getOut(); out.print("welcome to custom tag."); } } TLD file (WEB-INF/tlds/mytaglibrary.tld): <taglib> <tlib-version>1.0</tlib-version> <jsp-version>2.0</jsp-version> <short-name>mytag</short-name> <tag> <name>welcome</name> <tag-class>vu.WelcomeTagHandler</tag-class> <body-content>empty</body-content> </tag> </taglib> JSP page: <%@ taglib uri="/WEB-INF/tlds/mytaglibrary.tld" prefix="mytag" %> <html><body> <mytag:welcome /> </body></html>
Create a class “AddBean”. Pass three values val1, val2, result. Also create an AddResult() method which returns the sum of values.
package vu; import java.io.Serializable; public class AddBean implements Serializable { private int val1; private int val2; private int result; public AddBean() { } public void setVal1(int v) { val1 = v; } public int getVal1() { return val1; } public void setVal2(int v) { val2 = v; } public int getVal2() { return val2; } public void setResult(int r) { result = r; } public int getResult() { return result; } public int AddResult() { result = val1 + val2; return result; } }
What are packages? And how they are organized?
A package is a set of related Java classes and interfaces kept together in one directory, mainly for convenience and to avoid name collisions. When a project grows, keeping all files in one folder becomes difficult, so files are organized into directories according to their functionality, usability and category. Organization: the first statement of a source file declares its package, for example package vu.cs506;. The class files are then placed in a matching directory structure (vu/cs506/...). Other classes use them with import vu.cs506.*; or the fully qualified name, and the directory above the package must be on the classpath.
What is the difference between custom tags and javabeans?
Custom tags: - can manipulate JSP content (for example the tag body) - can simplify complex operations better than beans but need more work to set up (tag handler class, TLD) - are used only in JSP pages JavaBeans: - cannot manipulate JSP content - are easier to set up - can be used in both servlets and JSP pages; a bean created in one servlet can be used in another servlet or JSP
What is validator? Write types of built in validators?
A validator is a JSF component that checks the value entered in an input component before it is stored in the model. If the value is invalid, an error message is queued and the page is shown again. JSF provides standard (built-in) validators, and developers can also write their own: - LengthValidator (<f:validateLength minimum=".." maximum=".."/>): checks that the length of a String value is within a range. - LongRangeValidator (<f:validateLongRange>): checks that a value convertible to long is between minimum and maximum. - DoubleRangeValidator (<f:validateDoubleRange>): checks that a numeric value is between minimum and maximum. The required="true" attribute of input components also checks that a value is entered.
What is value binding and method binding?
Value binding: a JSF expression such as #{bean.property} that connects a component's value to a property of a managed bean. It can create the bean and place it in a scope, get and set the property through its accessor methods, read map, list and array contents, and keep form data and bean values in sync. JSF uses #{} instead of the ${} used in JSP EL. Method binding: an expression that refers to a method of a bean, not a property accessor. It is used for event handlers, actions and validators, for example <h:commandButton value="Login" actionListener="#{customer.loginActionListener}"/>
JSP life cycle
JSP life cycle: 1. Translation: the JSP page is translated into a servlet source file (done once, or again when the page changes). 2. Compilation: the generated servlet is compiled into a class. 3. Loading and instantiation of the servlet class. 4. Initialization: jspInit() is called once. 5. Request processing: _jspService() is called for each request. 6. Destruction: jspDestroy() is called before the page is removed.
What are the two ways of reading initialization parameters of a servlet?
1. Servlet initialization parameters, defined with <init-param> inside the servlet's <servlet> tag in web.xml, are read through ServletConfig: getServletConfig().getInitParameter("name") (or getInitParameter("name") directly in the servlet). 2. Context initialization parameters, defined with <context-param> in web.xml for the whole application, are read through ServletContext: getServletContext().getInitParameter("name").
What data is sent to server when user sends request to server?
When a user submits a request, the browser sends two kinds of data to the web server: 1. Form data: data the user explicitly enters in HTML form controls (text boxes, password, select, checkboxes, radio buttons), for example registration information. 2. HTTP request header data: data the browser adds automatically, for example cookies, browser type (User-Agent), accepted content types, host and the client's IP address.
Include method of dispatcher
include(request, response) of RequestDispatcher lets a servlet include the output of another resource (servlet, JSP or HTML) in its own response. Flow: the user sends a request to Servlet1; Servlet1 gets a RequestDispatcher for Servlet2 and calls include(request, response); Servlet2 writes its output, and control returns to Servlet1, which can add more content and finally sends the complete response to the user. Differences from forward(): data can be written to the response before and after an include, and the first servlet that received the request is the one that finishes the response. Example: RequestDispatcher rd = request.getRequestDispatcher("servlet2"); rd.include(request, response);
Why is J2EE said to be multi tiered application?
J2EE uses a multi-tiered distributed application model. Application logic is divided into components according to their function, and these components are installed on different machines (tiers): - Client tier components (browser, applets, application clients) run on the client machine. - Web tier components (servlets, JSP) run on the J2EE server. - Business tier components (EJBs) run on the J2EE server. - Enterprise information system (EIS) tier (databases, legacy systems) runs on the EIS server. Because the parts of an application are spread across these physical tiers, J2EE is called multi-tiered.
Why we need JSP as we already have servlet?
Servlets are good for processing (reading form data and headers, cookies, sessions, sharing data), but generating HTML from servlets is painful: all HTML must be written with println() statements, which is hard to write and maintain, and page designers cannot use normal HTML tools. JSP solves this: the page is written mostly in regular HTML and only the dynamic parts are marked with special tags. The container translates the JSP into a servlet automatically, so we get the power of servlets with easier page design, and presentation is separated from business logic (servlets can then act as controllers and JSPs as views).
What are output comments in JSP?
An output comment is an HTML comment in a JSP page that is sent to the client and can be seen in the page source in the browser. The JSP engine treats it as normal template text, but JSP expressions inside it are evaluated. Syntax: <!-- comment [ <%= expression %> ] --> Example: <!-- This page was sent on <%= new java.util.Date() %> --> The browser page source then shows the comment with the current date.
Write five operators used in Expression Language
Five arithmetic operators used in EL: + (addition), - (subtraction), * (multiplication), / or div (division) and % or mod (remainder). EL also has relational operators (== eq, != ne, < lt, > gt, <= le, >= ge), logical operators (&& and, || or, ! not) and the empty operator.
What is webpage and web server?
A web page is a document (usually HTML, possibly with images and scripts) that is accessed over the Internet by a URL and displayed in a web browser. It can be static or generated dynamically. A web server is software (and the machine running it) that hosts websites and web applications: it receives HTTP requests from clients and sends back web pages or other resources, for example Apache Tomcat or Microsoft IIS.
What type of data is sent to web server when user submits the button?
When a user submits a request, the browser sends two kinds of data to the web server: 1. Form data: data the user explicitly enters in HTML form controls (text boxes, password, select, checkboxes, radio buttons), for example registration information. 2. HTTP request header data: data the browser adds automatically, for example cookies, browser type (User-Agent), accepted content types, host and the client's IP address.
What is JSP? Why need JSP? How JSP framework works?
What is JSP: JavaServer Pages is a specification and technology for building dynamic, platform-independent web pages by mixing regular HTML with Java code. Why JSP is needed: with servlets it is easy to read form data and headers, set status codes, use cookies and sessions and share data, but it is a pain to generate and maintain HTML with println() statements, and designers cannot use normal HTML tools. JSP removes this problem and separates presentation from logic. How the JSP framework works: most of the page is regular HTML and the servlet code is marked with special tags (scripting elements, directives, actions). On the first request (or when the page changes) the whole JSP page is translated into a servlet and compiled once; that servlet is then what actually runs for each request and generates the response.
Write code for Student info servlet that gets name and id and displays them in a table using HTML
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class StudentServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String name = request.getParameter("name"); String id = request.getParameter("id"); out.println("<html><body>"); out.println("<table border='1'>"); out.println("<tr><th>Name</th><th>ID</th></tr>"); out.println("<tr><td>" + name + "</td><td>" + id + "</td></tr>"); out.println("</table>"); out.println("</body></html>"); out.close(); } }
Write code for session and count how many times user visited the page
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class VisitCounter extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(true); Integer count = (Integer) session.getAttribute("count"); if (count == null) { count = 1; } else { count = count + 1; } session.setAttribute("count", count); out.println("<html><body>"); out.println("You have visited this page " + count + " times."); out.println("</body></html>"); out.close(); } }
Write a JSP page that gets the value of “amount” from an html page, calculates Zakat on it and displays the calculated Zakat. Note: Use the following overall format of the program. <html> <body> <!-- JSP to calculate Zakat--> <%-- Declaration --%> <%! //your code here %> <%-- Scriptlet --%> <% //your code here %> <%-- expression used to display Zakat --%> <h3>Zakat value is: <% // your code here %> </h3> </body> </html>
<html> <body> <!-- JSP to calculate Zakat --> <%-- Declaration --%> <%! double zakat; public double calculateZakat(double amount) { return amount * 2.5 / 100; } %> <%-- Scriptlet --%> <% double amount = Double.parseDouble(request.getParameter("amount")); zakat = calculateZakat(amount); %> <%-- expression used to display Zakat --%> <h3>Zakat value is: <%= zakat %> </h3> </body> </html>
Display this statement “I am student of vu university” using the Servlet?
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class StudentServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html><body>"); out.println("I am student of vu university"); out.println("</body></html>"); out.close(); } }
How java provides security and safety for applications? Also briefly explain JVM verifier.
Java has no explicit pointers, checks array bounds and casts at run time, uses automatic garbage collection and strong typing, so common errors such as buffer overflows and memory corruption cannot happen. Untrusted code (e.g. applets) runs in a sandbox controlled by the class loader and the Security Manager, which decides what a piece of code may do (e.g. no access to local files). The JVM bytecode verifier checks each class when it is loaded, before it runs: it confirms the bytecode has a valid structure, does not forge pointers, does not misuse types, does not overflow/underflow the operand stack and does not use uninitialized variables. Code that fails verification is rejected.
What is difference between Page-Centric Approach and Page-with-Bean Approach?
Page-centric: the web application is only a collection of JSPs; each JSP handles the request and mixes presentation, business and data-access logic. It is easy to start but maintenance is difficult, code is duplicated and it does not scale well. Page-with-Bean (MVC Model 1): the application is a collection of JSPs plus JavaBeans; business and data-access logic is factored into beans which JSPs use, giving better reuse and maintenance, but the JSPs still control request handling and page flow, so separation is incomplete.
You are required to write a Servlet code that will read the parameters passed from the login page. In a login page, user will enter username in text field uname and password in text field pass. If the user name is "vulms" and password is "admin" then send the user to "Welcome.jsp" else send the user to "Error.jsp" Note: You are not required to write complete code. Just write code which will read form data and send response to Welcome or Error page.
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String uname = request.getParameter("uname"); String pass = request.getParameter("pass"); if ("vulms".equals(uname) && "admin".equals(pass)) { response.sendRedirect("Welcome.jsp"); } else { response.sendRedirect("Error.jsp"); } }
Arrange the following classes in packages. Use suitable name for package: 1. Dbconn.java 2. Input.jsp 3. Home.html 4. Insertdb.java 5. AddUser.html 6. Deletedb.java
Group files by their role. Presentation files (Home.html, AddUser.html, Input.jsp) go in the web pages folder (e.g. a 'pages' or view directory under the application root). The database classes (Dbconn.java, Insertdb.java, Deletedb.java) go in one Java package such as 'database' (declared with package database; at the top of each file), so their compiled classes are placed in WEB-INF/classes/database.
Write literals that can be used as an EL (expression language). Also write their possible values.
Boolean: true or false. Integer: as in Java, e.g. 243, -9642. Floating point: as in Java, e.g. 54.67, 1.83. String: any text in single or double quotes, e.g. "hello" or 'hello'. Null: null.
What is difference between socket and server socket? Also right java syntax to create socket and server socket. Write solution by filling given table. (Table with columns: Socket | Server Socket)
Socket: the client-side endpoint of a connection; it connects to a server at a given host and port and is used to send and receive data through its input and output streams. Syntax: Socket s = new Socket("localhost", 2222); ServerSocket: used on the server side; it listens on a port and waits for client requests; accept() blocks until a client connects and then returns a Socket for talking to that client. Syntax: ServerSocket ss = new ServerSocket(2222); Socket s = ss.accept();
Draw and divide the components of internet banking(Client,web Server and DB server) into three layered approach?
Presentation layer: the client (web browser) showing pages and forms where the customer logs in and requests transactions. Business layer: the web server running servlets/JSP/beans that check the login, apply banking rules (balance checks, transfers) and build responses. Data layer: the database server that stores accounts and transactions, accessed by the business layer through JDBC. Requests flow Client -> Web server -> DB server and results flow back.
What is the difference between node and filter streams? If we get the data from user and compresses it to the required format which streams will be used as node stream and filter stream?
Node streams connect directly to a data source or destination (file, console, socket, memory), e.g. FileInputStream, FileReader. Filter streams are wrapped around another stream and add processing such as buffering, conversion or compression, e.g. BufferedReader, DataInputStream. For reading user input and compressing it: the stream attached to the source (System.in / an InputStream, or FileOutputStream for the output file) is the node stream, and the stream that compresses it (e.g. GZIPOutputStream or ZipOutputStream wrapped around the node stream, plus InputStreamReader/BufferedReader to read the input) is the filter stream.
What are benefits of partitioning the application in logical layers?
Each layer (presentation, business, data) has one responsibility, so code is easier to understand and maintain; a layer can be changed or replaced (e.g. a new UI or database) without affecting the others; layers and their components can be reused; teams can work on layers in parallel; and the layers can later be deployed on separate tiers for better scalability and security.
Write the names of any five event listener interfaces which are sub interfaces of java.util.EventListener interface.
ActionListener, MouseListener, MouseMotionListener, KeyListener, WindowListener (others include ItemListener, FocusListener and TextListener).
What is the difference between service () method of generic servlet and http servlet? Explain complete sequence of request forwarding.
In GenericServlet, service(ServletRequest, ServletResponse) is abstract and protocol-independent, so the programmer must override it. HttpServlet already implements service(): it reads the HTTP method and calls doGet(), doPost() etc., so the programmer usually overrides those instead. Request forwarding: (1) the client sends a request to servlet A; (2) A gets a RequestDispatcher with request.getRequestDispatcher("pathB") (or from the ServletContext); (3) A may store data with request.setAttribute(); (4) A calls rd.forward(request, response) before committing any output; (5) the container passes the same request and response objects to resource B, which processes them and generates the response; (6) the response goes back to the client, whose browser URL still shows A because it was one request on the server.
Implement the following code using JSTL tags: <% ArrayList students = (ArrayList)request.getAttribute("sList"); for(int i=0; i<students.size(); i++) { StudentInfo s = (StudentInfo)students.get(i); String name = s.getName(); %> <%= name %> <% } // end for %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <c:forEach var="s" items="${requestScope.sList}"> <c:out value="${s.name}" /> </c:forEach>
Which type of information is present in (.tld) file? Mention any five.
A TLD file contains: the tag library version; the JSP version required; the short name (preferred prefix) and URI of the library; for each tag its name and the tag handler class; the body content type (empty, JSP, scriptless or tagdependent); and each attribute's name, whether it is required, and whether it accepts runtime expressions (rtexprvalue).
Create a server program that receives user's NIC number from client and sends it back to the client whose IP address is: 196.192.1.2 residing on the port 1008. server resides on the 1299 port. The message should be sent in the following format: "Your [user given NIC number] shall be safe". You are not supposed to write a client program.
import java.net.*; import java.io.*; public class NicServer { public static void main(String[] args) { try { ServerSocket ss = new ServerSocket(1299); // server listens on port 1299 Socket s = ss.accept(); // wait for the client (196.192.1.2) BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); PrintWriter pw = new PrintWriter(s.getOutputStream(), true); String nic = br.readLine(); // NIC number from client pw.println("Your " + nic + " shall be safe"); // send it back br.close(); pw.close(); s.close(); ss.close(); } catch (IOException e) { System.out.println(e); } } } The reply goes back over the connected socket, which already links to the client at 196.192.1.2 (port 1008), so no new connection is needed.
Differentiate between JSP's and servlets with example codes.
Servlets are Java classes that generate HTML from Java code (HTML inside out.println statements); they are best for processing/controller logic. JSPs are HTML pages with embedded Java (scriptlets, expressions, tags); they are translated into servlets by the container and are best for presentation. In a servlet any change in the page needs recompilation and the developer writes doGet()/doPost(); a JSP is compiled automatically on change and is easier for page designers. Servlet example: import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html><body><h1>Date: " + new java.util.Date() + "</h1></body></html>"); out.close(); } } JSP example: <%@ page import="java.util.*" %> <html><body> <h1>Date: <%= new Date() %></h1> </body></html>
To simplify code in JSP expressions and scriptlets eight variables or implicit objects are already defined in JSP API. Three of them are already given below. Write the names of other five objects. 0. request 1. response 2. out 3. ...
session (HttpSession), application (ServletContext), config (ServletConfig), pageContext (PageContext) and page (the current servlet instance, like this).
Differentiate between web pages and web services?
Web pages are meant for humans: a browser requests them and gets HTML for display, with presentation mixed with data. Web services are meant for programs: one application calls another over the network using standard XML-based protocols (SOAP messages, described by WSDL, discovered via UDDI or REST/JSON), receives structured data rather than formatted pages, and the service is platform- and language-independent so it can be reused and combined into other applications. A web page needs a person to read it; a web service exposes operations that software invokes.