Java Servlet Example

Servlet

A servlet is a Java programming language class that is used to extend the capabilities of servers that host applications accessed by means of a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by web servers. See more about Servlet .

Servlet Interface

The Servlet interface is the central abstraction of the Servlet API and it defines methods which servlets must implement, see below Servlet root hierarchy.

Example

 This example is xml based ..
Create a maven web-app archetype project and add below dependencies 

<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
        </dependency>
    </dependencies>

Create a servlet class

package com.vinod;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class MyFirstServlet
 */

public class MyFirstServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * Default constructor.
     */

    public MyFirstServlet() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.println("<HTML><TITLE>Http Servlet Example</TITLE><BODY>");
        out.println("<H2>Hello world</H2><HR>");
        out.println("</BODY><HTML>");
        out.close();
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

Web.xml 

<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_2_5.xsd"
    id="WebApp_ID" version="2.5">
        <display-name>Archetype Created Web Application</display-name>
        <servlet>
            <servlet-name>MyFirstServlet</servlet-name>
            <servlet-class>com.vinod.MyFirstServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>MyFirstServlet</servlet-name>
            <url-pattern>/*</url-pattern>
        </servlet-mapping>
    </web-app>

Deploy application in to any web server and hit the below url

http://localhost:8080/vinod-web-project/MyFirstServlet

Download example

https://github.com/kkvinodkumaran/myrepository/tree/master/vinod-web-project

Reference:
Done!!!

Scripting in Java Example

Scripting in Java Example
Package javax.script 

Javax.script api provides the classes and interfaces for creating java script engines and executing java script inside java applications'

Example
Steps
· Instantiating Script engine manager instance with default constructor
· Creating script engine instance from Script engine manager
· Creating script context instance and add some values
· Execute Java Script
· Get the attribute values
· Print values



import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class ScriptingExample {
    public static void main(String[] args) {

        // Instantiating Script engine manager instance with default constructor
        ScriptEngineManager sem = new ScriptEngineManager();

        // Creating script engine instance from Script engine manager
        ScriptEngine engine = sem.getEngineByName("JavaScript");

        // Creating script context instance and add some values
        ScriptContext context = engine.getContext();

        context.setAttribute("a", 100, ScriptContext.ENGINE_SCOPE);
        context.setAttribute("b", 200, ScriptContext.ENGINE_SCOPE);

        // Execute Java Script
        try {
            engine.eval("print('Hello World!'); ");

            engine.eval("var total=a+b; ");

        } catch (ScriptException ex) {
            System.err.println(ex);
        }

        // Get the attribute values
        Double ans = (Double) context.getAttribute("total");
        // Print values
        System.out.println("Total value from script: " + ans);
    }
}

Output

Hello World!Total value from script: 300.0
 

References

Android Hello world example

 

Android Hello world example


Softwares Used


Eclipse 3.7
Java 1.6
Android SDK

Steps


1. Download and install Android SDK


( Available in http://developer.android.com/sdk/index.html)

2.Open SDK Manager (Start->Programs->Android SDK Tools) and download Android version


This example used Android 2.1 version
clip_image002

3. Install ADT Eclipse plugin in


Eclipse help menu->Install new software->Add repository with below url
https://dl-ssl.google.com/android/eclipse/

4. Create an Android Virtual Device (AVD)


In Eclipse tool bar we can see AVD Manager/ or Open it from Start->Programs->Android SDK Tools
In this example selected 2.1

clip_image004

5. Create an Android project in Eclipse


Here selected 2.1 version with blank activity (In this example i given activity name as PretechActivity)

clip_image006

6. Please see this project structure and Add TextView Object the Activity class onCreate method.


clip_image008



packagecom.example.pretechandroiddemo;

import android.os.Bundle;
importandroid.app.Activity;
import android.view.Menu;
importandroid.widget.TextView;

public class PretechActivity extends Activity {

       @Override
       public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              TextView view = new TextView(this);
              String s = "Hello world by Pretech Solutions";
              view.setText(s);
              setContentView(view);
       }

       @Override
       public booleanonCreateOptionsMenu(Menu menu) {
              getMenuInflater().inflate(R.menu.activity_pretech, menu);
              return true;
       }
}


7. Run as Android Application


We can see the emulator starting and creating apk file and installing in the console
Note: Some times emulator will take long time to start, please wait for few minutes


[2012-09-25 01:31:46 - PretechAndroidDemo] ------------------------------
[2012-09-25 01:31:46 - PretechAndroidDemo] Android Launch!
[2012-09-25 01:31:46 - PretechAndroidDemo] adb is running normally.
[2012-09-25 01:31:46 - PretechAndroidDemo] Performing com.example.pretechandroiddemo.PretechActivity activity launch
[2012-09-25 01:31:46 - PretechAndroidDemo] Automatic Target Mode: launching new emulator with compatible AVD 'Pretech'
[2012-09-25 01:31:46 - PretechAndroidDemo] Launching a new emulator with Virtual Device 'Pretech'
[2012-09-25 01:31:47 - PretechAndroidDemo] New emulator found: emulator-5554
[2012-09-25 01:31:47 - PretechAndroidDemo] Waiting for HOME ('android.process.acore') to be launched...
[2012-09-25 01:33:15 - PretechAndroidDemo] HOME is up on device 'emulator-5554'
[2012-09-25 01:33:15 - PretechAndroidDemo] Uploading PretechAndroidDemo.apk onto device 'emulator-5554'
[2012-09-25 01:33:16 - PretechAndroidDemo] Installing PretechAndroidDemo.apk...
[2012-09-25 01:34:55 - PretechAndroidDemo] Success!
[2012-09-25 01:34:55 - PretechAndroidDemo] Starting activity


Output



clip_image010
















































GWT Menu example

Here is one simple example to create GWT Menu, please follow below steps to create Menus

1. Create a GWT Project and update Entry point class with below code

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.MenuBar;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class PretechGWT implements EntryPoint {

@Override
public void onModuleLoad() {
Command cmd = new Command() {
public void execute() {
Window.alert("You selected a menu item!");
}
};
Label label = new Label("Hello World");
Button button = new Button("Click on this");

MenuBar pretechMenu = new MenuBar();

pretechMenu.addItem("Home", cmd);
pretechMenu.addItem("Frameworks", cmd);
pretechMenu.addItem("Java/J2ee",cmd);
pretechMenu.addItem("Mongodb",cmd);

button.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
Window.alert("Hello good morning.. this message from event");
}
});
RootPanel.get().add(pretechMenu);
RootPanel.get().add(label);
RootPanel.get().add(button);
}
}

2. Run application

clip_image002

GWT Hello world Example

What is Google Web Toolkit

The Google Web Toolkit (GWT) is a open source toolkit to develop Ajax web application with Java. The programmer writes Java code and this code is translated into HTML and Javascript via the GWT compiler. 

GWT modes

Development Mode: allows to debug the Java code of your application directly via the standard Java debugger.
Web mode: the application is translated into HTML and Javascript code and can be deployed to a webserver. 

GWT Components

GWT has four major components: a Java-to-JavaScript compiler, a "hosted" web browser, and two Java class libraries
clip_image002 

GWT Entry points

All GWT applications are started with Entry points,Entry points are starting point of a GWT application and we have to implement com.google.gwt.core.client.EntryPoint interface to our Entry point class and should override onModuleLoad() method 

GWT Modules

GWT applications are described as modules. A module "modulename" is described by a configuration file "modulename.gwt.xml". Each module can define one or more Entry point classes. 

GWT Hello world example

1. Install Google tools plug-in in Eclipse (Help->Eclipse Market place)

clip_image004

2. Create a GWT Web application project

clip_image006

4. Project Structure

clip_image008

5 Create/Modify GWT entry point

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class PretechGWT implements EntryPoint {

@Override
public void onModuleLoad() {
Label label = new Label("Hello World");
Button button = new Button("Click on this");
button.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
Window.alert("Hello good morning.. this message from event");
}
});


RootPanel.get().add(label);
RootPanel.get().add(button);
}
}

6. Create/Modify html page (PretechGWT.html)

<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">

<title>Web Application Starter Project</title>
<script type="text/javascript" language="javascript"
src="pretechgwt/pretechgwt.nocache.js"></script>
</head>
<body>
<iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1'
style="position: absolute; width: 0; height: 0; border: 0"></iframe>
<noscript>
<div
style="width: 22em; position: absolute; left: 50%; margin-left: -11em; color: red; background-color: white; border: 1px solid red; padding: 4px; font-family: sans-serif">
Your web browser must have JavaScript enabled in order for this
application to display correctly.</div>
</noscript>
<h1>Pretech GWT Web Application Starter Project</h1>
</body>
</html>

7. Generated Web.xml

<?xmlversion="1.0"encoding="UTF-8"standalone="no"?><web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<!-- Servlets -->
<servlet>
<servlet-name>greetServlet</servlet-name>
<servlet-class>com.pretechgwt.server.GreetingServiceImpl</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>greetServlet</servlet-name>
<url-pattern>/pretechgwt/greet</url-pattern>
</servlet-mapping>

<!-- Default page to serve -->
<welcome-file-list>
<welcome-file>PretechGWT.html</welcome-file>
</welcome-file-list>

<servlet>
<servlet-name>SystemServiceServlet</servlet-name>
<servlet-class>com.google.api.server.spi.SystemServiceServlet</servlet-class>
<init-param>
<param-name>services</param-name>
<param-value/>
</init-param>
</servlet>

<servlet-mapping>
<servlet-name>SystemServiceServlet</servlet-name>
<url-pattern>/_ah/spi/*</url-pattern>
</servlet-mapping>

</web-app>
8. Run application and install this plug-in in browser if required
clip_image010clip_image012

9. Output

clip_image014

10. Reference

https://developers.google.com/web-toolkit/

Cobertura Line and Branch coverage Example


1. What is Cobertura ?

Cobertura is a free Java tool that calculates the percentage of code accessed by tests. It can be used to identify which parts of your Java program are lacking test coverage. It is based on jcoverage.

2. Cobertura Advantages and Features

  • Cobertura is a open source Java tool
  • Helps to get the code coverage details
  • It shows the percentage of line and branch test cases have been covered
  • Cobertura report shows which line of code is lacking of test cases
  • It can be executed with Maven, Ant or command line

3. What is Line and Branch Coverage?

Line coverage –> During the test cases run how much percentage of lines have been covered

Branch coverage-> During the test coverage how much percentage of branches have been covered.

4. Cobertura Example


Below example will show how cobertura calculating line and branch coverage.

1. Create a Maven Project and add below plugin/configuration in pom.xml

Note: Please check the include tag to add package details
 
<dependencies>
  <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <!-- cobertura -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>cobertura-maven-plugin</artifactId>
                <version>2.1</version>
                <configuration>
                    <instrumentation>
                        <includes>
                            <include>com/pretechsol/**/*.class</include>
                        </includes>
                    </instrumentation>
                </configuration>
                <executions>
                    <execution>
                        <id>clean</id>
                        <phase>pre-site</phase>
                        <goals>
                            <goal>clean</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>instrument</id>
                        <phase>site</phase>
                        <goals>
                            <goal>instrument</goal>
                            <goal>cobertura</goal>
                            <goal>check</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
    <reporting>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>cobertura-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </reporting>

