Captcha creating in servlet

Posted by Somesh Shinde On Tuesday, 23 August 2016 0 comments
Captcha creating in servlet

captcha is a type of challenge-response test used in computing to determine whether the user is human. Captcha is a contrived acronym for "Completely Automated Public Turing test to tell Computers and Humans Apart". (Wikipedia) Using captchas on Internet is almost inevitable, because the forums and message boards are infested with spam.

Captcha

In the following example, we will demonstrate a captcha system in a small example. We have an HTML form. At the bottom of the form, we have a input tag named code. Here the user has to copy the characters of an image, which is displayed below the input box. This is the most common captcha system on the Internet. The main part of the captcha system is a image, displaying random alphanumeric characters. The characters are usually blurred or otherwise made a bit more difficult to read.
style.css
* { font-size: 12px; font-family: Verdana }

input, textarea { border: 1px solid #ccc }

tr { margin: 5px; padding:5px;}

.alert { font-size:15px; color:red; font-weight:bolder }
This is a simple style sheet for our example. The .alert class is used to format text displaying whether we passed the test or not.
index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Captcha</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<center>
<form method="post">
<table cellspacing="15">
<tr>
<td>Name</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Message</td>
<td> <textarea type="text" cols="25" rows="8" name="message"></textarea></td>
</tr>

<tr>
<td>Are you human?</td>
<td><input type="text" name="code"></td>
</tr>

</table>

<br>
<img src="http://localhost:8080/captcha/CaptchaServlet"> 

<br><br>
<input type="submit" value="submit">

</form>
<br><br>
<%
  String captcha = (String) session.getAttribute("captcha");
  String code = (String) request.getParameter("code");

  if (captcha != null && code != null) {

    if (captcha.equals(code)) {
   out.print("<p class='alert'>Correct</p>");
    } else {
          out.print("<p class='alert'>Incorrect</p>");
    }
  }
%>
</center>
</body>
</html>
This is the file, where we define the HTML form, load the captcha image and react to submit action.
<form method="post">
If we do not provide the action parameter, the processing is transfered to the same file by default, e.g. index.jsp in our case.
<img src="http://localhost:8080/captcha/CaptchaServlet"> 
This is the way, how we get the image from the servlet. We provide the location of the servlet to the src parameter of the HTML img tag. Each time we refresh the page, we get a new image from theCaptchaServlet.
String captcha = (String) session.getAttribute("captcha");
String code = (String) request.getParameter("code");

if (captcha != null && code != null) {

if (captcha.equals(code)) {
        out.print("<p class='alert'>Correct</p>");
} else {
        out.print("<p class='alert'>Incorrect</p>");
}
}
This code receives the parameters from the request. The message and name parameters are ignored. The captcha is a string that is set randomly by the servlet. This string is being shown in the image. The code is the text, which is put by the user. If these two strings match, we output "Correct" string, otherwise "Incorrect".
Captcha
Figure: Captcha
CaptchaServlet.java
package com.zetcode;

import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;

import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.*;
import javax.servlet.http.*;


public class CaptchaServlet extends HttpServlet {


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

    int width = 150;
    int height = 50;

    char data[][] = {
        { 'z', 'e', 't', 'c', 'o', 'd', 'e' },
        { 'l', 'i', 'n', 'u', 'x' },
        { 'f', 'r', 'e', 'e', 'b', 's', 'd' },
        { 'u', 'b', 'u', 'n', 't', 'u' },
        { 'j', 'e', 'e' }
    };


    BufferedImage bufferedImage = new BufferedImage(width, height, 
                  BufferedImage.TYPE_INT_RGB);

    Graphics2D g2d = bufferedImage.createGraphics();

    Font font = new Font("Georgia", Font.BOLD, 18);
    g2d.setFont(font);

    RenderingHints rh = new RenderingHints(
           RenderingHints.KEY_ANTIALIASING,
           RenderingHints.VALUE_ANTIALIAS_ON);

    rh.put(RenderingHints.KEY_RENDERING, 
           RenderingHints.VALUE_RENDER_QUALITY);

    g2d.setRenderingHints(rh);

    GradientPaint gp = new GradientPaint(0, 0, 
    Color.red, 0, height/2, Color.black, true);

    g2d.setPaint(gp);
    g2d.fillRect(0, 0, width, height);

    g2d.setColor(new Color(255, 153, 0));

    Random r = new Random();
    int index = Math.abs(r.nextInt()) % 5;

    String captcha = String.copyValueOf(data[index]);
    request.getSession().setAttribute("captcha", captcha );

    int x = 0; 
    int y = 0;

    for (int i=0; i<data[index].length; i++) {
        x += 10 + (Math.abs(r.nextInt()) % 15);
        y = 20 + Math.abs(r.nextInt()) % 20;
        g2d.drawChars(data[index], i, 1, x, y);
    }

    g2d.dispose();

    response.setContentType("image/png");
    OutputStream os = response.getOutputStream();
    ImageIO.write(bufferedImage, "png", os);
    os.close();
  } 


  protected void doGet(HttpServletRequest request, 
                       HttpServletResponse response)
                           throws ServletException, IOException {
      processRequest(request, response);
  } 


  protected void doPost(HttpServletRequest request, 
                        HttpServletResponse response)
                            throws ServletException, IOException {
      processRequest(request, response);
  }
}
In the Captcha servlet, we create an image of 150*50 size. To create the image, we use the Java 2D vector library. The image is filled with red - black gradient. We draw randomly a string into the image.
char data[][] = {
    { 'z', 'e', 't', 'c', 'o', 'd', 'e' },
    { 'l', 'i', 'n', 'u', 'x' },
    { 'f', 'r', 'e', 'e', 'b', 's', 'd' },
    { 'u', 'b', 'u', 'n', 't', 'u' },
    { 'j', 'e', 'e' }
};
This is an array, from which we choose our string.
BufferedImage bufferedImage = new BufferedImage(width, height, 
            BufferedImage.TYPE_INT_RGB);

