Thursday, June 23, 2016

RESTful WebService using Jersey, AngularJS, MySQL (Small application to maintain users - Usermaintenance)

RESTful WebService using Jersey, AngularJS, MySQL

In this application, we will use AngularJS at the front-end and MySQL at the back-end. Moreover, Angular will communicate with database to store and fetch information using RESTful webservices. Obviously, we would be using JSON format for transfer of data from angular to rest and vice versa.




Following some steps to achieve this task and our output will be as below:




a) Libraries required:

jersey-server 1.9
mysql-connector-java 5.1.10
(com.google.code.gson) gson 2.2.1


b) Create a property file named as configuration.properties and write following lines:

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql:///um
jdbc.user = root 


c) Create a package named as com.gag and Create a class named as                               ReadFromPropertiesFile.java and write following lines in it:


package com.gag;

import java.io.InputStream;
import java.util.Properties;

public class ReadFromPropertiesFile {

Properties properties = null;

ReadFromPropertiesFile() {
try {
InputStream is = ReadFromPropertiesFile.class.getClassLoader()
.getResourceAsStream("configuration.properties");
properties = new Properties();
properties.load(is);
} catch (Exception e) {
System.out.println("aaaa " + e);
}
}

public String getURL() {
try {
return properties.getProperty("jdbc.url");
} catch (Exception e) {
System.out.println("getURL:" + e);
}
return "";
}

}


d) Create a class named as ConnectDB.java and write following lines in it:

package com.gag;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.logging.Logger;

public class ConnectDB {

static ReadFromPropertiesFile obj = new ReadFromPropertiesFile();

public static Connection connect() {

Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(obj.getURL(), "root", "");
} catch (Exception e) {
System.out.println("ConnectDB:  " + e);
Logger.getLogger(ConnectDB.class + "");
}
return conn;
}
}


e) Create a POJO class named as Customer.java and write following lines in it:

package com.gag;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

private int id;
private String name, email;

public int getId() {
return id;

}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

@Override
public String toString() {
return "{\"id\":\"" + id + "\",\"name\":\"" + name + "\",\"email\":\""
+ email + "\"}";
}
}

f) Create a class CustomerServices.java and write following lines in it:

package com.gag;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class CustomerServices {

public List<Customer> getAllCustomers() {
List<Customer> lst = new ArrayList();
try {
Connection conn = ConnectDB.connect();
PreparedStatement pstmt = conn
.prepareStatement("select * from customer");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
Customer obj = new Customer();
obj.setId(rs.getInt("id"));
obj.setName(rs.getString("name"));
obj.setEmail(rs.getString("email"));
lst.add(obj);
}
} catch (Exception e) {
System.out.println(e);
}
return lst;
}

public String addCustomer(Customer obj) {
try {
Connection conn = ConnectDB.connect();
PreparedStatement pstmt = conn
.prepareStatement("insert into customer values(?,?,?)");
pstmt.setInt(1, obj.getId());
pstmt.setString(2, obj.getName());
pstmt.setString(3, obj.getEmail());
int i = pstmt.executeUpdate();
if (i > 0) {
return "{\"msg\":\"Customer Created\"}";
}
} catch (Exception e) {
System.out.println("addCustomer: " + e);
}
return "{\"msg\":\"Failed to  Create Customer\"}";
}

public String updateCustomer(Customer obj) {
try {
Connection conn = ConnectDB.connect();
PreparedStatement pstmt = conn
.prepareStatement("update customer set name=?,email = ? where id = ?");
pstmt.setString(1, obj.getName());
pstmt.setString(2, obj.getEmail());
pstmt.setInt(3, obj.getId());
int i = pstmt.executeUpdate();
if (i > 0) {
return "{\"msg\":\"Customer Updated\"}";
}
} catch (Exception e) {
System.out.println("updateCustomer: " + e);
}
return "Failed to  Update Customer";
}

public String delCustomer(int id) {
try {
Connection conn = ConnectDB.connect();
PreparedStatement pstmt = conn
.prepareStatement("delete from customer where id = ?");
pstmt.setInt(1, id);
int i = pstmt.executeUpdate();
if (i > 0) {
return "{\"msg\":\"Customer Deleted\"}";
}
} catch (Exception e) {
System.out.println("delCustomer: " + e);
}
return "Failed to  Delete Customer";
}
}


