Showing posts with label Web Technology. Show all posts
Showing posts with label Web Technology. Show all posts

Friday, February 25, 2011

Online Eamination using JSP and Databases

 Question - Write programs in Java to create three-tier applications using JSP and Databases for conducting online examination.


Download Source code

Download Database file

index.jsp

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Welcome to Online Examination</title>
    </head>
    <body bgcolor="cyan">
        <form name="index" action="exam.jsp" method="post">
        <center><h1><span><font color="red">Welcome to Online Examination</font></span></h1>
        <br>
        <h2><u><span><font color="blue">Instructions to the Candidates</font></span></u></h2>
        <br><h3><ol><li>Fill the correct Registration number.</li>
        <br><li>Enter your name.</li>
        <br><li>Read the questions carefully.</li>
        <br><li>No negative marking.</li></ol></h3>
     
        <br>
        <b>Enter your Register number</b>
        <input type="text" name="txt_reg">
        <b>Enter your Name</b>
        <input type="text" name="txt_name"><br><br>
        <input name ="submit" value="Submit" type="submit"/>
        </center>
        </form>
    </body>
</html>


exam.jsp

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Examination Panel</title>
    </head>
    <body bgcolor="cyan">
        <%@ page language="java" %>
<%@ page import ="java.sql.*" %>
<%
String reg= request.getParameter("txt_reg");
String name = request.getParameter("txt_name");
out.println("<h2>Welcome"   name   "...Your Register number is "   reg   "!!</h2><br><br><br>");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String sTable = "exam";
String sSql = "SELECT * FROM "   sTable   "";
String sDBQ = "C:/Users/A/Documents/NetBeansProjects/Online Examination/exam.mdb";

String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ="   sDBQ   ";DriverID=22;READONLY=true";
Connection cn = null;
Statement st = null;
ResultSet rs = null;
try {
cn = DriverManager.getConnection( database ,"","");
st = cn.createStatement();
rs = st.executeQuery( sSql );
ResultSetMetaData rsmd = rs.getMetaData();
String s1,s2,s3,s4;
int i=1;
while(rs.next())
{

out.println("<form name='exam' action='report.jsp' method='post'><b>" i " . "   rs.getString(1)   "</b><br><br>");
s1 = rs.getString(2);
s2 = rs.getString(3);
s3 = rs.getString(4);
s4 = rs.getString(5);
out.println("<input type=radio name=opt" i " value=" s1 " CHECKED>"  s1  " <br><br>");
out.println("<input type=radio name=opt" i " value=" s2 ">"   s2  "<br><br>");
out.println("<input type=radio name=opt" i " value=" s3 ">"   s3  "<br><br>");
out.println("<input type=radio name=opt" i " value=" s4 ">"   s4  "<br><br>");
i  ;
}
out.println("<input name ='submit' value='Submit' type='submit'/>");
/*int n = rsmd.getColumnCount();
out.println( "<table border=1 cellspacing=3><tr>" );
for( int i=1; i<=n; i   ) // Achtung: erste Spalte mit 1 statt 0
out.println( "<th>"   rsmd.getColumnName( i )   "</th>" );
while( rs.next() )
{
out.println( "</tr><tr>" );
for( int i=1; i<=n; i   ) // Achtung: erste Spalte mit 1 statt 0
out.println( "<td nowrap>"   rs.getString( i )   "</td>" );
}
out.println( "</tr></table>" );*/
}
  finally {
try { if( null != rs ) rs.close(); } catch( Exception ex ) {}
try { if( null != st ) st.close(); } catch( Exception ex ) {}
try { if( null != cn ) cn.close(); } catch( Exception ex ) {}
}

%>
       
    </body>
</html>

report.jsp

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Exam Report</title>
    </head>
    <body bgcolor="cyan">
        <center><h1>Your Report Card</h1></center>
 <%@ page language="java" %>
<%@ page import ="java.sql.*" %>
<%
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String sTable = "exam";
String sSql = "SELECT * FROM "   sTable   "";
String sDBQ = "C:/Users/A/Documents/NetBeansProjects/Online Examination/exam.mdb";

