Introduction to Java

Java technology is widely used. The questions arise: What is java? Where it is used?

Java is a programming language. It is used to make web applications, mobile applications, desktop applications, and so on.

Why Is Java used?

Java has certain advanced features over other programming languages that make it easy to use and learn. There are certain features that make it different from other languages are:-

  • Platform independency
  • Byte code
  • Portability
  • OOP concept
  • Use of applets

Platform Independency

Java is a platform-independent language. “Platform” means an environment where software runs. Now a question arises here: Why is Java platform-independent? Because Java has its own platform to run a program, it does not require any platform like other languages, such as C, C++, etc.

When a program is written in most other language, a platform-dependent executable code is produced that can only be run on same type of platform on which it is compiled. But when a Java code is compiled, it produces a .class file that contains bytecode. Bytecode runs the same on almost all computers. A Java virtual machine (JVM) loads the .class file and runs it. The compiler takes that code and converts it into the native machine code, which makes it platform-dependent. We only need to install JVM in our system.

Bytecode

Bytecode is the heart of Java; it makes Java platform-independent. Bytecode is nothing but a set of instructions designed to execute on the Java run-time machine, which is JVM. Once a programming code is compiled, it runs through JVM. Translating Java code into bytecode makes it easier to run in a wide variety of environments. The only thing required is JVM.

Once a Java program is compiled, it generates a .class file (bytecode) that can be executed on any system that supports JVM.

OOP Concept

Java is an object-oriented programming (OOP) language. Object means real world entity. Every small thing is an object, such as a pen or pencil. Java is purely based on objects. An object-oriented approach is an approach based on classes and objects.

  • Object

    An object is a real world entity. It is a state and behavior, e.g., dog, cat, pen, pencil, etc.

  • Class

    A class is collection of objects. It is nothing but a thing that is bigger and contains objects.

    Let us explain object and class with an example, such as Dog. Dog is an object. It has different states, such as color, breed, etc., and it also has behaviors, such as barking, eating, walking, etc. Now take Cat; Cat is also an object. It also has states, such as color and name, and behaviors, such as eating and walking. We can see that both objects, Dog and Cat, have some common states and behavior. Now, we can keep both the objects in a single unit, Animal. Here, Animal is a class that contains the objects Dog and Cat.

    Abstraction, polymorphism, inheritance, and encapsulation are OOP concepts that are called the four pillars of Java.

Four Pillars of Java

There are four pillars of Java:

  • Abstraction
  • Polymorphism
  • Inheritance
  • Encapsulation

Abstraction

Abstraction is hiding the complexity. It is the concept of exposing only essential characteristics and behavior. A car is a very good example of abstraction: If a person wants to drive a car, he only needs to know where the brakes, clutch, steering, gears, etc., are. He does not need to know how its engine works. But now consider a mechanic: He should know everything about the working of a car. The car’s complexity is hidden for a driver. This is nothing but abstraction.

Polymorphism

Polymorphism is combination of two roots. One is “poly,” which means “many” and the other one is “morph,” which means “form,” therefore It means “many forms.” It refers to things that can be used in many forms or, as we say in Java, a method that can be used in many ways. Let us understand it with an example: We take an operator ‘+’ that can be used to add two numbers and it also can be used for concatenation. It comes in two forms, overloading and overriding.

Inheritance

Inheritance means that a property is passed down. When one class inherits the property and behavior of another class it is called inheritance. The basic purpose of inheritance is code reusability. For example, Animal is a class. The Animal class has the properties of eating, walking, etc. Another class, Dog, also has all these properties. The Dog class can inherit the properties of Animal class. In this way, a code written for the Animal class can be reused by the Dog class. The class that inherits the property of another class is a child class or sub class and the class that is inherited from is called a parent class or super class. Inheritance can be applied when two classes have same behavior.

Encapsulation

Encapsulation means to capsulate the data. Class is a good example of encapsulation. All data members and methods are bound in a single unit, which is called a class. In encapsulation, the concept of access modifier is also used. There are three keywords (access modifiers) ‘public,’
private,’ and ‘protected,’ that are used to access the data. public means that data can be used anywhere within the class or outside the class, using the concept of inheritance. private means that data cannot be accessed outside the class. Only the method defined in the class can use it. protected data can be used by the method within the class and method within child class. It is hiding the essential details.

Portability

If a language is portable, it can be run on any operating system. Java is a language that is compiled on a system and its .class file can be run on any other system. Of course, JVM has to be installed on that system.

Java on the Web

