Thursday, 12 March 2020

JSP interview questions and answers

Q1. What is JSP and why do we need it?

JSP stands for JavaServer Pages. JSP is java server side technology to create dynamic web pages. JSP is extension of Servlet technology to help developers create dynamic pages with HTML like syntax.

We can create user views in servlet also but the code will become very ugly and error-prone. Also, most of the elements on a web page are static, so the JSP page is more suitable for web pages. We should avoid business logic in JSP pages and try to use it only for view purpose. JSP scripting elements can be used for writing Java code in JSP pages but it’s best to avoid them and use JSP action elements, JSTL tags or custom tags to achieve the same functionalities.

One more benefit of JSP is that most of the containers support hot deployment of JSP pages. Just make the required changes in the JSP page and replace the old page with the updated jsp page in the deployment directory and the container will load the new JSP page. We don’t need to compile our project code or restart server whereas if we make a change in servlet code, we need to build the complete project again and deploy it. Although most of the containers now provide hot deployment support for applications still it’s more work that JSP pages.


Q2. What are the JSP lifecycle phases?

If you will look into JSP page code, it looks like HTML and doesn’t look anything like java classes. Actually JSP container takes care of translating the JSP pages and create the servlet class that is used in web application. JSP lifecycle phases are:

Translation – JSP container checks the JSP page code and parse it to generate the servlet source code. For example in Tomcat you will find generated servlet class files at TOMCAT/work/Catalina/localhost/WEBAPP/org/apache/jsp directory. If the JSP page name is home.jsp, usually the generated servlet class name is home_jsp and file name is home_jsp.java

Compilation – JSP container compiles the jsp class source code and produce class file in this phase.

Class Loading – Container loads the class into memory in this phase.

Instantiation – Container invokes the no-args constructor of generated class to load it into memory and instantiate it.

Initialization – Container invokes the init method of JSP class object and initializes the servlet config with init params configured in deployment descriptor. After this phase, JSP is ready to handle client requests. Usually from translation to initialization of JSP happens when first request for JSP comes but we can configure it to be loaded and initialized at the time of deployment like servlets using load-on-startup element.

Request Processing – This is the longest lifecycle of JSP page and JSP page processes the client requests. The processing is multi-threaded and similar to servlets and for every request a new thread is spawned and ServletRequest and ServletResponse object is created and JSP service method is invoked.

Destroy – This is the last phase of JSP lifecycle where JSP class is unloaded from memory. Usually it happens when application is undeployed or the server is shut down.


Q3. What are JSP lifecycle methods?

JSP lifecycle methods are:

jspInit(): This method is declared in JspPage and it’s implemented by JSP container implementations. This method is called once in the JSP lifecycle to initialize it with config params configured in deployment descriptor. We can override this method using JSP declaration scripting element to initialize any resources that we want to use in JSP page.

_jspService(): This is the JSP method that gets invoked by JSP container for each client request by passing request and response object. Notice that method name starts with underscore to distinguish it from other lifecycle methods because we can’t override this method. All the JSP code goes inside this method and it’s overridden by default. We should not try to override it using JSP declaration scripting element. This method is defined in HttpJspPage interface.

jspDestroy(): This method is called by container when JSP is unloaded from memory such as shutting down application or container. This method is called only once in JSP lifecycle and we should override this method to release any resources created in JSP init method.

Q4. Which JSP lifecycle methods can be overridden?

We can override jspInit() and jspDestroy() methods using JSP declaration scripting element. We should override jspInit() methods to create common resources that we would like to use in JSP service method and override jspDestroy() method to release the common resources.


Q5. How can we avoid direct access of JSP pages from client browser?

We know that anything inside the WEB-INF directory can’t be accessed directly in a web application, so we can place our JSP pages in WEB-INF directory to avoid direct access to JSP page from the client browser. But in this case, we will have to configure it in deployment descriptor just like Servlets. The sample configuration is given below code snippet of web.xml file.

<servlet>
  <servlet-name>Test</servlet-name>
  <jsp-file>/WEB-INF/test.jsp</jsp-file>
  <init-param>
    <param-name>test</param-name>
    <param-value>Test Value</param-value>
  </init-param>
</servlet>
 
<servlet-mapping>
  <servlet-name>Test</servlet-name>
  <url-pattern>/Test.do</url-pattern>
</servlet-mapping>

Q6. What are different types of comments in JSP?

JSP pages provide two types of comments that we can use:

HTML Comments: Since JSP pages are like HTML, we can use HTML comments like <!-- HTML Comment -->. These comments are sent to client also and we can see it in HTML source. So we should avoid any code level comments or debugging comments using HTML comments.

JSP Comments: JSP Comments are written using scriptlets like <%-- JSP Comment --%>. These comments are present in the generated servlet source code and doesn’t sent to client. For any code level or debugging information comments we should use JSP comments.

Q7. What is Scriptlet, Expression and Declaration in JSP?

Scriptlets, Expression and Declaration are scripting elements in JSP page using which we can add java code in the JSP pages.

A scriptlet tag starts with <% and ends with %>. Any code written inside the scriptlet tags go into the _jspService() method. For example;

<%
Date d = new Date();
System.out.println("Current Date="+d);
%>

Since most of the times we print dynamic data in JSP page using out.print() method, there is a shortcut to do this through JSP Expressions. JSP Expression starts with <%= and ends with %>.

<% out.print("Pankaj"); %> can be written using JSP Expression as <%= "Pankaj" %>

Notice that anything between <%= %> is sent as parameter to out.print() method. Also notice that scriptlets can contain multiple java statements and always ends with semicolon (;) but expression doesn’t end with semicolon.

JSP Declarations are used to declare member methods and variables of servlet class. JSP Declarations starts with <%! and ends with %>.

For example we can create an int variable in JSP at class level as <%! public static int count=0; %>.


Q8. What are JSP implicit objects?

JSP implicit objects are created by container while translating JSP page to Servlet source to help developers. We can use these objects directly in scriptlets that goes in service method, however we can’t use them in JSP Declaration because that code will go at class level.

We have 9 implicit objects that we can directly use in JSP page. Seven of them are declared as local variable at the start of _jspService() method whereas two of them are part of _jspService() method argument that we can use.

out Object
request Object
response Object
config Object
application Object
session Object
pageContext Object
page Object
exception Object


Q9. Can we use JSP implicit objects in a method defined in JSP Declaration?

No we can’t because JSP implicit objects are local to service method and added by JSP Container while translating JSP page to servlet source code. JSP Declarations code goes outside the service method and used to create class level variables and methods and hence can’t use JSP implicit objects.


Q10. Which implicit object is not available in normal JSP pages?

JSP exception implicit object is not available in normal JSP pages and it’s used in JSP error pages only to catch the exception thrown by the JSP pages and provide useful message to the client.


Q11. What are the benefits of PageContext implicit object?

JSP pageContext implicit object is instance of javax.servlet.jsp.PageContext abstract class implementation. We can use pageContext to get and set attributes with different scopes and to forward request to other resources. pageContext object also hold reference to other implicit object.

This is the only object that is common in both JSP implicit objects and in JSP EL implicit objects.


Q12. How do we configure init params for JSP?

We can configure init params for JSP similar to servlet in web.xml file, we need to configure JSP init params with servlet and servlet-mapping element. The only thing differs from servlet is jsp-file element where we need to provide the JSP page location.


Q13. Why use of scripting elements in JSP is discouraged?

JSP pages are mostly used for view purposes and all the business logic should be in the servlet or model classes. We should pass parameters to JSP page through attributes and then use them to create the HTML response in JSP page.

Most part of the JSP page contains HTML code and to help web designers to easily understand JSP page and develop them, JSP technology provides action elements, JSP EL, JSP Standard Tag Library and custom tags that we should use rather than scripting elements to bridge the gap between JSP HTML part and JSP java part.


Q14. Can we define a class in a JSP Page?

It’s not a good practice though, but we can define a class inside a JSP Page. Below is the sample code for this:

<%!
  private static class NestedClass { //static is better because Servlet is multi-threaded
  private final int num = 0;
  public int getNum() {
    return num;
  }
}
%>

Or

<%   
    class Person {
        //this will go inside method body, so can't be public
    }
%>

Q15. How can we disable java code or scripting in JSP page?

We can disable scripting elements in JSP pages through deployment descriptor configuration like below.

<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<scripting-invalid>true</scripting-invalid>
</jsp-property-group>
</jsp-config>

Above URL-pattern will disable scripting for all the JSP pages but if you want to disable it only for a specific page, you can give the JSP file name itself.


Q16. Explain JSP Action Elements or Action Tags?

JSP action elements or action tags are HTML like tags that provide useful functionalities such as working with Java Bean, including a resource, forwarding the request and to generate dynamic XML elements. JSP action elements always starts with jsp: and we can use them in JSP page directly without the need to import any tag libraries or any other configuration changes. Some of the important action elements are

jsp:useBean,
jsp:getProperty,
jsp:setProperty,
jsp:include,
jsp:forward.



Q17. What is difference between include directive and jsp:include action?

The difference between JSP include directive and include action is that in include directive the content to other resource is added to the generated servlet code at the time of translation whereas with include action it happens at runtime.

Another difference is that in JSP include action, we can pass params to be used in the included resource with jsp:param action element but in JSP include directive we can’t pass any params.

When the included resource is static such as header, footer, image files then we should use include directive for faster performance but if the included resource is dynamic and requires some parameters for processing then we should use include action tag.


Q18. What is JSP Expression Language and what are it’s benefits?

Most of the times we use JSP for view purposes and all the business logic is present in servlet code or model classes. When we receive client request in the servlet, we process it and then add attributes in request/session/context scope to be retrieved in JSP code. We also use request params, headers, cookies and init params in JSP to create response views.

We can use scriptlets and JSP expressions to retrieve attributes and parameters in JSP with java code and use it for view purpose. But for web designers, java code is hard to understand and that’s why JSP Specs 2.0 introduced Expression Language (EL) through which we can get attributes and parameters easily using HTML like tags.

Expression language syntax is ${name} and we can use EL implicit objects and EL operators to retrieve the attributes from different scopes and use them in JSP page.


Q19. What are JSP EL implicit objects and how it’s different from JSP implicit Objects?

JSP Expression Language provides many implicit objects that we can use to get attributes from different scopes and parameter values. Note that these are different from JSP implicit objects and contains only the attributes in given scope. The only common implicit object in JSP EL and JSP page is pageContext object.

Below table provides a list of implicit object in JSP EL.

JSP EL Implicit Objects Type Description
pageScope Map A map that contains the attributes set with page scope.
requestScope Map Used to get the attribute value with request scope.
sessionScope Map Used to get the attribute value with session scope.
applicationScope Map Used to get the attributes value from application scope.
param Map Used to get the request parameter value, returns a single value
paramValues Map Used to get the request param values in an array, useful when request parameter contain multiple values.
header Map Used to get request header information.
headerValues Map Used to get header values in an array.
cookie Map Used to get the cookie value in the JSP
initParam Map Used to get the context init params, we can’t use it for servlet init params
pageContext pageContext Same as JSP implicit pageContext object, used to get the request, session references etc. example usage is getting request HTTP Method name.


Q20. How to use JSP EL to get HTTP method name?

We can use pageContext JSP EL implicit object to get the request object reference and use dot operator to get the HTTP method name in JSP page. The JSP EL code for this will be

${pageContext.request.method}.


Q21. What is JSP Standard Tag Library, provide some example usage?

JSP Standard Tag Library or JSTL is more versatile than JSP EL or Action elements because we can loop through a collection or escape HTML tags to show them like text in response.

JSTL is part of the Java EE API and included in most servlet containers. But to use JSTL in our JSP pages, we need to download the JSTL jars for your servlet container. Most of the times, you can find them in the example projects and you can use them. You need to include these libraries in the project WEB-INF/lib directory. These jars are container specific, for example in Tomcat, we need to include jstl.jar and standard.jar jar files in the project build path.


Q22. What are the types of JSTL tags?

Based on the JSTL functions, they are categorized into five types.

Core Tags – Core tags provide support for iteration, conditional logic, catch exception, url, forward or redirect response etc.

Formatting and Localization Tags – These tags are provided for formatting of Numbers, Dates and i18n support through locales and resource bundles.

SQL Tags – JSTL SQL Tags provide support for interaction with relational databases such as Oracle, MySql etc.

XML Tags – XML tags are used to work with XML documents such as parsing XML, transforming
XML data and XPath expressions evaluation.

JSTL Functions Tags – JSTL tags provide a number of functions that we can use to perform common operation, most of them are for String manipulation such as String Concatenation, Split String etc.


Q23. What is JSP Custom Tag and what are it’s components?

Sometimes JSP EL, Action Tags and JSTL tags are not enough and we might get tempted to write java code to perform some operations in JSP page. Fortunately JSP is extendable and we can create our own custom tags to perform certain operations.

We can create JSP Custom Tags with following components:

JSP Custom Tag Handler
Creating Tag Library Descriptor (TLD) File
Deployment Descriptor Configuration for TLD
We can add custom tag library in JSP page using taglib directive and then use it.


Q24. Give an example where you need JSP Custom Tag?

Let’s say we want to show a number with formatting with commas and spaces. This can be very useful for user when the number is really long. So we want some custom tags like below:

<mytags:formatNumber number="123456.789" format="#,###.00"/>

Based on the number and format passed, it should write the formatted number in JSP page, for the above example it should print 123,456.79

We know that JSTL doesn’t provide any inbuilt tags to achieve this, so we will create our own custom tag implementation and use it in the JSP page.


Q25. Why don’t we need to configure JSP standard tags in web.xml?

We don’t need to configure JSP standard tags in web.xml because the TLD files are inside the META-INF directory of the JSTL jar files. When container loads the web application and finds TLD files inside the META-INF directory of the JAR file, it automatically configures them to be used directly in the application JSP pages. All we need to do it to include it in the JSP page using taglib directive.


Q26. How can we handle exceptions thrown by JSP service method?

To handle exceptions thrown by the JSP page, all we need is an error page and define the error page in JSP using page directive.

To create a JSP error page, we need to set the page directive attribute isErrorPage value to true, then we can access exception implicit object in the JSP and use it to send a customized error message to the client.

We need to define exception and error handler JSP pages in the deployment descriptor like below.
<error-page>
<error-code>404</error-code>
<location>/error.jsp</location>
</error-page>

<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/error.jsp</location>
</error-page>
Read more with example program at JSP Exception Handling.


Q27. How do we catch exception and process it using JSTL?

We can use JSTL Core tags c:catch and c:if to catch exception inside the JSP service method and process it. c:catch tag catches the exception and wraps it into the exception variable and we can use c:if condition tag to process it. Below code snippet provide sample usage.

<c:catch var ="exception">
   <% int x = 5/0;%>
</c:catch>

<c:if test = "${exception ne null}">
   <p>Exception is : ${exception} <br />
   Exception Message: ${exception.message}</p>
</c:if>
Notice the use of JSP EL in the c:if condition.


Q28. How do we print “<br> creates a new line in HTML” in JSP?

We can use c:out escapeXml attribute to escape the HTML elements so that it get’s shown as text in the browser, for this scenario we will write code like below.


<c:out value="<br> creates a new line in HTML" escapeXml="true"></c:out>


Q29. What is jsp-config in deployment descriptor?

jsp-config element is used to configure different parameters for JSP pages. Some of it’s usage are:

Configuring tag libraries for the web application like below.

<jsp-config>
<taglib>
<taglib-uri>https://journaldev.com/jsp/tlds/mytags</taglib-uri>
<taglib-location>/WEB-INF/numberformatter.tld</taglib-location>
</taglib>
</jsp-config>

We can control scripting elements in JSP pages.
We can control JSP Expression Language (EL) evaluation in JSP pages.
We can define the page encoding for URL pattern.
To define the buffer size to be used in JSP page out object.
To denote that the group of resources that match the URL pattern are JSP documents, and thus must be interpreted as XML documents.

