JSP(Java Server Pages)

JSP is a technology used to create dynamic web pages. It is combination of HTML and JSP tags and has more functionalities over servlet. In servlet, it was difficult to include HTML content as we have to write out.print again and again. JSP solves that problem as it combines HTML and Java code in single page.

Lifecycle:

JSP exercises necessary overhead. Let’s see how.

jsplifecyclegif

Web container translates the .jsp file into servlet code(.java). After that the servlet gets compiled and .class file is generated. Then it is loaded by classloader and instance of servlet class is created by container. This initialized servlet can request now.


Tags in JSP:

  1. Scriplet- Scriplet tag allows to write java code inside . You can simple write servlet code within these tags. One great feature is that, JSP provides the access of objects such as out, request, response, session etc. implicity i.e. we need not create objects for those, they are already created and we can refer them anytime.
  2. Declaration- Declaration tags allow to declare attributes and methods. They are to be enclosed within .
  3. Expression- The code inside expression tags is written to output stream. It is equivalent to out.print. Code needs to be written inside .

Including a file in JSP:

In JSP we can also add another file’s content. I also told you about how to include file in Servlet using request dispatcher. In JSP it’s done by:

<%@include file="anyfile.html" %>

Exception handling:

We can either write a basic try catch block for handling the exceptions or we can include an error page in the file where exception may occur. We can make any page as error page to display error to user in an appropriate manner, by setting page directive attribute isErrorPage as true.

error.jsp-

<%@ page language="java" contentType="text/html; charset=UTF-8"     pageEncoding="UTF-8"%>
<%@ page isErrorPage="true" %>
<!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=UTF-8">
<title>My web page</title>
</head>
<body>
	Some exception has occured:
	<%=exception %>
</body>
</html>
 

index.jsp-

Add the error.jsp page in index.jsp page(where error might occur).


<%@ page language="java" contentType="text/html; charset=UTF-8"     pageEncoding="UTF-8"%>
<%@ page errorPage="error.jsp" %>
<!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=UTF-8">
<title>My web page</title>
</head>
<body>
<h2>Getting value at index 20</h2>
<%! int num[] = {10,20,30}; %>
  <%     out.print("Number at index 30: "+num[20]);   %>
</body>
</html>

Output-

Screenshot from 2017-06-26 15-19-51

Filter, Init param, Context param

I am today gonna discuss about Filters, static parameters which are init-param and context-param.

Filters:

Filters are the pluggable components where preprocessing and postprocessing is done. Preprocessing is executing the code before request is sent to servlet and postprocessing means executing the code after servlet code is finished and before the container sends the response back to client. Main tasks performed at preprocessing are decryption of message sent from client, data decompression, input validation etc. At postprocessing, tasks such as encryption of response message to be sent to client, data compression etc.

Example- I have created a login form validation(checks for empty fields) using filter. Filter will check for the input fields at it’s own end first. If any one of the field is empty, it will display a message and login form is shown again else request will be redirected to associated servlet.

index.html-


<!DOCTYPE html>
<html >
<head>
<title>Flat 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>

 

MyFilter.java-

doFilter is the method which has an important role in Filter. This is invoked every time by container when it has to apply filter to a resource. Container provides request and response object references to filter as argument. FilterChain is used to invoke the next filter in the chain.

@WebFilter("/MyFilter")
public class MyFilter implements Filter {

    public MyFilter() {

    }
    public void init(FilterConfig fConfig) throws ServletException {
		// initialize resources
     }

     public void destroy() {
	    // free the memory occupied by resources
     }

     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

		String email = request.getParameter("txtEmail");
		String password = request.getParameter("txtPassword");

		PrintWriter out = response.getWriter();
		if(email.trim().equals("") || password.trim().equals("")) {

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

			out.print("<center>Fill required field(s) and then proceed</center>");
		}else {
			chain.doFilter(request, response);
		}
	}
}

 

ServletClass.java-