Java on the web is divided into three categories:

  • Applets
  • Servlets
  • JSP

    Applets

    An applet is a lightweight program that runs on a browser. It is a small application that is accessed on an internet server. It is automatically installed, and run as part of web document.

    If a user clicks a link that contains applet, it will automatically download and will run on the browser. Applets are typically used to handle user input and to display data provided by server. It allows some functionality to be moved from server to client. Applets make Java a secure language.

    Want to learn more?? The InfoSec Institute Web Application Penetration Testing Boot Camp focuses on preparing you for the real world of Web App Pen Testing through extensive lab exercises, thought provoking lectures led by an expert instructor. We review of the entire body of knowledge as it pertains to web application pen testing through a high-energy seminar approach.

    The Web Application Penetration Testing course from InfoSec Institute is a totally hands-on learning experience. From the first day to the last day, you will learn the ins and outs of Web App Pen Testing by attending thought provoking lectures led by an expert instructor. Every lecture is directly followed up by a comprehensive lab exercise (we also set up and provide lab workstations so you don't waste valuable class time installing tools and apps). Benefits to you are:

    • Get CWAPT Certified
    • Learn the Secrets of Web App Pen Testing in a totally hands-on classroom environment
    • Learn how to exploit and defend real-world web apps: not just silly sample code
    • Complete the 83 Step "Web App Pen Test Methodology", and bring a copy back to work with you
    • Learn how perform OWASP Top 10 Assessments: for PCI DSS compliance

    How Are Applets Secure???

    Applets cannot access system data and files. They are executed in the JVM, which restricts the changes made by an applet to be permanent and the JVM also keeps check on what is being executed by an applet.

    Security researchers have discovered a number of vulnerabilities in Java that allow an attacker to execute arbitrary code on client’s computer. We should be aware of this, but still vulnerabilities are a part of security.

    Servlets

    A servlet is server side programming. This is nothing but a Java class that runs on a web server.

    The life cycle of servlet has five steps or five methods. Those are:

  • init()
  • service()
  • destroy()
  • getServerInfo()
  • servletConfiggetServletconfig()

    .

    An HTTP request has two methods:

  • doGet()
  • doPost()

    The doGet() method is called by default. It is invoked when an HTTP request is sent using the HTTP GET method. Like doGet(), doPost() is also invoked when a request uses the HTTP POST method. If data is sent using the GET method, then doGet() is called and parameters and their values are appended in the URL. On the other hand, in the POST method, data is sent over HTTP POST method and parameter with their values are not appended to the URL. Let us understand it with an example.

    Example of doGet()

    Hello.java

    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    @WebServlet("/Hello")public class Hello extends HttpServlet 
    {
    private static final long serialVersionUID = 1L;
        public Hello() 
        {
            super();
         }
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
    	{
    		PrintWriter out=response.getWriter();
    		out.println("Username is "+request.getParameter("user"));
    		out.println("Password is "+request.getParameter("pass"));
    		out.println("hello");
    	}
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
    	{
    		
    	}
    

    Web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
      <display-name>servlets1</display-name>
      <welcome-file-list>
        <welcome-file>default.jsp</welcome-file>
      </welcome-file-list>
      <servlet>
            <servlet-name>servlets1</servlet-name>
            <servlet-class>Hello</servlet-class>
        </servlet>
    <servlet-mapping>
            <servlet-name>servlets1</servlet-name>
            <url-pattern>/hello</url-pattern>
        </servlet-mapping>
    </web-app>
    

    login.html

    <!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>
    		<form action="Hello" method=”get”>
    		Username:<input type="text" name="user"><br>
    		Password:<input type="password" name="pass"><br>
    		<input type="submit">
    		</form>
    </body>
    </html>
    

    Here we can see that the username and password are appended in the URL, so using the doGet() method to process sensitive data is not secure.

    Example of doPost()

    Hello.java

    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    @WebServlet("/Hello")
    public class Hello extends HttpServlet 
    {
    	private static final long serialVersionUID = 1L;
        public Hello() 
        {
            super(); 
        }
       protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
    	{
        	
    	}
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
    	{
    		PrintWriter out=response.getWriter();
    		out.println("<html>");
    		out.println("<body>");
    		out.println("<form method= post>");
    		out.println("hello");
    		out.println("<br>Username:<input type="text" name="user"><br>");
    		out.println("Password:<input type="pass" name="pass"><br>");
    		out.println("<input type="submit" name="sub">");
    		out.println("</form>");
    		out.println("</body>");
    		out.println("</html>");
    		out.println("Username is "+request.getParameter("user"));
    		out.println("Password is "+request.getParameter("pass"));
    	}
    }
    

    Web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
      <display-name>servlets1</display-name>
      <welcome-file-list>
        <welcome-file>default.jsp</welcome-file>
      </welcome-file-list>
      <servlet>
            <servlet-name>servlets1</servlet-name>
            <servlet-class>Hello</servlet-class>
        </servlet>
    
        <servlet-mapping>
            <servlet-name>servlets1</servlet-name>
            <url-pattern>/hello</url-pattern>
        </servlet-mapping>
    </web-app>
    

    Login.html

    <!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>
    	<form action="Hello" method=”post”>
    	Username:<input type="text" name="user"><br>
    	Password:<input type="password" name="pass"><br>
    	<input type="submit">
    	</form>
    </body>
    </html>
    

    Here, we can see that no values are appended in the URL.

    In doPost(), the data sent over HTTP POST method is processed. This method is called only when the page is accessed by the POST method, while doGet() is called when page is accessed by the GET method. Another thing is that, in an .html file, we have to change the method name to GET or POST depending on the requirement. Please note that the GET method accepts a lower limit of data size than the POST method.

    JSP: Java Server Pages

    Java server pages (JSP) is a technology that helps software developers to create dynamically generated web pages based on HTML, XML, and Java. JSP can be used to design dynamic web applications more easily and with more flexibility, compared to what we have to do in servlets.

    Want to learn more?? The InfoSec Institute Web Application Penetration Testing Boot Camp focuses on preparing you for the real world of Web App Pen Testing through extensive lab exercises, thought provoking lectures led by an expert instructor. We review of the entire body of knowledge as it pertains to web application pen testing through a high-energy seminar approach.

    The Web Application Penetration Testing course from InfoSec Institute is a totally hands-on learning experience. From the first day to the last day, you will learn the ins and outs of Web App Pen Testing by attending thought provoking lectures led by an expert instructor. Every lecture is directly followed up by a comprehensive lab exercise (we also set up and provide lab workstations so you don't waste valuable class time installing tools and apps). Benefits to you are:

    • Get CWAPT Certified
    • Learn the Secrets of Web App Pen Testing in a totally hands-on classroom environment
    • Learn how to exploit and defend real-world web apps: not just silly sample code
    • Complete the 83 Step "Web App Pen Test Methodology", and bring a copy back to work with you
    • Learn how perform OWASP Top 10 Assessments: for PCI DSS compliance

    JSP tags

    • Scriplet tags
    • Expression tags
    • Directive tags
    • Declarative tags

    Scriplet tags→ <% (java code) %> → initialization
    Expression tags → <%= > → print
    Declarative tags → < % ! %> → initialization of methods & variables
    Directive tags → <% @ %>

    In JSP we find the method (GET or POST) with which the page is being accessed using request.getMethod().

    Example of GET Method Using JSP:

    Login.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>
    	
    	<%
    	if ("GET".equalsIgnoreCase(request.getMethod()))
    	{
    		out.println("Your username is " + request.getParameter("user")+"<br>");
    		out.println("Your password is " + request.getParameter("pass")+"<br>");
    	}
    	%>
    </body>
    </html>
    

    login.html

    <!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>
    	<form action="login.jsp" method="get">
    		Username:<input type="text" name="user"><br>
    		Password:<input type="password" name="pass"><br>
    		<input type="submit" name="sub">
    	</form>
    </body>
    </html>
    

    http://localhost:8080/demo/Login.jsp?user=hello&pass=world&sub=Submit

    In JSP too, when data is sent using the GET method, values are appended in the URL. We can see in the URL that the values of username and password are appended.

    Example of POST method using JSP:

    Login.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>
    	
    	<%
    	if ("POST".equalsIgnoreCase(request.getMethod()))
    	{
    		out.println("Your username is " + request.getParameter("user")+"<br>");
    		out.println("Your password is " + request.getParameter("pass")+"<br>");
    	}
    	%>
    </body>
    </html>
    

    Login.html

    <!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>
    	<form action="login.jsp" method="post">
    		Username:<input type="text" name="user"><br>
    		Password:<input type="password" name="pass"><br>
    		<input type="submit" name="sub">
    	</form>
    </body>
    </html>
    

    In the POST method, the data is not appended to the URL. The data is sent in request body.

    The POST method is a better choice for sending sensitive data than the GET method. Now we are aware of major components and how to use POST and GET methods in Java. We can begin to see what the shortcomings are in a Java code and how to patch them.