String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ="   sDBQ   ";DriverID=22;READONLY=true";
Connection cn = null;
Statement st = null;
ResultSet rs = null;
try {
cn = DriverManager.getConnection( database ,"","");
st = cn.createStatement();
rs = st.executeQuery( sSql );
ResultSetMetaData rsmd = rs.getMetaData();
String s1,s2,s3,s4;
int i=1;
int correct=0,incorrect=0,total=0;
out.println("<h2><br><br><center><table border=1 cellpadding=2 cellspacing=2><tr><th>Question</th><th>Your Answer</th><th>Correct Answer</th><th>Status</th></tr>");
while(rs.next())
{
total  ;
s1 = rs.getString(1);
s2 = request.getParameter("opt" i);
s3 = rs.getString(6);
if(s2.equals(s3))
{
    s4="Correct";
    correct  ;
}
else
{
    s4="Incorrect";
    incorrect  ;
}   
out.println("<tr><td>" s1 "</td><td>" s2 "</td><td>" s3 "</td><td>" s4 "</td></tr>");
i  ;
}
out.println("</table><br><br><table><b><tr><td>Correct Answers</td><td>" correct "</td></tr>");
out.println("<tr><td>Incorrect Answers</td><td>" incorrect "</td></tr>");
out.println("<tr><td>Total Questions</td><td>" total "</td></tr></table></b></center></h2>");

}
  finally {
try { if( null != rs ) rs.close(); } catch( Exception ex ) {}
try { if( null != st ) st.close(); } catch( Exception ex ) {}
try { if( null != cn ) cn.close(); } catch( Exception ex ) {}
}

%>
     
    </body>
</html>





Screenshots


index.jsp


exam.jsp


report.jsp



Hope u like it guys..:)

Monday, February 7, 2011

Invoking servlets from HTML forms

Question - "To invoke servlets from HTML forms".

To work on this program, I recommend you to download Netbeans IDE.

You can download Netbeans IDE from the following link,

http://netbeans.org/downloads/

After you download and install perform the following procedure,

Procedure to run this program on Netbeans
  • Start Netbeans IDE.
  • Now Select File->New Project.
  • In the New Project Dialog box that appears  select Java Web(Web Application).
  • Now “New Web Application” Dialog box appears.
  • Give the Project Name as “ServletApplication”.
  • Click Next twice and then Finish.
  • Now a web application named ServletApplication is created with a default page “index.jsp”. There write the code for HTML forms.
  • Then right click on the WEB-INF folder and select New-> Servlet. Give the name of the servlet as “MyServlet” , click Next. In the next dialog that appears please make sure “Add information to deployment descriptor” checkbox is selected. Now click next and then finish.
  • Write the code for Servlet in it.
  • To compile the file, right click on index.jsp and then select “compile file”.
  • After compiling, again right click on index.jsp and select “Run file”.
  • Now the browser(use firefox) will open and verify the output.
Download the Source code 


Code

index.jsp

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<html>
    <head><title>HTML Forms and Servlet</title></head>
    <body>
        <%-- <jsp:useBean id="beanInstanceName" scope="session" class="beanPackage.BeanClassName" /> --%>
        <%-- <jsp:getProperty name="beanInstanceName"  property="propertyName" /> --%>
        <h1>Enter your Details</h1>
        <form action = "MyServlet">
        <table>
        <tr>
        <td>Name
        <td><input type="text" name="name"><br><br>
        </tr>
        <tr>
        <td>Reg No
        <td><input type="text" name="reg"><br><br>
        </tr>
        <tr>
        <td>Sub1 Mark
        <td><input type="text" name="sub1"><br><br>
        </tr>
        <tr>
        <td>Sub2 Mark
        <td><input type="text" name="sub2"><br><br>
        </tr>
        <tr>
        <td>Sub3 Mark
        <td><input type="text" name="sub3"><br><br>
        </tr>
        <tr>
        <td>Sub4 Mark
        <td><input type="text" name="sub4"><br><br>
        </tr>
        <tr>
        <td>Sub5 Mark
        <td><input type="text" name="sub5"><br><br>
        </tr>
        <tr>
        <td>Sub6 Mark
        <td><input type="text" name="sub6"><br><br>
        </tr>
        </table>
        <input type="submit">
        </form>
    </body>