Filter is applied to this class. When the empty fields are checked by filter, then request goes to this servlet class where we would write code for cross-checking the email and password(the fields in index.xml)  from database which is done by JDBC.

@WebServlet("/Login")
public class ServletClass extends HttpServlet {
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          /* here, write the code for vaidation of email and password using JDBC */
     }
}

 

web.xml-

We need to configure web.xml. Declare the filter here and do the filter-mapping. Make sure the url-mapping pattern in filter mapping is same as url-mapping of servlet class to which we want to link our filter.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>JavaEEProject</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

  <servlet>
    <servlet-name>Login</servlet-name>
    <servlet-class>ServletClass</servlet-class>
  </servlet>

  <filter>
    <filter-name>MyFilter</filter-name>
    <filter-class>MyFilter</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>MyFilter</filter-name>
    <url-pattern>/Login</url-pattern>
  </filter-mapping>

</web-app>

 


Init-param:

This is static parameter stored in web.xml file. It has param-name(key) and param-value. This type of parameter is declared within the scope of a servlet of filter and has private scope to them only.

<servlet>
     <display-name>ServletClass</display-name>
     <servlet-name>ServletClass</servlet-name>
     <init-param>
         <param-name>Greetings</param-name>
         <param-value>Hello</param-value>
     </init-param>
</servlet>

 

Access the parameter value in servlet using ServletConfig object which can be used to get configuration information from web.xml file.

ServletConfig config=getServletConfig();
String greetings=config.getInitParameter("Greetings");

 


Context-param:

This is similar to init-param. The only difference is it’s global scope. It can’t  be declared locally to any servlet or filter. Data is common to whole application. This is how global parameter is declared in web.xml.

<web-app>
    <context-param>
        <param-name>driver</param-name>
        <param-value>com.mysql.jdbc.Driver</param-value>
    </context-param>
</web-app>

 

Accessing the value in servlet.

ServletConfig config=getServletConfig();
String driver=config.getInitParameter("driver");

Session Tracking

Today, I gained insight into a very important concept of session tracking in servlet. Session Tracking is a way to maintain state (data) of a user to recognize the user. It becomes very important to persist the data of user while the user is navigating between different web pages.

We have four techniques to do the same:

  1. Cookies
  2. URL Rewriting
  3. Hidden Form Fields
  4. HttpSession
  • Cookies:

Cookies are key-value pairs consisting of user’s information or other important information that are stored in cache of browser. When client makes request to the same site, cookies stored during the last session will be transferred along the request, so that the site recognizes the user as an old user and displays the content specific to the user.

Note: The value can only be of String type in cookies.

ServletClass(where cookies are created)-


@WebServlet("/Login")
public class ServletClass extends HttpServlet {

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  /* Here, add the code to validate the user first and then fetch the data(email, age, salary) from database using JDBC */

		Cookie c1 = new Cookie("keyEmail", email);
		Cookie c2 = new Cookie("keyAge", String.valueOf(age));
		Cookie c3 = new Cookie("keySalary", String.valueOf(salary));
		response.addCookie(c1);
		response.addCookie(c2);
		response.addCookie(c3);

		PrintWriter out = response.getWriter();
		out.print("<a href='Home'>Go to Home</a>");
	}
}

ServletHome(where cookies are retrieved)-

@WebServlet({ "/ServletHome", "/Home" })
public class ServletHome extends HttpServlet {

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

                response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.print("<html><body>");
		out.print("
<h3>Welcome User</h3>
");

                //Getting the cookies
		Cookie[] cookieArr = request.getCookies();
		for(Cookie c: cookieArr)
			out.print(c.getName()+" : "+c.getValue());

		out.print("</body></html>");
		}
}

We have some drawbacks of using cookies-

  1. It may be the case that cookies are disabled on client’s machine.
  2. We can’t get access to  single cookie if we wish to access only one, rather we need to fetch the entire cookies array.
  • URL Rewriting:

URL Rewriting embeds the the data in the form of key-value pair in the URL itself (to whichever page we are redirecting). ‘?’ is added after file name in URL. key and value is separated by ‘=’. One parameter is separated from another by ‘&’.

If you will observe, it’s nothing but a GET request in which data is shown in URL.

ServletClass(where  URL is written)-

@WebServlet("/Login")
public class ServletClass extends HttpServlet {

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  /* Here, add the code to validate the user first and then fetch the data(email, age, salary) from database using JDBC */

		PrintWriter out = response.getWriter();
		out.print("<a href='Home?txtEmail="+email+"&txtAge=" 					+ age +"&txtSalary="+salary+"'>Go to Home page</a>");
	}
}

ServletHome(where data is fetched from URL)-

@WebServlet({ "/ServletHome", "/Home" })
public class ServletHome extends HttpServlet {

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              String email = request.getParameter("txtEmail");
	      int age = Integer.parseInt(request.getParameter("txtAge"));
	      int salary= Integer.parseInt(request.getParameter("txtSalary"));

              out.println("Email : "+email);
              out.println("Age : "+age);
	      out.println("Salary : "+salary);

	}
}

This method has drawbacks:

  1. Sensitive data can’t be transferred using this technique as data is visible in URL.
  2. Large amount of data has difficulty to be added in single URL.
  • Hidden Form Fields:

In this technique, we store the information in the hidden field and get it from another servlet. We keep the type of input element as ‘hidden’.

ServletClass(where  Hidden fields are created)-

@WebServlet("/Login")
public class ServletClass extends HttpServlet {

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  /* Here, add the code to validate the user first and then fetch the data(email, age, salary) from database using JDBC */
              PrintWriter out = response.getWriter();
              out.print("<html><body>");
			out.print("
<form action='Home' method='post'>");
			out.print("<input type='hidden' name='txtEmail' value='"+email+"'>");
			out.print("<input type='hidden' name='txtAge' value='"+age+"'>");
			out.print("<input type='hidden' name='txtSalary' value='"+salary+"'>");
			out.print("<input type='submit' value='Go to Home Page'>");
			out.print("</form>

</body></html>");
	}
}

ServletHome(where data is fetched from Hidden fields)-

@WebServlet({ "/ServletHome", "/Home" })
public class ServletHome extends HttpServlet {

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
             String email = request.getParameter("txtEmail");
	     int age = Integer.parseInt(request.getParameter("txtAge"));
              int salary = Integer.parseInt(request.getParameter("txtSalary"));

              out.println("Email : "+email);
              out.println("Age : "+age);
	      out.println("Salary : "+salary);

	}
}

It has drawaback

If we click View Page Source on that page, all the data will be revealed which we have kept hidden. So, privacy is difficult to maintain. :0

  • HttpSession:

In this technique, container creates a session ID for each user. This ID is unique to user and will be used to identify particular user.

ServletClass(where  Hidden fields are created)-

@WebServlet("/Login")
public class ServletClass extends HttpServlet {

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  /* Here, add the code to validate the user first and then fetch the data(email, age, salary) from database using JDBC */
             HttpSession session = request.getSession();
	     session.setAttribute("keyEmail", email);
	     session.setAttribute("keyAge", age);
	     session.setAttribute("keySalary", salary);

             out.print("<a href='Home'>Go to Home</a>");
	}
}

ServletHome(where data is fetched from Hidden fields)-

@WebServlet({ "/ServletHome", "/Home" })
public class ServletHome extends HttpServlet {

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                HttpSession session = request.getSession();
		String email = (String)session.getAttribute("keyEmail");
		int age = (int)session.getAttribute("keyAge");
		int salary = (int)session.getAttribute("keySalary");

		out.print("Email : "+email+"
");
		out.print("Age : "+age+"
");
		out.print("Salary : "+salary+"
");

	}
}

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.