Q30. How to ignore the EL expression evaluation in a JSP?

We can ignore EL evaluation in JSP page by two ways.

Using page directive as <%@ page isELIgnored="true" %>
Configuring in web.xml – better approach when you want to disable EL evaluation for many JSP pages.

<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<el-ignored>true</el-ignored>
</jsp-property-group>
</jsp-config>

Q31. When will Container initialize multiple JSP/Servlet Objects?

If we have multiple servlet and servlet-mapping elements in deployment descriptor for a single servlet or JSP page, then container will initialize an object for each of the element and all of these instances will have their own ServletConfig object and init params.

For example, if we configure a single JSP page in web.xml like below.

<servlet>
  <servlet-name>Test</servlet-name>
  <jsp-file>/WEB-INF/test.jsp</jsp-file>
  <init-param>
    <param-name>test</param-name>
    <param-value>Test Value</param-value>
  </init-param>
</servlet>
 
<servlet-mapping>
  <servlet-name>Test</servlet-name>
  <url-pattern>/Test.do</url-pattern>
</servlet-mapping>
 
<servlet>
  <servlet-name>Test1</servlet-name>
  <jsp-file>/WEB-INF/test.jsp</jsp-file>
</servlet>
 
<servlet-mapping>
  <servlet-name>Test1</servlet-name>
  <url-pattern>/Test1.do</url-pattern>
</servlet-mapping>
Then if we can access the same JSP page with both the URI pattern and both will have their own init params values.


Q32. How can we prevent implicit session creation in JSP?

By default JSP page creates a session but sometimes we don’t need session in JSP page. We can use JSP page directive session attribute to indicate compiler to not create session by default. It’s default value is true and session is created. To disable the session creation, we can use it like below.

<%@ page session="false" %>

Q33. What is difference between JspWriter and Servlet PrintWriter?

PrintWriter is the actual object responsible for writing the content in response. JspWriter uses the PrintWriter object behind the scene and provide buffer support. When the buffer is full or flushed, JspWriter uses the PrintWriter object to write the content into response.


Q34. How can we extend JSP technology?
We can extend JSP technology with custom tags to avoid scripting elements and java code in JSP pages.


Q35. Provide some JSP Best Practices?

Some of the JSP best practices are:

Avoid scripting elements in JSP pages. If JSP EL, action elements and JSTL not serve your needs then create custom tags.

Use comment properly, use JSP comments for code level or debugging purpose so that it’s not sent to client.

Avoid any business logic in JSP page, JSP pages should be used only for response generation for client.

Disable session creation in JSP page where you don’t need it for better performance.

Use page, taglib directives at the start of JSP page for better readability.

Proper use of jsp include directive or include action based on your requirements, include directive is good for static content whereas include action is good for dynamic content and including resource at runtime.

Proper exception handling using JSP error pages to avoid sending container generated response incase JSP pages throw exception in service method.

If you are having CSS and JavaScript code in JSP pages, it’s best to place them in separate files and include them in JSP page.

Most of the times JSTL is enough for our needs, if you find a scenario where it’s not then check your application design and try to put the logic in a servlet that will do the processing and then set attributes to be used in JSP pages.

Yes why not, I have seen some developers getting confused with this. Even though JSP is a server-side technology, it’s used to generate a client-side response and we can add javascript or CSS code like any other HTML page.


Q36. How can we prevent implicit session creation in JSP?

By default JSP page creates a session but sometimes we don’t need session in JSP page. We can use JSP page directive session attribute to indicate compiler to not create session by default. It’s default value is true and session is created. To disable the session creation, we can use it like below.

<%@ page session="false" %>

Q37. What is difference between JspWriter and Servlet PrintWriter?
PrintWriter is the actual object responsible for writing the content in response. JspWriter uses the PrintWriter object behind the scene and provide buffer support. When the buffer is full or flushed, JspWriter uses the PrintWriter object to write the content into response.


Servlet Interview Questions and Answers

Q1. What is different between web server and application server?

A web server responsibility is to handler HTTP requests from client browsers and respond with HTML response. A web server understands HTTP language and runs on HTTP protocol.
Apache Web Server is kind of a web server and then we have specific containers that can execute servlets and JSPs known as the servlet container, for example, Tomcat.
Application Servers provide additional features such as Enterprise JavaBeans support, JMS Messaging support, Transaction Management, etc. So we can say that the Application server is a web server with additional functionalities to help developers with enterprise applications.


Q2. Which HTTP method is non-idempotent?

An HTTP method is said to be idempotent if it returns the same result every time. HTTP methods GET, PUT, DELETE, HEAD, and OPTIONS are idempotent method and we should implement our application to make sure these methods always return the same result. HTTP method POST is non-idempotent method and we should use post method when implementing something that changes with every request.

For example, to access an HTML page or image, we should use GET because it will always return the same object but if we have to save customer information to the database, we should use the POST method. Idempotent methods are also known as safe methods and we don’t care about the repetitive request from the client for safe methods.


Q3. What is the difference between GET and POST method?

GET is a safe method (idempotent) where POST is non-idempotent method.
We can send limited data with GET method and it’s sent in the header request URL whereas we can send large amount of data with POST because it’s part of the body.
GET method is not secure because data is exposed in the URL and we can easily bookmark it and send similar request again, POST is secure because data is sent in request body and we can’t bookmark it.
GET is the default HTTP method whereas we need to specify method as POST to send request with POST method.
Hyperlinks in a page uses GET method.


Q4. What is MIME Type? (Multipurpose Internet Mail Extensions)

The “Content-Type” response header is known as MIME Type. Server sends MIME type to client to let them know the kind of data it’s sending. It helps client in rendering the data for user. Some of the mostly used mime types are text/html, text/xml, application/xml etc.

We can use ServletContext getMimeType() method to get the correct MIME type of the file and use it to set the response content type. It’s very useful in downloading a file through servlet from the server.


Q5. What is a web application and what is its directory structure?

Web Applications are modules that run on the server to provide both static and dynamic content to the client browser. Apache webserver supports PHP and we can create a web application using PHP. Java provides web application support through Servlets and JSPs that can run in a servlet container and provide dynamic content to the client browser.

Java Web Applications are packaged as Web Archive (WAR) and it has a defined structure like below image.



Q6. What is a servlet?

Java Servlet is server side technologies to extend the capability of web servers by providing support for dynamic response and data persistence.

The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing our own servlets.

All servlets must implement the javax.servlet.Servlet interface, which defines servlet lifecycle methods. When implementing a generic service, we can extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet() and doPost(), for handling HTTP-specific services.

Most of the times, web applications are accessed using HTTP protocol and that’s why we mostly extend HttpServlet class. Servlet API hierarchy is shown in the below image.



Q7. What are the advantages of Servlet over CGI?

Servlet technology was introduced to overcome the shortcomings of CGI technology.

Servlets provide better performance than CGI in terms of processing time, memory utilization because servlets use benefits of multithreading and for each request, a new thread is created, that is faster than loading creating new Object for each request with CGI.
Servlets and platform and system independent, the web application developed with Servlet can be run on any standard web container such as Tomcat, JBoss, Glassfish servers and on operating systems such as Windows, Linux, Unix, Solaris, Mac, etc.
Servlets are robust because container takes care of the life cycle of servlet and we don’t need to worry about memory leaks, security, garbage collection, etc.
Servlets are maintainable and the learning curve is small because all we need to take care is business logic for our application.


Q8. What are common tasks performed by Servlet Container?

Servlet containers are also known as web container, for example, Tomcat. Some of the important tasks of servlet container are:

Communication Support: Servlet Container provides easy way of communication between web client (Browsers) and the servlets and JSPs. Because of the container, we don’t need to build a server socket to listen for any request from the web client, parse the request and generate a response. All these important and complex tasks are done by container and all we need to focus is on business logic for the applications.

