More concepts in Servlet

Hello viewers, today I got to know few more things in servlet like heirarchy through which HttpServlet extends, fetching data through request parameter in servlet, printing HTML content in servlet page, RequestDispatcher for including and forwarding the request to other resources. I am gonna discuss about them one by one.

Heirarchy:

As we saw, whenever we create a servlet class, it extends HttpServlet. Now, I will tell the basic heirarchy from which HttpServlet extends.

  • First, we have an interface named Servlet which has declaration of methods init, service, destroy.
  • GenericServlet class implements this interface Servlet. In GenericServlet there is definition of methods init, service, destroy.
  • HttpServlet class extends GenericServlet. HttpServlet class provides the methods such as doGet, doPost, doTrace, doPut etc.
  • Finally our servlet class extends HttpServlet to get access to all the important methods for servlet functioning.

Note: doPost method is called when request method is post. doGet method is called when request method is get. service method performs the task of both. It can receive the get as well as post request.


Getting data in servlet:

In service method, we get have two parameters- reference of HttpServletRequest and reference of HttpServletResponse. Using request reference we can get the data which has been sent along with request for example form data in HTML page after submission. Let’s see how you receive that.

index.html-

<!DOCTYPE html>
<html >
<head><title>Login Form</title></head>
<body>
<h2>Login to your account</h2>
<form action="Login" method="post">
<input type="text" placeholder="Email" name="txtEmail"/>
<input type="password" placeholder="Password" name="txtPassword"/>
<button type="submit" value="Login">Login</button>
</form>

</body>
</html>

Then in servlet class, you created, write the following code where you will use request.getParameter to get the input values of form elements entered by user.

@WebServlet("/Login")
public class ServletClass extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String email = request.getParameter("txtEmail");
		String password = request.getParameter("txtPassword");
                //rest of code
            }
}

Display HTML content in servlet:

For displaying HTML content in servlet page, PrintWriter is used to print text data to a character stream. request.getWriter returns the PrintWriter object. Now, you can simply write the text to be printed using print method.

PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>
<h3>You are successfully logged in</h3>
");
out.println("</body></html>");

RequestDispatcher:

RequestDipatcher is an interface which plays very important role in dispatching the request to other servlet, jsp or html page. Here, we can use two methods for performing two much required functions. They are:

  1. include: This method includes the content of the resource file which we have specified. Whatever print statements are written in current servlet will be erased as we are including some other resource file.
  2. forward: This method will forward the request to the specified resource and include  the content of that resource file without affecting the content of current(calling) servlet.

include:

RequestDispatcher dispatcher = request.getRequestDispatcher("index.html");
dispatcher.include(request, response);

forward:

RequestDispatcher dispatcher = request.getRequestDispatcher("Home");
dispatcher.forward(request, response);

Servlets in Java (Introduction)

Today, I came to know about servlets which is a technology to create web applications. Before starting with what things I came to know today, I would like to mention come concepts about server.

So, what’s basically a server?

Server is a computer software(not a hardware, I had this misconception) that runs on powerful machines which is responsible for providing services or you can say handling the request of client(computer program requesting for services from server). We have mainly two types of server- Application and Web server.

  • Web server: Web server is an internet server for handling HTTP request and responding to them(HTTP response). This kind of server can send response as static HTML page. It doesn’t have capability to generate dynamic HTML pages. Examples of web server- Apache Tomcat, Apache Web server, nginx, IIS web server.
  • Application server:  Application server is superset of web server having plenty of other features such as Connection Pooling, Object Pooling, Transaction Support, Messaging services. When client requests for dynamic content(having database connectivity) then application server comes into picture. Examples of application server- JBoss, WildFly, Glassfish.

If one is interested for knowing the differences between them, go through the links.

http://www.javaworld.com/article/2077354/learn-java/app-server-web-server-what-s-the-difference.html

https://stackoverflow.com/a/936257/6499635

Servlet:

Servlet is typically a java program which manages the code on server. It’s the technology for creating web applications typically generating the dynamic web pages.

Install Apache tomcat in eclipse:

  1. Download server. I am using apache tomcat(web server). Download it from here.
  2. Extract the download zip folder. It can be renamed.
  3. Come to eclipse. Switch to Java EE perspective.
  4. Go to Windows -> Show view -> Servers.
  5. Then in the servers view, right click and choose New -> server.
  6. In dialog box, expand Apache and choose the Apache tomcat server from the list below. Make sure, the downloaded version of Tomcat is same as the one you are choosing from the list here. Click Next.
  7. Browse for the directory where tomcat folder is located which you extracted few steps back. Click Next. Finish.
  8. You have successfully installed tomcat in eclipse.