2. Create a Sample Java Program and its Junit Test

package com.vinod;

public class SimpleValidate {
    public String validation(String name, String gender) {
        if (name.equals("")) {
            System.out.println("name should not be null");
        }
        if (gender.equals("")) {
            System.out.println("gender should not be null");
        }
        String result = null;
        if (name.equals("pretech")) {
            if (gender.equals("male")) {
                result = "success";
            } else {
                result = "fail";
            }
        } else {
            result = "try again";
        }
        return result;
    }
}
 

3. Junit test class

package com.vinod.test;

import org.junit.Before;

import com.vinod.SimpleValidate;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.After;
import org.junit.Test;

public class SimpleValidateTest {
    SimpleValidate simpleValidate = null;

    @Before
    public void setUp() throws Exception {
        simpleValidate = new SimpleValidate();
        assertNotNull(simpleValidate);
    }
    @After
    public void tearDown() throws Exception {
        simpleValidate = null;
    }
    @Test
    public void testSimpleValidateaValidation() {

        String result = simpleValidate.validation("Vinod", "male");
        assertEquals("try again", result);
    }
    @Test
    public void testSimpleValidateValidation1() {
        String result = simpleValidate.validation("", "male");
        assertEquals("try again", result);
    }

}
 

Run it (Use below command)

mvn clean install cobertura:cobertura

After the build we can see the cobertura report has been generated with test coverage statistics..

 
Done!!!
Download example 
 
 

Model Context Protocol (MCP) — Complete Guide for Backend Engineers

  Model Context Protocol (MCP) — Complete Guide for Backend Engineers Build Tools, Resources, and AI-Driven Services Using LangChain Moder...

Featured Posts