g) Create a class named as CustomerAPI.java in which we will write our RESTful  webservice code:

package com.gag;

import java.util.List;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.google.gson.Gson;

@Path("/customer")
public class CustomerAPI {

@GET
@Path("/getCustomers")
@Produces("application/json")
public String feed() {
String feeds = null;
try {
List<Customer> lstCustomers = null;
CustomerServices customerServices = new CustomerServices();
lstCustomers = customerServices.getAllCustomers();
Gson gson = new Gson();
System.out.println(gson.toJson(lstCustomers));
feeds = gson.toJson(lstCustomers);
} catch (Exception e) {
System.out.println("Exception Error"); // Console
}
return feeds;
}

@POST
@Path("/addCustomer")
@Produces(MediaType.APPLICATION_JSON)
public Response createCustomer(Customer customer) {
System.out.println();
String result = "";
try {
CustomerServices customerServices = new CustomerServices();
result = customerServices.addCustomer(customer);
} catch (Exception e) {
System.out.println("Exception Error  " + e); // Console
}
return Response.status(200).entity(result).build();
}

@PUT
@Path("/updateCustomer/id/{id}/name/{name}/email/{email}")
public String updateCustomer(@PathParam("id") int id,
@PathParam("name") String name, @PathParam("email") String email) {
String result = "";
try {
CustomerServices customerServices = new CustomerServices();
Customer obj = new Customer();
obj.setId(id);
obj.setName(name);
obj.setEmail(email);
result = customerServices.updateCustomer(obj);
} catch (Exception e) {
System.out.println("Exception Error  " + e); // Console
}
return result;
}

@DELETE
@Path("/delCustomer/id/{id}")
public String delCustomer(@PathParam("id") int id) {
String result = "";
try {
CustomerServices customerServices = new CustomerServices();
result = customerServices.delCustomer(id);
} catch (Exception e) {
System.out.println("Exception Error  " + e); // Console
}
return result;
}
}

h) Create a xml file named as web.xml and write following code in it:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>jersey-servlet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.gag</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>jersey-servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>

</web-app>


i) In the last, to use this API, we need a client, so we will use angularjs along with jquery and html. Following is the code in index.jsp file or any html file you can create:

<html>
<head>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script>
<script type="text/javascript">
var myapp = angular.module("myApp", []);
myapp
.controller(
"umcontroller",
function($scope, $http) {
$scope.employees = [];
$scope.form = {
id : "",
name : "",
email : ""
};
_refreshPageData();
$scope.check = "";
$scope.submitCustomer = function() {
if ($scope.form.check == "check") {
method = "PUT";
url = 'http://localhost:8088/CustomerJerseyRestAPI/rest/customer/updateCustomer/id/'
+ $scope.form.id
+ "/name/"
+ $scope.form.name
+ "/email/"
+ $scope.form.email;
} else {
method = "POST";
url = 'http://localhost:8088/CustomerJerseyRestAPI/rest/customer/addCustomer';
}
$http({
method : method,
url : url,
data : angular.toJson($scope.form),
headers : {
'Content-Type' : 'application/json'
}
}).then(function successCallback(response) {
$scope.form.check = "";
_success(response);
}, function errorCallback(response) {
alert("ERROE:: " + response);
});
};
$scope.removeEmployee = function(employee) {
$http(
{
method : 'DELETE',
url : 'http://localhost:8088/CustomerJerseyRestAPI/rest/customer/delCustomer/id/'
+ employee.id
}).then(function successCallback(response) {
_success(response);
}, function errorCallback(response) {
alert("ERROE:: " + response);
});
};

$scope.editEmployee = function(employee) {
$scope.form.name = employee.name;
$scope.form.email = employee.email;
$scope.form.id = employee.id;
$scope.form.check = "check";
};
function _refreshPageData() {
$http(
{
method : 'GET',
url : 'http://localhost:8088/CustomerJerseyRestAPI/rest/customer/getCustomers/'
}).then(function successCallback(response) {
$scope.employees = response.data;
}, function errorCallback(response) {
console.log(response.statusText);
});
}

function _success(response) {
_refreshPageData();
_clearForm()
}

function _error(response) {
console.log(response.statusText);
}
function _clearForm() {
$scope.form.name = "";
$scope.form.email = "";
$scope.form.id = "";
}

$scope.clearForm = function() {
_clearForm();
}
});
</script>
</head>
<body ng-app="myApp" ng-controller="umcontroller">