Create a project:

  1. Click File -> New -> Dynamic Web Project.
  2. Name the project. Click Next.
  3. Again click Next.
  4. Then tick the Generate web.xml deployment descriptor checkbox.
  5. Click Finish.

Some important points:

  • Add the HTML, CSS, Javascript, images, JSP files in Web content directory.
  • Add the Servlet class, other java classes in Java resources directory.
  • Add the libraries in lib directory inside WEB-INF directory(this is private directory).
  • If you checked the checkbox for generating web.xml file, you can find that in WEB-INF directory by expanding that.

Create a servlet class:

  1. Go to Java Resources in project explorer for your respective project.
  2. Right click src.
  3. Click New -> Servlet. Name the Servlet class. Click Next.
  4. You can add new URL mappings for the servlet class. Click Next.
  5. Choose the methods you want to include in the servlet.
  6. Click Finish.

Now, you will get the class which extends HttpServlet. On top of class name, you will see the annotation @WebServlet. This will contain the list of URL mappings. These mapping names are used in the HTML forms(in action attribute) or wherever you want to execute the code of this servlet class.

JDBC(Java Database Connectivity)

Finally! entered into Advance Java concepts. So, the first one which I explored is JDBC which is nothing but set of APIs/ library/ framework which allows the java application to connect to the database. That connection is made and handled using JDBC drivers

We have 4 types of drivers available to us but their usage is requirement dependent. Preferably, Type 4 driver is used as it provides direct communication between java-based driver and vendor’s DB using socket. Different database community Oracle, MySQL, PostgreSQL, MongoDB etc. provide their specific drivers. I am using MySQL. I installed the driver specific to MySQL in following steps:

  1. Download MySQL Connector/J.
  2. Extract the file.
  3. Now, come to eclipse.
  4. Right click on project name.
  5. Choose Build ppath -> Configure Build path.
  6. Go to Libraries tab.
  7. Click “Add External JARs”
  8. Browse your system to find location of extracted folder.
  9. Open that, and choose mysql connector’s jar file.
  10. Click Apply.

Done with driver linking to project. There are basically 5 steps for java database connectivity:

  1. Load the driver
  2. Create the connection
  3. Write SQL statement
  4. Execute SQL statement
  5. Close the connection
  • Loading the driver:

We use following syntax to load the driver in java application


Class.fromName("com.mysql.jdbc.Driver")

forName() and Class are used to register driver class.

Note: Driver class name is different for different vendors. I have written for MySQL.

  • Creating connection

Connection needs to be established with particular DB.


String url = "jdbc:mysql://localhost/dbName";

Connection conn = DriverManager.getConnection(url,username,password);

In url, jdbc is API, mysql is database we are using, localhost is server name, dbName is name pd database we want to connect to.

  • Write SQL statement

Time to write the query to database. Statement interface(java.sql) allows to execute query with database.


String sql = "Select * from Student";

Statement stmt = conn.createStatement();

  • Execute the statement


stmt.executeQuery();

  • Close the connection


conn.close();

Let’s consider a table “Student” having attributes: roll(int) and name(varchar). This table is used for giving examples for coming topics in this post.


Prepared Statements

It is used to eliminate concatenation of strings in case of insert query primarily. If we have large number of columns then using Statement interface is not efficient. We should rather use prepared statement.


String sql ="Insert into Student values(?,?)";

PreparedStatement pStmt = conn.prepareStatement(sql);

//setting rollnumber column

pStmt.setInt(1, 10);

//setting name column

pStmt.setString(2, "Shilpa");

pStmt.executeUpdate();

Note: executeQuery() is used for selecting(retrieving the data) and executeUpdate() is used for update, delete, insert operations.


Batch Processing

It is execution of multiple SQL queries. Needed for faster performance. They must follow ACID properties of transactions if required. Written as:


//important to set the auto commit 'off'

conn.setAutoCommit(false);

String sql1 = Insert into Student VALUES(12, "Radhika");

String sql2 = Insert into Student VALUES(13, "Sonia");

Statement s = conn.createStatement();

//creating batch of statements

s.addBatch(sql1);

s.addBatch(sql2);

s.executeBatch();

conn.commit();

 