Lifecycle and Resource Management: Servlet Container takes care of managing the life cycle of servlet. From the loading of servlets into memory, initializing servlets, invoking servlet methods and to destroy them. The container also provides utility like JNDI for resource pooling and management.

Multithreading Support: Container creates a new thread for every request to the servlet and provides them request and response objects to the processing. So servlets are not initialized for each request and save time and memory.

JSP Support: JSPs doesn’t look like normal java classes but every JSP in the application is compiled by container and converted to Servlet and then container manages them like other servlets.

Miscellaneous Task: Servlet container manages the resource pool, perform memory optimizations, execute garbage collector, provides security configurations, support for multiple applications, hot deployment and several other tasks behind the scene that makes a developer life easier.


Q9. What is ServletConfig object?

javax.servlet.ServletConfig is used to pass configuration information to Servlet. Every servlet has it’s own ServletConfig object and servlet container is responsible for instantiating this object. We can provide servlet init parameters in web.xml file or through use of WebInitParam annotation. We can use getServletConfig() method to get the ServletConfig object of the servlet.


Q10. What is ServletContext object?

javax.servlet.ServletContext interface provides access to web application parameters to the servlet. The ServletContext is unique object and available to all the servlets in the web application. When we want some init parameters to be available to multiple or all of the servlets in the web application, we can use ServletContext object and define parameters in web.xml using <context-param> element. We can get the ServletContext object via the getServletContext() method of ServletConfig. Servlet containers may also provide context objects that are unique to a group of servlets and which is tied to a specific portion of the URL path namespace of the host.

ServletContext is enhanced in Servlet Specs 3 to introduce methods through which we can programmatically add Listeners and Filters and Servlet to the application. It also provides some utility methods such as getMimeType(), getResourceAsStream() etc.


Q11. What is difference between ServletConfig and ServletContext?

Some of the differences between ServletConfig and ServletContext are:

ServletConfig is a unique object per servlet whereas ServletContext is a unique object for complete application.
ServletConfig is used to provide init parameters to the servlet whereas ServletContext is used to provide application level init parameters that all other servlets can use.
We can’t set attributes in ServletConfig object whereas we can set attributes in ServletContext that other servlets can use in their implementation.


Q12. What is Request Dispatcher?

RequestDispatcher interface is used to forward the request to another resource that can be HTML, JSP or another servlet in the same application. We can also use this to include the content of another resource to the response. This interface is used for inter-servlet communication in the same context.

There are two methods defined in this interface:

void forward(ServletRequest request, ServletResponse response) – forwards the request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.
void include(ServletRequest request, ServletResponse response) – includes the content of a resource (servlet, JSP page, HTML file) in the response.
We can get RequestDispatcher in a servlet using ServletContext getRequestDispatcher(String path) method. The path must begin with a / and is interpreted as relative to the current context root.


Q13. What is difference between PrintWriter and ServletOutputStream?

PrintWriter is a character-stream class whereas ServletOutputStream is a byte-stream class. We can use PrintWriter to write character based information such as character array and String to the response whereas we can use ServletOutputStream to write byte array data to the response.

We can use ServletResponse getWriter() to get the PrintWriter instance whereas we can use ServletResponse getOutputStream() method to get the ServletOutputStream object reference.


Q14. Can we get PrintWriter and ServletOutputStream both in a servlet?

We can’t get instances of both PrintWriter and ServletOutputStream in a single servlet method, if we invoke both the methods; getWriter() and getOutputStream() on response; we will get java.lang.IllegalStateException at runtime with message as other method has already been called for this response.


Q15. How can we create deadlock situation in servlet?

We can create deadlock in servlet by making a loop of method invocation, just call doPost() method from doGet() method and doGet() method to doPost() method to create deadlock situation in servlet.


Q16. What is the use of servlet wrapper classes?

Servlet HTTP API provides two wrapper classes – HttpServletRequestWrapper and HttpServletResponseWrapper. These wrapper classes are provided to help developers with custom implementation of servlet request and response types. We can extend these classes and override only specific methods we need to implement for custom request and response objects. These classes are not used in normal servlet programming.


Q17. What is SingleThreadModel interface?

SingleThreadModel interface was provided for thread safety and it guarantees that no two threads will execute concurrently in the servlet’s service method. However, SingleThreadModel does not solve all thread-safety issues. For example, session attributes and static variables can still be accessed by multiple requests on multiple threads at the same time, even when SingleThreadModel servlets are used. Also, it takes out all the benefits of multithreading support of servlets, that’s why this interface is Deprecated in Servlet 2.4.


Q18. Do we need to override service() method?

When servlet container receives client request, it invokes the service() method which in turn invokes the doGet(), doPost() methods based on the HTTP method of request. I don’t see any use case where we would like to override the service() method. The whole purpose of service() method is to forward to request to corresponding HTTP method implementations. If we have to do some pre-processing of request, we can always use servlet filters and listeners.


Q19. Is it good idea to create servlet constructor?

We can define a constructor for servlet but I don’t think it’s of any use because we won’t be having access to the ServletConfig object until unless servlet is initialized by the container. Ideally, if we have to initialize any resource for the servlet, we should override init() method where we can access servlet init parameters using ServletConfig object.


Q20. What is difference between GenericServlet and HttpServlet?

GenericServlet is protocol independent implementation of Servlet interface whereas HttpServlet is HTTP protocol specific implementation. Most of the times we use servlet for creating web application and that’s why we extend HttpServlet class. HttpServlet class extends GenericServlet and also provide some other methods specific to HTTP protocol.


Q21. What is the inter-servlet communication?

When we want to invoke another servlet from a servlet service methods, we use inter-servlet communication mechanisms. We can invoke another servlet using RequestDispatcher forward() and include() methods and provide additional attributes in request for other servlet use.


Q22. Are Servlets Thread Safe? How to achieve thread-safety in servlets?

HttpServlet init() method and destroy() method are called only once in the servlet life cycle, so we don’t need to worry about their synchronization. But service methods such as doGet() or doPost() are getting called in every client request and since servlet uses multithreading, we should provide thread safety in these methods.

If there are any local variables in service methods, we don’t need to worry about their thread-safety because they are specific to each thread but if we have a shared resource then we can use synchronization to achieve thread-safety in servlets when working with shared resources.

The thread safety mechanisms are similar to thread safety in standalone java application.


Q23. What is servlet attributes and their scope?

Servlet attributes are used for inter-servlet communication, we can set, get and remove attributes in web application. There are three scopes for servlet attributes – request scope, session scope and application scope.

ServletRequest, HttpSession, and ServletContext interfaces provide methods to get/set/remove attributes from request, session and application scope respectively.

Servlet attributes are different from init parameters defined in web.xml for ServletConfig or ServletContext.


Q24. How do we call one servlet from another servlet?

We can use RequestDispatcher forward() method to forward the processing of a request to another servlet. If we want to include the another servlet output to the response, we can use RequestDispatcher include() method.


Q25. How can we invoke another servlet in a different application?

We can’t use RequestDispatcher to invoke servlet from another application because it’s specific for the application. If we have to forward the request to a resource in another application, we can use the ServletResponse sendRedirect() method and provide the complete URL of another servlet. This sends the response to the client with the response code as 302 to forward the request to another URL. If we have to send some data also, we can use cookies that will be part of the servlet response and sent in the request to another servlet.


Q26. What is difference between ServletResponse sendRedirect() and RequestDispatcher forward() method?

RequestDispatcher forward() is used to forward the same request to another resource whereas ServletResponse sendRedirect() is a two step process. In sendRedirect(), web application returns the response to client with status code 302 (redirect) with URL to send the request. The request sent is a completely new request.
forward() is handled internally by the container whereas sednRedirect() is handled by browser.
We should use forward() when accessing resources in the same application because it’s faster than sendRedirect() method that required an extra network call.
In forward() browser is unaware of the actual processing resource and the URL in address bar remains same whereas in sendRedirect() URL in address bar change to the forwarded resource.
forward() can’t be used to invoke a servlet in another context, we can only use sendRedirect() in this case.