<div class="generic-container" ng-controller="umcontroller">
<div class="panel panel-default">
<div class="panel-heading">
<span class="lead">Usermaintenance</span>
</div>
<div class="formcontainer">
<form ng-submit="submitCustomer()">
<div class="row">
<input type="hidden" ng-model="form.id" /> <input type="hidden"
ng-model="form.check" />
<div class="form-group col-md-12">
<label class="col-md-2 control-lable" for="id">Id</label>
<div class="col-md-7">
<input type="text" ng-model="form.id" name="id"
class="username form-control input-sm"
placeholder="Enter your Id" required ng-minlength="1" />

</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="col-md-2 control-lable" for="name">Name</label>
<div class="col-md-7">
<input type="text" ng-model="form.name" id="name"
class="username form-control input-sm"
placeholder="Enter your name" required ng-minlength="3" />

</div>
</div>
</div>


<div class="row">
<div class="form-group col-md-12">
<label class="col-md-2 control-lable" for="email">Email</label>
<div class="col-md-7">
<input type="text" ng-model="form.email" id="email" name="email"
class="form-control input-sm"
placeholder="Enter your Email [This field is validation free]" />
</div>
</div>
</div>



<div class="row">
<div class="form-actions floatRight">
<input type="submit" value="{{!form.check ? 'Add' : 'Update'}}"
class="btn-sm" ng-disabled="myForm.$invalid">
<button type="button" ng-click="clearForm()"
class="btn-sm">Reset Form</button>
</div>
</div>

</form>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<span class="lead">Users</span>
</div>
<div class="tablecontainer">
<table class="table table-hover">
<thead>
<tr>
<th>ID.</th>
<th>Name</th>
<th>Email</th>
<th width="20%"></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="u in employees">
<td><span ng-bind="u.id"></span></td>
<td><span ng-bind="u.name"></span></td>
<td><span ng-bind="u.email"></span></td>
<td>
<button type="button" ng-click="editEmployee(u)"
class="btn btn-success custom-width">Edit</button>
<button type="button" ng-click="removeEmployee(u)"
class="btn btn-danger custom-width">Remove</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>

</body>
</html>

Wednesday, June 22, 2016

Spring MVC Multiple Controller Example

Spring MVC Multiple Controller Example


a) Libraries to be used:

spring-core - 4.1.6
spring-web - 4.1.6
spring-webmvc - 4.1.6
javax.servlet-api - 3.1.0
jstl - 1.2


b) Create a xml file named as web.xml in WEB-INF folder and write the following code in it:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>

</web-app>


c) Create a xml file named as spring-servlet.xml in WEB-INF folder and write following code in it:


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.gag.controller" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>  


d) Create an index.jsp and do following code in it:

<html>
<body>
<h2>Hello World!</h2>
<a href="hello.html">Hello Controller</a>
<a href="welcome.html">Welcome Controller</a>
</body>
</html>


e) Create a folder named jsp in WEB-INF folder and Create following JSP pages in this folder:
data.jsp 

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Hi you have arrived on Hello COntroller.....</h1>

</body>
</html>


and gagandeep.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Hii..you have arrived on Welcome Controller....</h1>

</body>
</html>


e) Create a package named as com.gag.controller and within this package Create following classes in it:

HelloController.java


package com.gag.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloController {
@RequestMapping("/hello")
public ModelAndView helloWorld() {
String message = "HELLO CONTROLLER";
System.out.println("Heloooo..........");
return new ModelAndView("data", "message", message);
}
}


WelcomeController.java


package com.gag.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class WelcomeController {
@RequestMapping("/welcome")
public ModelAndView helloWorld() {
String message = "WELCOME CONTROLLER";
System.out.println("Welcome.........");
return new ModelAndView("gagandeep", "message", message);
}
}



Tuesday, June 21, 2016

Spring MVC Hello World

Spring MVC HelloWorld Example

a) Libraries required:

spring-context - 4.1.6
spring-aop - 4.1.6
spring-webmvc - 4.1.6
spring-web 4.1.6
jstl - 1.2