Graphics2D g2d = bufferedImage.createGraphics();
We will draw into a buffered image.
RenderingHints rh = new RenderingHints(
        RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);

rh.put(RenderingHints.KEY_RENDERING, 
        RenderingHints.VALUE_RENDER_QUALITY);

g2d.setRenderingHints(rh);
The rendering hints are used to increase the quality of the text.
g2d.setRenderingHints(rh);

GradientPaint gp = new GradientPaint(0, 0, 
Color.red, 0, height/2, Color.black, true);

g2d.setPaint(gp);
g2d.fillRect(0, 0, width, height);
Here we draw the gradient.
Random r = new Random();
int index = Math.abs(r.nextInt()) % 5;

String captcha = String.copyValueOf(data[index]);
request.getSession().setAttribute("captcha", captcha );
Here we randomly choose an index into the array. We also set the chosen string into the session, so that we can compare it later to the parameter, specified by the user.
int x = 0; 
int y = 0;

for (int i=0; i<data[index].length; i++) {
    x += 10 + (Math.abs(r.nextInt()) % 15);
    y = 20 + Math.abs(r.nextInt()) % 20;
    g2d.drawChars(data[index], i, 1, x, y);
}
This is the code that draws the string into the image. We must make sure, that the text fits into the boudaries of the image.
response.setContentType("image/png");
OutputStream os = response.getOutputStream();
ImageIO.write(bufferedImage, "png", os);
os.close();
Finally, we return the image through a byte stream. We set a content type to png image. The write()method of the ImageIO class writes the data from the buffered image into the servlet output stream. This way we send binary data to the client.


In this chapter we have created a captcha in a Java Servlet.
READ MORE

Save SqlQuery result to FlatFiles

Posted by Somesh Shinde On Wednesday, 17 August 2016 0 comments