Stored procedures:

Stored procedures are useful to execute some business logic. These are precompiled. We create stored procedures in routines tab of phpMyAdmin. We provide parameters(IN, OUT) and the definition of procedure. Coming to java code, how to call stored procedure?


Statement s = conn.createStatement();

String sql = "{call storedProcedureName(?,?)}";

CallableStatement cStmt = conn.prepareCall(sql);

//setting values for '?'

cStmt.setInt(1, 2);

cStmt.setString(2, "Soumya");

cStmt.execute();

Polymorphism

Today, we were taught about polymorphism which is an important concept in OOPS. I have studied this topic earlier also but today I gained much clarity on this topic.

So, what’s the basic definition of polymorphism? It says, Polymorphism is the ability of an object to take on many forms. There are two types of it:

  • Compile time polymorphism/ Static binding/ Early binding
  • Run time polymorphism/ Dynamic binding/ Late binding

Now, Compile time polymorphism: Compile time polymorphism is nothing but the method overloading in java. It can be thought of as redefining the methods in the same class but having unique signature. Signature is basically function declaration(return type, name of function, datatypes of parameters).

For unique signature, some rules are specified:

  1.  Number of inputs.
  2.  Types of input.
  3.  Sequence of input.

Some things need to be considered for method overloading:

  • Function name should be same.
  • Inputs should always be different.
  • Return type has no role to play.

Example-


class CompileTimePoly{
void func() {
System.out.println("This is empty func");
}
void func(int a) {
System.out.println("This has integer "+a);
}
void func(float a) {
System.out.println("This has a float "+a);
}
float func(int a, float b) {
System.out.println("int comes before float");
return 0;
}
float func(float a, int b) {
System.out.println("float comes before int");
return 0;
}
}

Run time polymorphism: It involves inheritance. There’s a IS-A relationship between classes. It’s basically method overriding, which is redefinition of methods of parent class in the child class.

Example-


class Parent{
void whoAmI() {
System.out.println("I am parent");
}
}
class Child extends Parent{
//redefinition of whoAmI() method of Parent class
void whoAmI() {
System.out.println("I am Child");
}
}
public class Overriding {
public static void main(String[] args) {
Parent p =new Child();
p.whoAmI();
}
}

 

A Basic introduction to Bean class, reference variables …

Today was the first day of ‘Cloud computing with android’ training. We were introduced to the basic concepts of POJO/ Bean/ Model, reference variable, single value container, multivalue container, where the objects are stored, garbage collector.

For making any software, the prime thing is to know what are the requirements. They are the objects which consists of all the requirements i.e. attributes. For example, we have Product object. It can consists of attributes such as name, price, weight of product.

Bean/ POJO/ Model: A class with attributes, constructors, getters and setters.

Example of Bean class:


package com.mitaly.bean;

public class Product {
//attributes
String name;
int price;
float weight;

//constructor
public Product(String name, int price, float weight){
this.name = name;
this.price = price;
this.weight = weight;
}

//getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public float getWeight() {
return weight;
}
public void setWeight(float weight) {
this.weight = weight;
}
}

Single value and Multi-value container: Those variables are called as single value container which consists of single value and those variables which can contain more than one value are known as multi-value container. For example,

int = 20; //single value container

int[] arr = {10,20,30,40} //multi-value container

Product p1 = new Product (‘Dairy milk’, 20,  10); //Multi-value container

Storage:

Storage of objects, variables and reference variables

In i = 10, ‘i’ is a normal variable. It can store ‘literals’. Literals are stored in a place known as ”Permanent Generation’. Suppose, we have another variable, int j = 20; in this case ‘j’ will contain value 20(which comes from Permanent Generation). There will be only single copy of ’20’ in Permanent Generation area irrespective of number of variables i,j,… which has value 20.

For multi-value containers like array and reference variables, the stack is going to contain the address of objects which are created in Heap area. So, objects don’t have any name. They are just created in Heap area. Just there starting  address is copied into respective reference variable in Stack.  Like, we have array ‘arr’ storing 5001 which is the address for array object created in heap.

We have studied above that ‘p1’ is a reference variable. The object to which it points consists of attributes and the methods.

Garbage Collector: In Java, garbage collector automatically deletes the unnecessary objects. We have two types of space:

  • Old space
  • Young space

Mark and sweep algorithm is used which marks the useless objects and move them to ‘Old Space’. ‘Young Space’ consists of new objects and variables.