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




Thursday, February 3, 2011

Reg: OOAD Lab Experiments

For all those who been mailing me for the past one month regarding the OOAD Lab exercises, I couldn't complete my work on  it and it would take some more time to upload the use case diagrams and other stuffs.

I regret for the inconvenience caused by the delay.

Stay tuned for updates.

With Regards,
G.Vivek Venkatesh






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.