b) Create web.xml file in WEB-INF folder and write following lines of code:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>


c) Create a xml file named as spring-servlet.xml inside WEB-INF folder and write following lines of code:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.gag.controller" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>



d) Create a package named as com.gag.controller (or any other name) and inside this package Create a new class named as HelloWorldController and write following code:

package com.gag.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloWorldController {

@RequestMapping("/hello")
public ModelAndView helloWorld() {
String message = "HELLO SPRING MVC HOW R U";
System.out.println("Here.............");
return new ModelAndView("hellopage", "message", message);
}
}


e) Create a folder inside WEB-INF named as jsp and inside this folder Create a new JSP named as hellopage.jsp and write following code in it:


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@page isELIgnored="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>${message}
</body>
</html>

Tuesday, April 23, 2013

Servlet Question Answers


                    Certain Servlets interview Q/As

Q1. What is a servlet ?
Servlets are modules that extend request/response-oriented servers,such as Java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company’s order database. Servlets are to servers what applets are to browsers. Unlike applets, however, servlets have no graphical user interface.

Q2. Whats the advantages using servlets over using CGI?
Servlets provide a way to generate dynamic documents that is both easier to write and faster to run. Servlets also address the problem of doing server-side programming with platform-specific APIs: they are developed with the Java Servlet API, a standard Java extension.

Q3. What are the general advantages and selling points of Servlets?
A servlet can handle multiple requests concurrently, and synchronize requests. This allows servlets to support systems such as online real-time conferencing. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers that mirror the same content, and to partition a single logical service over several servers, according to task type or organizational boundaries.

Q4. Which package provides interfaces and classes for writing servlets? 
javax

Q5. What’s the Servlet Interface?
The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or, more commonly, by extending a class that implements it such as HttpServlet.Servlets > Generic Servlet > HttpServlet > MyServlet. The Servlet interface declares, but does not implement, methods that manage the servlet and its communications with clients. Servlet writers provide some or all of these methods when developing a servlet.

Q6. When a servlet accepts a call from a client, it receives two objects. What are they?
ServletRequest (which encapsulates the communication from the client to the server) and ServletResponse (which encapsulates the communication from the servlet back to the client). ServletRequest and ServletResponse are interfaces defined inside javax.servlet package.

Q7. What information does ServletRequest allow access to?
Information such as the names of the parameters passed in by the client, the protocol (scheme) being used by the client, and the names of the remote host that made the request and the server that received it. Also the input stream, as ServletInputStream.Servlets use the input stream to get data from clients that use application protocols such as the HTTP POST and GET methods.

Q8. What type of constraints can ServletResponse interface set on the client?
It can set the content length and MIME type of the reply. It also provides an output stream, ServletOutputStream and a Writer through which the servlet can send the reply data.

Q9. Explain servlet lifecycle?
Each servlet has the same life cycle: first, the server loads and initializes the servlet (init()), then the servlet handles zero or more client requests (service()), after that the server removes the servlet (destroy()). Worth noting that the last step on some servers is done when they shut down.

Q10. How does HTTP Servlet handle client requests?
An HTTP Servlet handles client requests through its service method. The service method supports standard HTTP client requests by dispatching each request to a method designed to handle that request.

Monday, April 22, 2013

JSP Interview Questions


Certain JSP interview question answers...


Q1. What is a JSP and what is it used for?

Java Server Pages (JSP) is a platform independent presentation layer technology that comes with SUN s J2EE platform. JSPs are normal HTML pages with Java code pieces embedded in them. JSP pages are saved to *.jsp files. A JSP compiler is used in the background to generate a Servlet from the JSP page.



Q2. What is difference between custom JSP tags and beans? 

Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files.


To use custom JSP tags, you need to define three separate components:

1. the tag handler class that defines the tag\'s behavior
2. the tag library descriptor file that maps the XML element names to the tag implementations 
3. the JSP file that uses the tag library 


When the first two components are done, you can use the tag by using taglib directive: 


<%@ taglib uri="xxx.tld" prefix="..." %>


Then you are ready to use the tags you defined.