Q27. Why HttpServlet class is declared abstract?

HttpServlet class provide HTTP protocol implementation of servlet but it’s left abstract because there is no implementation logic in service methods such as doGet() and doPost() and we should override at least one of the service methods. That’s why there is no point in having an instance of HttpServlet and is declared abstract class.


Q28. What are the phases of servlet life cycle?

We know that Servlet Container manages the life cycle of Servlet, there are four phases of servlet life cycle.

Servlet Class Loading – When container receives a request for a servlet, it first loads the class into memory and calls it’s default no-args constructor.
Servlet Class Initialization – Once the servlet class is loaded, container initializes the ServletContext object for the servlet and then invoke its init method by passing the servlet config object. This is the place where a servlet class transforms from normal class to servlet.
Request Handling – Once the servlet is initialized, it’s ready to handle the client requests. For every client request, servlet container spawns a new thread and invokes the service() method by passing the request and response object reference.
Removal from Service – When container stops or we stop the application, servlet container destroys the servlet class by invoking the destroy() method.


Q29. What are life cycle methods of a servlet?

Servlet Life Cycle consists of three methods:

public void init(ServletConfig config) – This method is used by container to initialize the servlet, this method is invoked only once in the lifecycle of servlet.

public void service(ServletRequest request, ServletResponse response) – This method is called once for every request, container can’t invoke service() method until unless init() method is executed.

public void destroy() – This method is invoked once when servlet is unloaded from memory.


Q30. why we should override only no-agrs init() method?

If we have to initialize some resource before we want our servlet to process client requests, we should override the init() method. If we override init(ServletConfig config) method, then the first statement should be super(config) to make sure superclass init(ServletConfig config) method is invoked first. That’s why GenericServlet provides another helper init() method without argument that get’s called at the end of init(ServletConfig config) method. We should always utilize this method for overriding init() method to avoid any issues as we may forget to add super() call in overriding init method with ServletConfig argument.


Q31. What is URL Encoding?

URL Encoding is the process of converting data into CGI form so that it can travel across the network without any issues. URL Encoding strips the white spaces and replaces special characters with escape characters. We can use java.net.URLEncoder.encode(String str, String unicode) to encode a String. URL Decoding is the reverse process of encoding and we can use java.net.URLDecoder.decode(String str, String unicode) to decode the encoded string.


Q32. What are different methods of session management in servlets?

The session is a conversational state between client and server and it can consist of multiple request and response between client and server. Since HTTP and Web Server both are stateless, the only way to maintain a session is when some unique information about the session (session-id) is passed between server and client in every request and response.

Some of the common ways of session management in servlets are:

User Authentication
HTML Hidden Field
Cookies
URL Rewriting
Session Management API


Q33. What is URL Rewriting?

We can use HttpSession for session management in servlets but it works with Cookies and we can disable the cookie in client browser. Servlet API provides support for URL rewriting that we can use to manage session in this case.

The best part is that from a coding point of view, it’s very easy to use and involves one step – encoding the URL. Another good thing with Servlet URL Encoding is that it’s a fallback approach and it kicks in only if browser cookies are disabled.

We can encode URL with HttpServletResponse encodeURL() method and if we have to redirect the request to another resource and we want to provide session information, we can use encodeRedirectURL() method.


Q34. How does Cookies work in Servlets?

Cookies are used a lot in web client-server communication, it’s not something specific to java. Cookies are text data sent by server to the client and it gets saved at the client local machine.
Servlet API provides cookies support through javax.servlet.http.Cookie class that implements Serializable and Cloneable interfaces.
HttpServletRequest getCookies() method is provided to get the array of Cookies from the request, since there is no point of adding Cookie to request, there are no methods to set or add a cookie to request.
Similarly, HttpServletResponse addCookie(Cookie c) method is provided to attach cookie in the response header, there are no getter methods for a cookie.


Q35. How to notify an object in session when session is invalidated or timed-out?

If we have to make sure an object gets notified when session is destroyed, the object should implement javax.servlet.http.HttpSessionBindingListener interface. This interface defines two callback methods – valueBound() and valueUnbound() that we can define to implement processing logic when the object is added as attribute to the session and when session is destroyed.


Q36. What is the difference between encodeRedirectUrl and encodeURL?

HttpServletResponse provide method to encode URL in HTML hyperlinks so that the special characters and white spaces are escaped and append session id to the URL. It behaves similar to URLEncoder encode method with additional process to append jsessionid parameter at the end of the URL.

However HttpServletResponse encodeRedirectUrl() method is used specially for encode the redirect URL in response.

So when we are providing URL rewriting support, for hyperlinks in HTML response, we should use encodeURL() method whereas for redirect URL we should use encodeRedirectUrl() method.


Q37. Why do we have servlet filters?

Servlet Filters are pluggable java components that we can use to intercept and process requests before they are sent to servlets and response after servlet code is finished and before container sends the response back to the client.

Some common tasks that we can do with filters are:

Logging request parameters to log files.
Authentication and authorization of request for resources.
Formatting of request body or header before sending it to servlet.
Compressing the response data sent to the client.
Alter response by adding some cookies, header information etc.


Q38. What is the effective way to make sure all the servlets are accessible only when the user has a valid session?

We know that servlet filters can be used to intercept request between a servlet container and servlet, we can utilize it to create an authentication filter and check if the request contains a valid session or not.


Q39. Why do we have servlet listeners?

We know that using ServletContext, we can create an attribute with application scope that all other servlets can access but we can initialize ServletContext init parameters as String only in the deployment descriptor (web.xml). What if our application is database-oriented and we want to set an attribute in ServletContext for Database Connection.

If your application has a single entry point (user login), then you can do it in the first servlet request but if we have multiple entry points then doing it everywhere will result in a lot of code redundancy. Also if the database is down or not configured properly, we won’t know until the first client request comes to the server. To handle these scenarios, servlet API provides Listener interfaces that we can implement and configure to listen to an event and do certain operations.


Q40. How to handle exceptions thrown by application with another servlet?

If you notice, doGet() and doPost() methods throw ServletException and IOException. Since browser understand only HTML, when our application throw exception, servlet container processes the exception and generate a HTML response. Same goes with other error codes like 404, 403 etc.

Servlet API provides support for custom Exception and Error Handler servlets that we can configure in the deployment descriptor, the whole purpose of these servlets are to handle the Exception or Error raised by application and send HTML response that is useful for the user. We can provide a link to the application home page or some details to let the user know what went wrong.

We can configure them in web.xml like below:
<error-page>
<error-code>404</error-code>
    <location>/AppExceptionHandler</location>
</error-page>
 
<error-page>
  <exception-type>javax.servlet.ServletException</exception-type>
  <location>/AppExceptionHandler</location>
</error-page>


Q41. What is a deployment descriptor?

The deployment descriptor is a configuration file for the web application and its name is web.xml and it resides in WEB-INF directory. Servlet container uses this file to configure web application servlets, servlet config params, context init params, filters, listeners, welcome pages and error handlers.

With servlet 3.0 annotations, we can remove a lot of clutter from web.xml by configuring servlets, filters, and listeners using annotations.


Q42. How to make sure a servlet is loaded at the application startup?

Usually, servlet container loads a servlet on the first client request. Sometimes the servlet is heavy and takes time to loads, we might want to load it on application startup. We can use a load-on-startup element with servlet configuration in the web.xml file or use WebServlet annotation loadOnStartup variable to tell the container to load the servlet on system startup.

<servlet>
<servlet-name>foo</servlet-name>
<servlet-class>com.foo.servlets.Foo</servlet-class>
<load-on-startup>5</load-on-startup>
</servlet>

The load-on-startup value should be int, if it’s a negative integer then servlet container will load the servlet based on client requests and requirement but if it’s 0 or positive, then the container will load it on application startup.

If there are multiple servlets with load-on-startup value such as 0,1,2,3 then lower integer value servlet will be loaded first.


Q43. How to get the actual path of servlet in server?

We can use following code snippet to get the actual path of the servlet in file system.