Save SqlQuery result to FlatFiles


 public void printToFile( ResultSet rs, String path ) throws IOException { 

     PrintStream out = new FileOutputStream( path );

     int cols = rs.getMetaData().getColumnCount();

     while( rs.next() ) { 
         for( int i = 0; i < cols ; i++ ) { 
             out.printf("%s,", rs.getObject( i ) );
          }           
          out.println();
     }

     // add exception handling and such...
     // or move the from here.
     out.close();
     rs.close();

 }
And then call it like this:
 ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
 printToFile( rs, "/some/file" );


If you use this function, be sure to change 
PrintStream out = new FileOutputStream(path); toPrintStream out = new PrintStream(new FileOutputStream(pat‌​h));
READ MORE

Login System Using Servlet

Posted by Somesh Shinde On Thursday, 4 August 2016 0 comments

Login System Using Servlet


In this example we will show you how to develop a login form using servlet. Here we are using MySqldatabase. List of file to be created are:
  • index.html
  • Login.java
  • Validate.java
  • Welcome.java
  • web.xml
login form example with Servlet
To try this application you will need to create a table in your database and enter some record into it. Refer the previos Lesson for creating table.

index.html

<html>
    <head>
        <title>login form</title>
    </head>
    <body>
        <form method="post" action="login">
        Email ID:<input type="text" name="email" /><br/>
        Password:<input type="text" name="pass" /><br/>
        <input type="submit" value="login" />
        </form>
    </body>
</html>

Login.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class Login extends HttpServlet {
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        String email = request.getParameter("email");
        String pass = request.getParameter("pass");
        
        if(Validate.checkUser(email, pass))
        {
            RequestDispatcher rs = request.getRequestDispatcher("Welcome");
            rs.forward(request, response);
        }
        else
        {
           out.println("Username or Password incorrect");
           RequestDispatcher rs = request.getRequestDispatcher("index.html");
           rs.include(request, response);
        }
    }  
}

Validate.java

import java.sql.*;

public class Validate
 {
     public static boolean checkUser(String email,String pass) 
     {
      boolean st =false;
      try{

  //loading drivers for mysql
         Class.forName("com.mysql.jdbc.Driver");

   //creating connection with the database 
         Connection con=DriverManager.getConnection
                        ("jdbc:mysql:/ /localhost:3306/test","root","studytonight");
         PreparedStatement ps =con.prepareStatement
                             ("select * from register where email=? and pass=?");
         ps.setString(1, email);
         ps.setString(2, pass);
         ResultSet rs =ps.executeQuery();
         st = rs.next();
        
      }catch(Exception e)
      {
          e.printStackTrace();
      }
         return st;                 
  }   
}

Welcome.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class Welcome extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println("Welcome user");
      }  
}

web.xml

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

    <servlet>
        <servlet-name>login</servlet-name>
        <servlet-class>Login</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>Welcome</servlet-name>
        <servlet-class>Welcome</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>login</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Welcome</servlet-name>
        <url-pattern>/Welcome</url-pattern>
    </servlet-mapping>
    
</web-app>
READ MORE

Run Servlet Application Using Eclipse IDE

Posted by Somesh Shinde On 0 comments

Run Servlet Application Using Eclipse IDE


Eclipse IDE is the most popular Java IDE used in the Industry. It is developed by an open source community and can be downloaded for free from Eclipse.org

Steps to create Servlet using Eclipse IDE