Let's say the tag prefix is test: 
MyJSPTag or JavaBeans are Java utility classes you defined. Beans have a standard format for Java classes. You use tags to declare a bean and use to set value of the bean class and use to get value of the bean class. 
<%=identifier.getclassField() %>
Custom tags and beans accomplish the same goals, encapsulating complex behavior into simple and accessible forms.

There are several differences:
a) Custom tags can manipulate JSP content; beans cannot.
b) Complex operations can be reduced to a significantly simpler form with custom tags than with beans. c) Custom tags require quite a bit more work to set up than do beans. 
d) Custom tags usually define relatively self-contained behavior, whereas beans are often defined in   one servlet and used in a different servlet or JSP page.
e) Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions.



Q3. What are the two kinds of comments in JSP and what's the difference between them ?

1. JSP Comment

    Example:     <%-- JSP Comment --%>
2. HTML Comment
    Example:     <!-- HTML Comment -->

Q4. What is JSP technology?

Java Server Page is a standard Java extension that is defined on top of the servlet Extensions. The goal of JSP is the simplified creation and management of dynamic Web pages. JSPs are secure, platform-independent, and best of all, make use of Java as a server-side scripting language.

Q5. How can a servlet refresh automatically if some new data has entered the database? 

You can use a client-side Refresh or Server Push.



Q6. How many JSP scripting elements and what are they? 

There are three scripting language elements:
1. declarations 
2. scriptlets 
3. expressions


Q7. Why are JSP pages the preferred API for creating a web-based client program? 

Because no plug-ins or security policy files are needed on the client systems(applet does). Also, JSP pages enable cleaner and more module application design because they provide a way to separate applications programming from web page design. This means personnel involved in web page design do not need to understand Java programming language syntax to do their jobs.


Q8. Is JSP technology extensible? 

YES. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.


Q9. What are the implicit objects? 

Implicit objects are objects that are created by the web container and contain information related to a particular request, page, or application. 

They are:
1. request 
2. response 

3. exception
4. pageContext

5. out  
6. session 
7. application

8. config 
9. page



Q10. Can we use the constructor, instead of init(), to initialize servlet? 

Yes , of course you can use the constructor instead of init(). There’s nothing to stop you. But you shouldn’t. The original reason for init() was that ancient versions of Java couldn’t dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won’t have access to a ServletConfig or ServletContext.


Q11. What is JSP page? 

A JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format such as HTML, SVG, WML, and XML, and JSP elements, which construct dynamic content.




Sunday, January 20, 2013

Java Today: Servlets

Java Today: Servlets:                 Basic Information about Servlets in Java: 1. Servlets are server side components that provide a powerful mechanism...

Interview Questions - Servlets and latest version







Hi Friends...!!..

Check out the new version of Java7. You may click the link below

http://www.java.com/en/download/index.jsp

Some brief information about Java:


1. Java is a general-purpose, concurrent, class-based, object-oriented computer programming language that is specifically designed to have as few implementation dependencies as possible. It is intended to let application developers "write once, run anywhere" meaning that code that runs on one platform does not need to be recompiled to run on another.

2.  Java applications are typically compiled to bytecode (class file) that can run on any JVM regardless of computer architecture. Java is, as of 2012, one of the most popular programming languages in use, particularly for client-server web applications, with a reported 15 million users. Java was originally developed by James Gosling at Sun Microsystems (which has since merged into Oracle Corporation) and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C++, but it has fewer low-level facilities than either of them.

Some questions about Servlets:
Technical Interviewers ask mostly from this topic just to check your basic skills.

Q:
What is the difference between HttpServlet and GenericServlet?
A:
A GenericServlet has a service() method aimed to handle requests. 
HttpServlet extends GenericServlet and adds support for doGet(), 
doPost(), doHead() methods (HTTP 1.0) plus doPut(), doOptions(), 
doDelete(), doTrace() methods (HTTP). 
Both these classes are abstract.




Q:
What is the difference between ServletContext and ServletConfig?
A:
ServletContext: 
Defines a set of methods that a servlet uses to 
communicate with its servlet container, for example, to get the 
MIME type of a file, dispatch requests, or write to a log file.
The ServletContext object is contained within the ServletConfig object,
 which the Web server provides the servlet when the servlet is initialized 

ServletConfig: 
The object created after a servlet is instantiated and 
its default constructor is read. It is created to pass initialization information
 to the servlet.