getServletContext().getRealPath(request.getServletPath())


Q44. How to get the server information in a servlet?

We can use below code snippet to get the servlet information in a servlet through servlet context object.

getServletContext().getServerInfo()


Q45. Write a servlet to upload file on server.

File Upload and Download and common tasks in a java web application. Unfortunately Servlet API doesn’t provide easy methods to upload file on server, so we can use Apache FileUpload jar to make our life easier.

Please read File Upload Servlet post that provide all the necessary details with example program to upload and download file using servlets.


Q46. How do we go with database connection and log4j integration in servlet?

If you work with database connection a lot in your web application, its best to initialize it in a servlet context listener and set it as a context attribute for other servlets to use. Integrating Log4j is also very easy in web applications, all we need is a log4j configuration XML or property file and then configure it in a servlet context listener.


Q47. How to get the IP address of client in servlet?

We can use request.getRemoteAddr() to get the client IP address in servlet.


Q48. What are important features of Servlet 3?

Servlet Specs 3.0 was a major release and some of the important features are:

Servlet Annotations: Prior to Servlet 3, all the servlet mapping and its init parameters were used to defined in web.xml, this was not convenient and more error prone when number of servlets are huge in an application.
Servlet 3 introduced the use of Java annotations to define a servlet, filter and listener servlets and init parameters.
Some of the important Servlet API annotations are WebServlet, WebInitParam, WebFilter, and WebListener.

Web Fragments: Prior to servlet specs 3.0, all the web application configurations are required to be present in the web.xml that makes it cluttered with a lot of elements and chances of error increases. So servlet 3 specs introduced web fragments where we can have multiple modules in a single web application, all these modules should have a web-fragment.xml file in META-INF directory. We can include all the elements of web.xml inside the web-fragment.xml too. This helps us in dividing our web application into separate modules that are included as a JAR file in the web application lib directory.

Adding Web Components dynamically: We can use ServletContext object to add servlets, filters and listeners programmatically. This helps us in building a dynamic system where we are loading a component only if we need it. These methods are addServlet(), addFilter() and addListener() defined in the servlet context object.

Asynchronous Processing: Asynchronous support was added to delegate the request processing to another thread rather than keeping the servlet thread busy. It can increase the throughput performance of the application. This is an advance topic and I recommend to read Async Servlet tutorial.


Q49. What are different ways for servlet authentication?

Servlet Container provides different ways of login based servlet authentication:

HTTP Basic Authentication
HTTP Digest Authentication
HTTPS Authentication
Form Based Login:

A standard HTML form for authentication, advantage is that we can change the login page layout as our application requirements rather than using HTTP built-in login mechanisms.


Q50. How can we achieve transport layer security for our web application?

We can configure our servlet container to use SSL for message communication over the network. To configure SSL on Tomcat, we need a digital certificate that can be created using Java keytool for a development environment. For the production environment, you should get the digital certificate from SSL certificate providers, for example, Verisign or Entrust.

Monday, 9 September 2019

S.O.L.I.D: The First 5 Principles of Object Oriented Design (OOD)

S.O.L.I.D is an acronym for the first five object-oriented design(OOD)** principles** by Robert C. Martin, popularly known as Uncle Bob.

These principles, when combined together, make it easy for a programmer to develop software that are easy to maintain and extend. They also make it easy for developers to avoid code smells, easily refactor code, and are also a part of the agile or adaptive software development.

Note: this is just a simple "welcome to _S.O.L.I.D" article, it simply sheds light on what S.O.L.I.D is_.

Single-responsibility Principle
Open-closed Principle
Liskov substitution principle
Interface segregation principle
Dependency Inversion principle

Conclusion
S.O.L.I.D stands for: When expanded the acronyms might seem complicated, but they are pretty simple to grasp.

S - Single-responsiblity principle
O - Open-closed principle
L - Liskov substitution principle
I - Interface segregation principle
D - Dependency Inversion Principle
Let's look at each principle individually to understand why S.O.L.I.D can help make us better developers.

Single-responsibility Principle
S.R.P for short - this principle states that:

A class should have one and only one reason to change, meaning that a class should have only one job.

For example, say we have some shapes and we wanted to sum all the areas of the shapes. Well this is pretty simple right?

Essential Reading: Learn React from Scratch! (2019 Edition)
class Circle {
    public $radius;

    public function construct($radius) {
        $this->radius = $radius;
    }
}

class Square {
    public $length;

    public function construct($length) {
        $this->length = $length;
    }
}
First, we create our shapes classes and have the constructors setup the required parameters. Next, we move on by creating the AreaCalculator class and then write up our logic to sum up the areas of all provided shapes.

class AreaCalculator {

    protected $shapes;

    public function __construct($shapes = array()) {
        $this->shapes = $shapes;
    }

    public function sum() {
        // logic to sum the areas
    }

    public function output() {
        return implode('', array(
            "",
                "Sum of the areas of provided shapes: ",
                $this->sum(),
            ""
        ));
    }
}
To use the AreaCalculator class, we simply instantiate the class and pass in an array of shapes, and display the output at the bottom of the page.

$shapes = array(
    new Circle(2),
    new Square(5),
    new Square(6)
);

$areas = new AreaCalculator($shapes);

echo $areas->output();
The problem with the output method is that the AreaCalculator handles the logic to output the data. Therefore, what if the user wanted to output the data as json or something else?

All of that logic would be handled by the AreaCalculator class, this is what SRP frowns against; the AreaCalculator class should only sum the areas of provided shapes, it should not care whether the user wants json or HTML.

So, to fix this you can create an SumCalculatorOutputter class and use this to handle whatever logic you need to handle how the sum areas of all provided shapes are displayed.

The SumCalculatorOutputter class would work like this:

$shapes = array(
    new Circle(2),
    new Square(5),
    new Square(6)
);

$areas = new AreaCalculator($shapes);
$output = new SumCalculatorOutputter($areas);

echo $output->JSON();
echo $output->HAML();
echo $output->HTML();
echo $output->JADE();
Now, whatever logic you need to output the data to the user is now handled by the SumCalculatorOutputter class.

Open-closed Principle
Objects or entities should be open for extension, but closed for modification.

This simply means that a class should be easily extendable without modifying the class itself. Let's take a look at the AreaCalculator class, especially it's sum method.

public function sum() {
    foreach($this->shapes as $shape) {
        if(is_a($shape, 'Square')) {
            $area[] = pow($shape->length, 2);
        } else if(is_a($shape, 'Circle')) {
            $area[] = pi() * pow($shape->radius, 2);
        }
    }

    return array_sum($area);
}
If we wanted the sum method to be able to sum the areas of more shapes, we would have to add more if/else blocks and that goes against the Open-closed principle.

A way we can make this sum method better is to remove the logic to calculate the area of each shape out of the sum method and attach it to the shape's class.

class Square {
    public $length;

    public function __construct($length) {
        $this->length = $length;
    }

    public function area() {
        return pow($this->length, 2);
    }
}
The same thing should be done for the Circle class, an area method should be added. Now, to calculate the sum of any shape provided should be as simple as:

public function sum() {
    foreach($this->shapes as $shape) {
        $area[] = $shape->area();
    }

    return array_sum($area);
}
Now we can create another shape class and pass it in when calculating the sum without breaking our code. However, now another problem arises, how do we know that the object passed into the AreaCalculator is actually a shape or if the shape has a method named area?

Coding to an interface is an integral part of S.O.L.I.D, a quick example is we create an interface, that every shape implements:

interface ShapeInterface {
    public function area();
}

class Circle implements ShapeInterface {
    public $radius;

    public function __construct($radius) {
        $this->radius = $radius;
    }

    public function area() {
        return pi() * pow($this->radius, 2);
    }
}
In our AreaCalculator sum method we can check if the shapes provided are actually instances of the ShapeInterface, otherwise we throw an exception:

public function sum() {
    foreach($this->shapes as $shape) {
        if(is_a($shape, 'ShapeInterface')) {
            $area[] = $shape->area();
            continue;
        }

        throw new AreaCalculatorInvalidShapeException;
    }

    return array_sum($area);
}
Liskov substitution principle
Let q(x) be a property provable about objects of x of type T. Then q(y) should be provable for objects y of type S where S is a subtype of T.

All this is stating is that every subclass/derived class should be substitutable for their base/parent class.

Still making use of out AreaCalculator class, say we have a VolumeCalculator class that extends the AreaCalculator class:

class VolumeCalculator extends AreaCalulator {
    public function construct($shapes = array()) {
        parent::construct($shapes);
    }

    public function sum() {
        // logic to calculate the volumes and then return and array of output
        return array($summedData);
    }
}
In the SumCalculatorOutputter class:

class SumCalculatorOutputter {
    protected $calculator;

    public function __constructor(AreaCalculator $calculator) {
        $this->calculator = $calculator;
    }

    public function JSON() {
        $data = array(
            'sum' => $this->calculator->sum();
        );

        return json_encode($data);
    }

    public function HTML() {
        return implode('', array(
            '',
                'Sum of the areas of provided shapes: ',
                $this->calculator->sum(),
            ''
        ));
    }
}
If we tried to run an example like this:

$areas = new AreaCalculator($shapes);
$volumes = new AreaCalculator($solidShapes);

$output = new SumCalculatorOutputter($areas);
$output2 = new SumCalculatorOutputter($volumes);
The program does not squawk, but when we call the HTML method on the $output2 object we get an E_NOTICE error informing us of an array to string conversion.

To fix this, instead of returning an array from the VolumeCalculator class sum method, you should simply:

public function sum() {
    // logic to calculate the volumes and then return and array of output
    return $summedData;
}
The summed data as a float, double or integer.

Interface segregation principle
A client should never be forced to implement an interface that it doesn't use or clients shouldn't be forced to depend on methods they do not use.

Still using our shapes example, we know that we also have solid shapes, so since we would also want to calculate the volume of the shape, we can add another contract to the ShapeInterface:

interface ShapeInterface {
    public function area();
    public function volume();
}
Any shape we create must implement the volume method, but we know that squares are flat shapes and that they do not have volumes, so this interface would force the Square class to implement a method that it has no use of.

ISP says no to this, instead you could create another interface called SolidShapeInterface that has the volume contract and solid shapes like cubes e.t.c can implement this interface:

interface ShapeInterface {
    public function area();
}

interface SolidShapeInterface {
    public function volume();
}

class Cuboid implements ShapeInterface, SolidShapeInterface {
    public function area() {
        // calculate the surface area of the cuboid
    }

    public function volume() {
        // calculate the volume of the cuboid
    }
}
This is a much better approach, but a pitfall to watch out for is when type-hinting these interfaces, instead of using a ShapeInterface or a SolidShapeInterface.

You can create another interface, maybe ManageShapeInterface, and implement it on both the flat and solid shapes, this way you can easily see that it has a single API for managing the shapes. For example:

interface ManageShapeInterface {
    public function calculate();
}

class Square implements ShapeInterface, ManageShapeInterface {
    public function area() { /Do stuff here/ }

    public function calculate() {
        return $this->area();
    }
}

class Cuboid implements ShapeInterface, SolidShapeInterface, ManageShapeInterface {
    public function area() { /Do stuff here/ }
    public function volume() { /Do stuff here/ }

    public function calculate() {
        return $this->area() + $this->volume();
    }
}
Now in AreaCalculator class, we can easily replace the call to the area method with calculate and also check if the object is an instance of the ManageShapeInterface and not the ShapeInterface.

Dependency Inversion principle
The last, but definitely not the least states that:

Entities must depend on abstractions not on concretions. It states that the high level module must not depend on the low level module, but they should depend on abstractions.

This might sound bloated, but it is really easy to understand. This principle allows for decoupling, an example that seems like the best way to explain this principle:

class PasswordReminder {
    private $dbConnection;

    public function __construct(MySQLConnection $dbConnection) {
        $this->dbConnection = $dbConnection;
    }
}
First the MySQLConnection is the low level module while the PasswordReminder is high level, but according to the definition of D in S.O.L.I.D. which states that Depend on Abstraction not on concretions, this snippet above violates this principle as the PasswordReminder class is being forced to depend on the MySQLConnection class.

Later if you were to change the database engine, you would also have to edit the PasswordReminder class and thus violates Open-close principle.

The PasswordReminder class should not care what database your application uses, to fix this again we "code to an interface", since high level and low level modules should depend on abstraction, we can create an interface:

interface DBConnectionInterface {
    public function connect();
}
The interface has a connect method and the MySQLConnection class implements this interface, also instead of directly type-hinting MySQLConnection class in the constructor of the PasswordReminder, we instead type-hint the interface and no matter the type of database your application uses, the PasswordReminder class can easily connect to the database without any problems and OCP is not violated.

class MySQLConnection implements DBConnectionInterface {
    public function connect() {
        return "Database connection";
    }
}

class PasswordReminder {
    private $dbConnection;

    public function __construct(DBConnectionInterface $dbConnection) {
        $this->dbConnection = $dbConnection;
    }
}
According to the little snippet above, you can now see that both the high level and low level modules depend on abstraction.

Conclusion
Honestly, S.O.L.I.D might seem to be a handful at first, but with continuous usage and adherence to its guidelines, it becomes a part of you and your code which can easily be extended, modified, tested, and refactored without any problems.

Wednesday, 28 August 2019

Basics Spring Interview Questions and Answers

Q1) What is Spring Framework? What are some of the important features and advantages of Spring Framework?

Spring is one of the most widely used Java EE framework.
I like spring because it provides a lot of features and capabilities.
it has different modules for specific tasks such as Spring MVC , Spring JDBC , Spring Web, Spring AOP, Spring Security and Spring BOOT etc.
it can be used to achieve loose coupling between different components by implementing dependency injection and we can perform cross cutting tasks.

-------------------------------------------------------------------------

Lightweight and very highly used framework
Dependency Injection or Inversion of Control to write components that are independent of each other,
spring container takes care of wiring them together to achieve our work.
Spring IoC container manages Spring Bean life cycle and project specific configurations such as JNDI lookup.
Spring MVC framework can be used to create web applications as well as restful web services capable of returning XML as well as JSON response.
Support for transaction management, JDBC operations, File uploading, Exception Handling etc with very little configurations, either by using annotations or by spring bean configuration file.

Some of the advantages of using Spring Framework are:
-----------------------------------------------------

Reducing direct dependencies between different components of the application,
usually Spring IoC container is responsible for initializing resources or beans and inject them as dependencies.

Writing unit test cases are easy in Spring framework because our business logic doesn’t have direct dependencies with actual resource implementation classes. We can easily write a test configuration and inject our mock beans for testing purposes.

Reduces the amount of boiler-plate code, such as initializing objects, open/close resources.
I like JdbcTemplate class a lot because it helps us in removing all the boiler-plate code that comes with JDBC programming.

Spring framework is divided into several modules, it helps us in keeping our application lightweight. For example, if we don’t need Spring transaction management features, we don’t need to add that dependency in our project.

Spring framework support most of the Java EE features and even much more. It’s always on top of the new technologies, for example there is a Spring project for Android to help us write better code for native android applications. This makes spring framework a complete package and we don’t need to look after different framework for different requirements.




Q2) What do you understand by Dependency Injection or Inversion of control ?