</html>


MyServlet.java

/*
 * MyServlet.java
 *
 * Created on February 3, 2011, 9:03 PM
 */
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
 *
 * @author  Administrator
 * @version
 */
public class MyServlet extends HttpServlet {
    /** Initializes the servlet.
     */
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

    /** Destroys the servlet.
     */
    public void destroy() {

    }
      public String display(int mark)
    {
        if(mark>90 && mark<=100)
    {
    return "S";
    }
    else if(mark>80 && mark<=90)
    {
    return("A");
    }
    else if(mark>70 && mark<=80)
    {
    return("B");
    }
    else if(mark>60 && mark<=70)
    {
    return("C");
    }
    else if(mark>55 && mark<=60)
    {
    return("D");
    }
    else if(mark>=50 && mark<55)
    {
    return("E");
    }
    else
    {
    return("Re Appear");
    }
    }
    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        try {
            String name, reg;
            int mark,s1,s2,s3,s4,s5,s6;
name = request.getParameter("name");
reg = request.getParameter("reg");
s1 = Integer.parseInt(request.getParameter("sub1"));
s2 = Integer.parseInt(request.getParameter("sub2"));
s3 = Integer.parseInt(request.getParameter("sub3"));
s4 = Integer.parseInt(request.getParameter("sub4"));
s5 = Integer.parseInt(request.getParameter("sub5"));
s6 = Integer.parseInt(request.getParameter("sub6"));

response.setContentType("text/html");

out.println("<html>");
out.println("<head>");
out.println("<title>Mark Report Servlet<title>");
out.println("</head>");

out.println("<body>");
out.println("<center><p><h2><b>Name :" + name + "</p>");
out.println("<p><b>Reg No :" + reg + "</p>");
out.println("<p><b>Your Mark Details</p><br><br></center>");
out.println("<center><table border=2 cellpadding=5 cellspacing=5>");
out.println("<tr><th>Subjects</th><th>Mark</th><th>Grade</th></tr>");
out.println("<tr><th>Sub1</th><td>"+s1 + "</td><td>" + display(s1) + "</td></tr>");
out.println("<tr><th>Sub2</th><td>"+s2 + "</td><td>"  + display(s2) + "</td></tr>");
out.println("<tr><th>Sub3</th><td>"+s3 + "</td><td>"  + display(s3) + "</td></tr>");
out.println("<tr><th>Sub4</th><td>"+s4 + "</td><td>"  + display(s4) + "</td></tr>");
out.println("<tr><th>Sub5</th><td>"+s5 + "</td><td>"  + display(s5) + "</td></tr>");
out.println("<tr><th>Sub6</th><td>"+s6 + "</td><td>"  + display(s6) + "</td></tr></table>");
out.println("</body>");
out.println("</html>");
        } finally {
            out.close();
        }

    }

    /** Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    /** Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    /** Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }

Note

Some parts of the code will be automatically generated by Netbeans itself. So you need not worry.

Screenshots




Tuesday, January 25, 2011

Color Paletter using Sliders

To implement a color palette using a Slider. Here we use three sliders for Red, Blue and Green. Based on the slide value the Redness, Greenness and Blueness gets adjusted and thereby we can bring about all colors.

Download Source Code

Code

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JScrollBar;
import java.applet.*;

public class Slide extends Applet
{
    JScrollBar scroll;
    JScrollBar scroll1;
    JScrollBar scroll2;
    JLabel lbl1;
    JLabel lbl2;
    JLabel lbl3;
    JPanel panel1;
    JPanel panel2;
    JPanel panel3;
    JPanel panel;
    int redness=0;
    int greenness=0;
    int blueness=0;
   
    Color co;
   
    public void init()
    {
        scroll= new JScrollBar(JScrollBar.HORIZONTAL);
        scroll.setMaximum(265);
        scroll.addAdjustmentListener(new MyAdjustmentListener());
        scroll1= new JScrollBar(JScrollBar.HORIZONTAL);
        scroll1.setMaximum(265);
        scroll1.addAdjustmentListener(new MyAdjustmentListener());
        scroll2= new JScrollBar(JScrollBar.HORIZONTAL);
        scroll2.setMaximum(265);
        scroll2.addAdjustmentListener(new MyAdjustmentListener());
        lbl1 = new JLabel("Red");
        lbl2 = new JLabel("Green");
        lbl3 = new JLabel("Blue");
       
        panel = new JPanel();
        panel1 = new JPanel();
        panel2 = new JPanel();
        panel3 = new JPanel();
        panel1.setLayout(new BorderLayout());
        panel2.setLayout(new BorderLayout());
        panel3.setLayout(new BorderLayout());
       
        panel1.add(lbl1,BorderLayout.WEST);
        panel1.add(scroll);
       
        panel2.add(lbl2,BorderLayout.WEST);
        panel2.add(scroll1);
       
        panel3.add(lbl3,BorderLayout.WEST);
        panel3.add(scroll2);
       
        panel.setLayout(new BorderLayout());
        panel.add(panel1,BorderLayout.NORTH);
        panel.add(panel2,BorderLayout.CENTER);
        panel.add(panel3,BorderLayout.SOUTH);
        add(panel,BorderLayout.NORTH);
        setSize(300,300);
        setVisible(true);
    }
   
    class MyAdjustmentListener implements AdjustmentListener
    {
        public void adjustmentValueChanged(AdjustmentEvent e)
        {
            if(e.getSource()==scroll)
                redness = e.getValue();
            else if(e.getSource() == scroll1)
                greenness = e.getValue();
            else
                blueness = e.getValue();
            co=new Color(redness,greenness,blueness);
            setBackground(co);
            repaint();
        }
    }
}   
       
Screenshots







Color Palette using matrix of buttons in Applet

Let us create an applet that contains a matrix of buttons and when clicked the background will change accordingly.


Download the Source Code

Code for Applet

import java.io.*;
import java.applet.*;
import java.awt.event.*;
import java.awt.*;


public class matrixcolors extends Applet implements ActionListener
{
    Checkbox cf,cb;
    TextArea a;
    private Color color[]={Color.red,Color.blue,Color.cyan,Color.white,Color.black,Color.green,Color.gray,Color.lightGray,Color.darkGray,Color.yellow, Color.pink, Color.magenta,Color.orange};
    Button b[];
    Panel p1;
   
    public void init()
    {
        setLayout(new BorderLayout());
        p1=new Panel();
        b=new Button[13];
        for(int i=0;i
        {
            b[i]=new Button("");
            b[i].addActionListener(this);
            b[i].setBackground(color[i]);
            p1.add(b[i]);
        }
       
        cb=new Checkbox("Back Ground Color",true);
        cf=new Checkbox("Fore Ground Color",true);
        p1.add(cb);
        p1.add(cf);
        p1.setVisible(true);
        add(p1,BorderLayout.SOUTH);
        a=new TextArea("");
        add(a,BorderLayout.CENTER);
    }
    public void actionPerformed(ActionEvent e)
    {
        if(cb.getState())
        {
            for(int i=0;i
            {
                if(e.getSource() == b[i])
                    a.setBackground(color[i]);
            }
        }
        if(cf.getState())
        {
            for(int i=0;i
            {
                if(e.getSource()==b[i])
                    a.setForeground(color[i]);
            }
        }
    }
}

Screenshots


Wednesday, January 12, 2011

Validating Web Form Controls using DHTML

Question - Client Side Scripts for Validating Web Form Controls using DHTML.

Dynamic HTML, or DHTML, is an umbrella term for a collection of technologies used together to create interactive and animated web sites by using a combination of a static markup language (such as HTML), a client-side scripting language (such as JavaScript), a presentation definition language (such as CSS), and the Document Object Model.

I am going to create a simple HTML form where we validate the email Id..

First create the form, then using JavaScript we will validate the Email Id field, that is we will check if the user has entered a valid email id. Like if they leave @ or . we need to display to the user the error and make user they enter the proper format.

Here goes the code for the form,


<head>

<script type="text/javascript">

function validate_email(field)

{

with (field)

  {

  apos=value.indexOf("@");

  dotpos=value.lastIndexOf(".");

  len=value.length;

  if (apos<1||dotpos-apos<2||(len-dotpos)<2)

    {   document.getElementById('email_text').style.display = 'block';

    return false;}

  else

  {

  return true;}

  }

}

function validate_form(thisform)

{

with(thisform)

{

  if (validate_email(email)==false)

    {email.focus();return false;}

   alert("Registration Successful..Thank you!");   

}

}

</script>

</head>

Now we write the Javascript code to validate the email Id field,



<head>

<script type="text/javascript">

function validate_email(field)

{

with (field)

  {

  apos=value.indexOf("@");

  dotpos=value.lastIndexOf(".");

  len=value.length;

  if (apos<1||dotpos-apos<2||(len-dotpos)<2)

    {   document.getElementById('email_text').style.display = 'block';

    return false;}

  else

  {

  return true;}

  }

}

function validate_form(thisform)

{

with(thisform)

{

  if (validate_email(email)==false)

    {email.focus();return false;}

   alert("Registration Successful..Thank you!");   

}

}

</script>

</head>




Download the Source Code



Basically the script does the following,

The function above checks if the content has the general syntax of an email.
This means that the input data must contain at least an @ sign and a dot (.). Also, the @ must not be the first character of the email address, and the last dot must at least be one character after the @ sign. The by using "len-dotpos" we make sure that there are characters after those dot

So now we have created Client Side Scripts for Validating Web Form Controls using DHTML.

Friday, December 17, 2010

Creating Image Maps in HTML

Image Maps

In HTML and XHTML , an image map is a list of coordinates relating to a specific image, created in order to hyperlink areas of the image to various destinations (as opposed to a normal image link, in which the entire area of the image links to a single destination). For example, a map of the world may have each country hyperlinked to further information about that country. The intention of an image map is to provide an easy way of linking various parts of an image without dividing the image into separate image files.

Advantages of using Image Maps

  • Image maps can provide an aesthetically pleasing alternative to cluttered pages. 
  • The image map allows you to use a single image to provide links to a number of different URLs. This is especially useful if you have a website with a lot of images and you do not want to slow down the loading of pages over slow connections.  
Question

Create a web page with the following using HTML
  • To embed an image map in a web page.
  • To fix the hot spots.
  • Show all the related information when the hot spots are clicked.

Solution

I will explain the use of hotspots by using the map of India.


The basic syntax of Image Map is

    <img src="...." usemap="#mapname">

    .

    .

    .

    <map name = "mapname">

    <area shape="Shape" coords="..." href="..."

    </map>

where coords represents the coordinates of the shape of the hotpsot.

By usemap we specify the name of the map we have to use.

href specifies the link that the page has to navigate when the hotspot is clicked.

Now here Shape can be any one of the following,

  1. rect
  2. poly
  3. circle
rect
 
Rectangle has four coordinates. The first specifies the top left corner, and the second the bottom right corner of the rectangle.

<area shape="rect" COORDS="0,0,9,9">

circle

circle is defined by its center coordinate and its radius.

poly

A polygon is built up by a list of coordinates. They are all connected in the order you present, and the last coordinate pair is connected to the first. This way you can build arbitrary figures. For example, <area shape=poly coords="10,50,15,20,20,50"> would specify a triangle, with edge locations (10,50), (15,20) and (20,50).

Program

Now the example that I am going to demonstrate is to create an India Map and define hotspots for each state and when a state is clicked in the map the details of the state like capital, population and tourists places would be displayed.

Download the complete source code (recommended)

I will display a sample of the program alone here, you are recommended to download the full source code and see it for yourself.