To create a Servlet application in Eclipse IDE you will need to follow the following steps:
  1. Goto File -> New -> Dynamic Web Project
    steps to create servlet application in eclipse

  2. Give a Name to your Project and click Next
    steps to create servlet application in eclipse

    steps to create servlet application in eclipse

  3. Check Generate web.xml Deployment Descriptor and click Finish
    steps to create servlet application in eclipse

  4. Now, the complete directory structure of your Project will be automatically created by Eclipse IDE.
    steps to create servlet application in eclipse

  5. Click on First project, go to Java Resources -> src. Right click on src select New -> Servlet
    steps to create servlet application in eclipse

  6. Give Servlet class name and click Next
    steps to create servlet application in eclipse

  7. Give your Servlet class a Nmae of your choice.
    steps to create servlet application in eclipse

  8. Leave everything else to default and click Finish
    steps to create servlet application in eclipse

  9. Now your Servlet is created, write some code inside it. You can take reference from the code in the picture below.
    steps to create servlet application in eclipse

  10. Add servlet-api.jar JAR file to your project. Click on Libraries, right click on Web App Libraries selectBuild Path -> Configure Build Path
    steps to create servlet application in eclipse

  11. Click on Add External JARs
    steps to create servlet application in eclipse

  12. This JAR is now added to your project's build path.
  13. Select servlet-api.jar from Apache Tomcat Directory
    steps to create servlet application in eclipse

    steps to create servlet application in eclipse

  14. Now all you have to do is Start the server and run the application.
    steps to create servlet application in eclipse

Thank U.....
READ MORE

Process for creating servlet using Tomcat Server

Posted by Somesh Shinde On 0 comments

Process for creating servlet using Tomcat Server


To create a Servlet application you need to follow the below mentioned steps. These steps are common for all the Web server. In our example we are using Apache Tomcat server. Apache Tomcat is an open source web server for testing servlets and JSP technology. Download latest version of Tomcat Server and install it on your machine.
After installing Tomcat Server on your machine follow the below mentioned steps :
  1. Create directory structure for your application.
  2. Create a Servlet
  3. Compile the Servlet
  4. Create Deployement Descriptor for your application
  5. Start the server and deploy the application
All these 5 steps are explained in details below, lets create our first Servlet Application.

1. Creating the Directory Structure

Sun Microsystem defines a unique directory structure that must be followed to create a servlet application.
servlet directory strucutre
Create the above directory structure inside Apache-Tomcat\webapps directory. All HTML, static files(images, css etc) are kept directly under Web application folder. While all the Servlet classes are kept inside classesfolder.
The web.xml (deployement descriptor) file is kept under WEB-INF folder.

Creating a Servlet

There are three different ways to create a servlet.
  • By implementing Servlet interface
  • By extending GenericServlet class
  • By extending HttpServlet class
But mostly a servlet is created by extending HttpServlet abstract class. As discussed earlier HttpServlet gives the definition of service() method of the Servlet interface. The servlet class that we will create should not override service() method. Our servlet class will override only doGet() or doPost() method.
When a request comes in for the servlet, the Web Container calls the servlet's service() method and depending on the type of request the service() method calls either the doGet() or doPost() method.
NOTE: By default a request is Get request.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public MyServlet extends HttpServlet
{
 public void doGet(HttpServletRequest request,HttpServletResposne response) 
                     throws ServletException
 {
   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
   out.println("<html><body>");
   out.println("<h1>Hello Readers</h1>");
   out.println("</body></html>");
 }
}
Write above code in a notepad file and save it as MyServlet.java anywhere on your PC. Compile it(explained in next step) from there and paste the class file into WEB-INF/classes/ directory that you have to create inside Tomcat/webapps directory.

Compiling a Servlet

To compile a Servlet a JAR file is required. Different servers require different JAR files. In Apache Tomcat server servlet-api.jar file is required to compile a servlet class.
Steps to compile a Servlet
  • Set the Class Path.
  • compiling a Servlet
  • Download servlet-api.jar file.
  • Paste the servlet-api.jar file inside Java\jdk\jre\lib\ext directory.
  • compiling a Servlet
  • Compile the Servlet class.
  • compiling a Servlet
NOTE: After compiling your Servlet class you will have to paste the class file into WEB-INF/classes/directory.

Create Deployment Descriptor

Deployment Descriptor(DD) is an XML document that is used by Web Container to run Servlets and JSP pages. DD is used for several important purposes such as:
  • Mapping URL to Servlet class.
  • Initializing parameters.
  • Defining Error page.
  • Security roles.
  • Declaring tag libraries.
We will discuss about all these in details later. Now we will see how to create a simple web.xml file for our web application.
web.xml file

Start the Server