How do we implement DI in Spring Framework?
What are the benefits of using Spring Tool Suite?
Name some of the important Spring Modules?
What do you understand by Aspect Oriented Programming?
What is Aspect, Advice, Pointcut, JointPoint and Advice Arguments in AOP?
What is the difference between Spring AOP and AspectJ AOP?
What is Spring IoC Container?
What is a Spring Bean?
What is the importance of Spring bean configuration file?
What are different ways to configure a class as Spring Bean?
What are different scopes of Spring Bean?
What is Spring Bean life cycle?
How to get ServletContext and ServletConfig object in a Spring Bean?
What is Bean wiring and @Autowired annotation?
What are different types of Spring Bean autowiring?
Does Spring Bean provide thread safety?
What is a Controller in Spring MVC?
What’s the difference between @Component, @Repository & @Service annotations in Spring?
What is DispatcherServlet and ContextLoaderListener?
What is ViewResolver in Spring?
What is a MultipartResolver and when its used?
How to handle exceptions in Spring MVC Framework?
How to create ApplicationContext in a Java Program?
Can we have multiple Spring configuration files?
What is ContextLoaderListener?
What are the minimum configurations needed to create Spring MVC application?
How would you relate Spring MVC Framework to MVC architecture?
How to achieve localization in Spring MVC applications?
How can we use Spring to create Restful Web Service returning JSON response?
What are some of the important Spring annotations you have used?
Can we send an Object as the response of Controller handler method?
How to upload file in Spring MVC Application?
How to validate form data in Spring Web MVC Framework?
What is Spring MVC Interceptor and how to use it?
What is Spring JdbcTemplate class and how to use it?
How to use Tomcat JNDI DataSource in Spring Web Application?
How would you achieve Transaction Management in Spring?
What is Spring DAO?
How to integrate Spring and Hibernate Frameworks?
What is Spring Security?
How to inject a java.util.Properties into a Spring Bean?
Name some of the design patterns used in Spring Framework?
What are some of the best practices for Spring Framework?

Basics Java Script questions need to know

Q1) What is JavaScript?

Ans: JavaScript is a scripting language most often used for client-side web development. there are two ways which are normally utilized by developers.

JavaScript is a lightweight, translated programming language with object-oriented capacities that allow you to incorporate intelligence with generally static HTML pages.

i) <script type="text/javascript"> tag inside the <head> element.

<head>
<title>Java script </title>
<script language="JavaScript" type="text/javascript">
  var name = "kumar "
  alert(name);
</script>
</head>

ii) If your script code is very large, then you can make a JavaScript file and include its way in the following way:

<head>
<title>javascript</title>
<script type="text/javascript" src="script.js"></script>
</head>


Q2) What is the difference between an alert box and a confirmation box?

Alert box shows one and only button which is the OK button while the Confirm box shows two buttons namely OK and cancel.

Q3) What is a prompt box?

A prompt box allows the user to enter input by providing a text box.

Q4) what are the datatype in JavaScript?

  String,Number,Boolean,Array,Object,Null,Undefined.

Q5) Javascript case sensitive?

 Yes!, absolutely Javascript is case sensitive

 i) The function getElementById is not the same as getElementbyID
 ii) var NAME=”kumar”; is not the same var name=”rangari”;

Q6) what is the difference between ‘==’ and ‘===’?

‘==’ checks for value equality,
Equality using "=="

var num = 0;
var obj = new String("0");
var str = "0";
var b = false;
print(num == num); // true
print(obj == obj); // true
print(str == str); // true
print(num == obj); // true
print(num == str); // true

‘===’ checks for both type and value.
Strict equality using ===

var num = 0;
var obj = new String("0");
var str = "0";
var b = false;
print(num === num); // true
print(obj === obj); // true
print(str === str); // true
print(num === obj); // false
print(num === str); // false


Q7) What is negative infinity?

It’s a number in JavaScript, derived by dividing negative number by zero.

Q8) Can you explain what isNaN function does?

isNaN function will check an argument and return TRUE if the argument does not seem to be a number.

Return true if the argument is not a number.

Q9) what is the different between write() vs writeln()?

i) document.write();
basic JavaScript commands is document.write. This simply prints the specified text to the page. To print message truly, enter the text in single quote marks inside parentheses like so:

document.write('Hello World!');
The code above will cause the phrase "Hello World!" to appear on the page.

You can also use document.write to print variables. Enter the variable name without quotes, like so:

var mytext = "Hello again";
document.write(mytext);

Note that if quote marks are placed around the variable name, the variable name itself will be printed (instead of the variable value). You can also combine variable values and text strings by using the + sign:

var colour1 = "blue";
var colour2 = "red";
document.write('<p>colour1: ' + colour1 + '<br>colour2: ' + colour2 + '</p>');

Notice the way the variable names are used literally as well as for passing the values. This will print the following:

colour1: blue
colour2: red
Remember, text inside quotes will be printed literally, text with no quotes is assumed to be a variable.

write() vs writeln()
--------------------

write():

Note that write() does NOT add a new line after each statementex: Hello World! Have a nice day!

writeln()

Note that writeln() add a new line after each statement:Hello World!

Have a nice day!


Q10) What are the  boolean operators does  JavaScript support?

&& – the “and” operator.
|| – the “or” operator.
 ! – the “not” operator.


Q11) How to create arrays in JavaScript?

Ans:There are two ways to create array in JavaScript like other languages:

  a) The first way to create array:  By Declare Array:

var names = new Array();

Add Elements in Array:-
names[0] = "jehanabad";
names[1] = "nishant";
names[2] = "kumar";

  b) This is the second way:

var names = new Array("jehanabad", "nishant", "kumar");


Q12) What is the difference between undefined and null?

The value of a variable with no value is undefined (i.e., it has not been initialized).

Var =a;
a is undefined

Variables can be emptied by setting their value to null.

Var a =null;
a is null


Q13) What is the HTML DOM?

Once a site page loads, your browser generates something called a DOM,, or Document Object Model, of the page. The DOM acts as programming interface for HTML, which defines HTML properties, events, and methods. It likewise refers to HTML elements as objects..

JavaScript relies on this DOM to alter the elements and attributes of a page, and create the dynamic websites

demonstrating the hierarchy of HTML DOM objects:

<document>
 
  <html>

     <head>
         <title> </title>
     </head>

     <body>
       -----
     </body>

  </html>

</document>


Q14) What are global variables? How are they declared? What are the problems with using globals?


Global variables are available throughout your code: that is, the variables have no scope.

Local variables scope, then again, is restricted to where it is declared (like within a function).

The var keyword is used to declare  a local  variable or object, while discarding the var keywordcreates a global variable.

Most JavaScript developers avoid globals. One reason why is they’re averse to naming conflicts between local and globals,

Also, code that depends on globals can be difficult to maintain and test.

local variable
var localVariable = "local"

global variable
globalVariable = "global"


Q15) Difference between window.onload and onDocumentReady?

The onload event does not fire until every last piece of the page is loaded, this includes css and images, which means there’s a huge delay before any code is executed.

That isnt what we want. We just want to wait until the DOM is loaded and is able to be manipulated. onDocumentReady allows the programmer to do that.


Q16) What do mean by NULL in JavaScript?

The NULL value is used to represent no value or no object. It implies no object or null string, no valid boolean value, no number and no array object.


Q17) What are Javascript closures?When would you use them?

closure is the local variables for a function – kept alive after the function has returned,
closure is a stack-frame which is not deallocated when the function returns.
closure takes place when a function creates an environment that binds local variables to it in such a way that they are kept alive after the function has returned.
closure is a special kind of object that combines two things: a function, and any local variables that were in-scope at the time that the closure was created.

function sayHello2(name) {
var text = ‘Hello ‘ + name; // local variable
var sayAlert = function() { alert(text); }
return sayAlert;
}

Closures reduce the need to pass state around the application. The inner function has accessto the variables in the external function so there is no need to  to store the information some place that the inner function can get it.

This is important when the inner function will be called after the function has exited. The most common example of this is when the inner function is being used to handle an event. In this case you get no control over the arguments that are passed to the function so using a closure to keep track of state can be very convenient.


Q18) How to determine the state of a checkbox using Javascript?

var checkedP = window.document.getElementById("myCheckBox").checked;

Q19) What does "7"+5+6 evaluate to?

Ans: Since 7 is a string, everything is a string, so the result is 756.

Q20) What is “this” keyword?

Ans. It refers to the current object.

JSP interview questions and answers

Q1. What is JSP and why do we need it? JSP stands for JavaServer Pages. JSP is java server side technology to create dynamic web pages. J...