Double click on the startup.bat file to start your Apache Tomcat Server.
Or, execute the following command on your windows machine using RUN prompt.
C:\apache-tomcat-7.0.14\bin\startup.bat

Starting Tomcat Server for the first time

If you are starting Tomcat Server for the first time you need to set JAVA_HOME in the Enviroment variable. The following steps will show you how to set it.
  • Right Click on My Computer, go to Properites.
  • setting JAVA_HOME for Tomcat
  • Go to Advanced Tab and Click on Enviroment Variables... button.
  • setting JAVA_HOME for Tomcat
  • Click on New button, and enter JAVA_HOME inside Variable name text field and path of JDK inside Variable value text field. Click OK to save.
  • setting JAVA_HOME for Tomcat

Run Servlet Application

Open Browser and type http:localhost:8080/First/hello
Running first servlet application
Hurray! Our first Servlet Application ran successfully.
READ MORE

How to copy data from one table to another

Posted by Somesh Shinde On Tuesday, 2 August 2016 0 comments

How to copy data from one table to another


If you don't want to list the fields, and the structure of the tables is the same, you can do:
INSERT INTO `table2` SELECT * FROM `table1`;
or if you want to create a new table with the same structure:
CREATE TABLE new_tbl [AS] SELECT * FROM orig_tbl;
Example::
SQL> INSERT INTO COURSES SELECT * FROM STUDENT;

6 rows created.
READ MORE

Assert keyword in Java

Posted by Somesh Shinde On Monday, 1 August 2016 0 comments

ASSERT IN JAVA


The assert keyword is used in assert statement which is a feature of the Java programming language since Java 1.4. Assertion enables developers to test assumptions in their programs as a way to defect and fix bugs.

Syntax of assert statement

 Syntax of an assert statement is as follow (short version):
assert expression1;

or (full version):
assert expression1 : expression2;

Where:
  • expression1 must be a boolean expression.
  • expression2 must return a value (must not return void).
The assert statement is working as follows:
    • If assertion is enabled, then the assert statement will be evaluated. Otherwise, it does not get executed.
    • If expression1 is evaluated to false, an AssertionError error is thrown which causes the program stops immediately. And depending on existence of expression2:
      • If expression2 does not exist, then the AssertionError is thrown with no detail error message.
      • If expression2 does exist, then a String representation of expression2’s return value is used as detail error message.
    • If expression1 is evaluate to true, then the program continues normally.

Enable assertion


By default, assertion is disabled at runtime. To enable assertion, specify the switch –enableassertions or -ea at command line of java program. For example, to enable assertion for the program called CarManager:
java –enableassertions CarManager

or this for short:
java –ea CarManager

Assertion can be enabled or disable specifically for named classes or packages. For more information on how to enable and disable assertion, go to: http://docs.oracle.com/javase/1.4.2/docs/guide/lang/assert.html#enable-disable

Assertion examples

 The following simple program illustrates the short version of assert statement:
public class AssertionExample{
           public static void main(String args[]){
                              //get a number in the first argument
                             int number=Integer.perseInt(args[0]);
                             assert number<=10;
                             System.out.println("PASS");
           }
}

 When running the program above with this command:
java -ea AssertionExample 15

java.lang.AssertionError error will be thrown:

Exception in thread "main" java.lang.AssertionError

       at AssertionExample.main(AssertionExample.java:6)

But the program will continue and print out “Pass” if we pass a number less than 10, in this command:

java -ea AssertionExample 8

And the following example is using the full version of assert statement:
public class AssertionExample2 {
    public static void main(String[] args) {
        int argCount = args.length;
        assert argCount == 5 : "The number of arguments must be 5";
        System.out.println("OK");

    }

}
 When running the program above with this command:

java -ea AssertionExample2 1 2 3 4

it will throw this error:

Exception in thread "main" java.lang.AssertionError: The number of arguments must be 5

       at AssertionExample2.main(AssertionExample2.java:6)

Generally, assertion is enabled during development time to defect and fix bugs, and is disabled at deployment or production to increase performance.
READ MORE