Getting errors in servlet and display errors in jsp page

Thursday, February 25, 2010 Posted by Jagadeesh Manne 0 comments
in this post we will learn how to call validate class method and how to send values from servlet
to that method and how to get errors to servlet and how to display errors in jsp page


import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.UserBean;
import validation.ValidateForm;

/**
*
* @author Jagadeesh
*/

public class ControllerServlet extends HttpServlet {

//declare values to get form values from jsp page
String userName;
String dateOfBirth;
String email;
String phoneNo;
String action;

UserBean bean = new UserBean();
ValidateForm validateform = new ValidateForm();

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
//get the values from jsp page
userName = request.getParameter("userName");
dateOfBirth = request.getParameter("dateOfBirth");
email = request.getParameter("email");
phoneNo = request.getParameter("phoneNo");
action = request.getParameter("action");
if(action.equals("submit"))
{
//set values to bean.For this call below method
setValuesToBean();

//check all form values are valid or not. send bean object
UserBean checkedbean = validateform.validateData(bean);
if(!checkedbean.getIsValid())
{
//if data is invalid.set bean object in request and pass that request to
//insertupdate.jsp using forward
checkedbean.setAction("submit");
request.setAttribute("error",checkedbean);
RequestDispatcher rd = request.getRequestDispatcher("insertupdate.jsp");
rd.forward(request, response);
//now display errors in that jsp page
}
}
}
catch(Exception e)
{
out.println(e);
}
finally {
out.close();
}
}
//this method is used to setvalues to bean
public void setValuesToBean()
{
bean.setUserName(userName);
bean.setDateOfBirth(dateOfBirth);
bean.setEmail(email);
bean.setPhoneNo(phoneNo);

}

in this servlet we validate all values by calling validatedata() and if it is invalid we forward
errors to insertupdate.jsp page . we set that bean object in request and we forward page using RequestDispatcher.

in next post we will learn how to display errors in jsp page
Labels:

Validating form values

Posted by Jagadeesh Manne 0 comments
in this post we will create methods for validate form values and set errors to bean if those values are invalid.
now create methods.

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package validation;
import model.UserBean;
/**
*
* @author Jagadeesh
*/
public class ValidateForm {


UserBean validBean = new UserBean();
public UserBean validateData(UserBean ubean)
{

//if given username value is not valid then seterror
// message and set empty value to input field
if(ubean.getUserName().length()==0)
{
validBean.setUserNameError("please enter valid name");
validBean.setIsValid(false);
validBean.setUserName("");
}
else
if(!ubean.getUserName().matches("[a-zA-Z]*"))
{
validBean.setUserNameError("please enter valid name");
validBean.setIsValid(false);
validBean.setUserName("");

}
//if given username value is valid then seterror message to
// empty and set value to bean
else
{
validBean.setUserNameError("");
validBean.setIsValid(true);
validBean.setUserName(ubean.getUserName());
}


//if given username value is not valid then seterror message
// and set empty value to input field
if(!ubean.getDateOfBirth().matches("\\d{1,2}-\\d{1,2}-\\d{4}"))
{
validBean.setDateOfBirthError("please enter valid date");
validBean.setIsValid(false);
validBean.setDateOfBirth("");

}
//if given username value is valid then seterror message
// to empty and set value to bean
else
{
validBean.setDateOfBirthError("");
validBean.setIsValid(true);
validBean.setDateOfBirth(ubean.getDateOfBirth());
}


//if given username value is not valid then seterror message 
//and set empty value to input field

if(!ubean.getEmail().matches("^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$"))
{
validBean.setEmailError("please enter valid email");
validBean.setIsValid(false);
validBean.setEmail("");
}
//if given username value is valid then seterror message
//to empty and set value to bean
else
{
validBean.setEmailError("");
validBean.setIsValid(true);
validBean.setEmail(ubean.getEmail());
}

//if given username value is not valid then seterror message
// and set empty value to input field
if(!ubean.getPhoneNo().matches("\\d{10}"))
{
validBean.setPhoneNoError("please enter valid phoneno");
validBean.setIsValid(false);
validBean.setPhoneNo("");
}
//if given username value is valid then seterror message to 
// empty and set value to bean
else
{
validBean.setPhoneNoError("");
validBean.setIsValid(true);
validBean.setPhoneNo(ubean.getPhoneNo());
}
return validBean;
}
}

Labels:

Creating Bean (Model)

Posted by Jagadeesh Manne 0 comments
In this post we will learn how to create a package in netbeans and how to create a class in that pakage.
Right click on source packages and select package



Enter package name(model in this example) and click next
now create a bean class with in this package. for this select that package and right click and select create and select class. and now enter name of that class.In this example that class name is UserBean. and click finish



then netbeans creates a class with default structure.

package model;

/**
*
* @author Jagadeesh
*/
public class UserBean {

}

now insert setter methods and getter methods in that been.Simple way to create setter methods and getter methods.
1. declare variables
2. select all variables and right click and click on insert code. select setter methods and getter methods and ok



then it will create setter and getter methods.
in this example i declared four variables for form values and five variables for display error messages.


package model;
package model;

/**
* @author Jagadeesh
*/
public class UserBean {

private String userName ;
private String dateOfBirth ;
private String email ;
private String phoneNo ;

//for validation error messages

private String userNameError;
private String dateOfBirthError;
private String emailError;
private String phoneNoError;
private boolean isValid;

//this is for action means edit or submit or delete or update
private String action;
//construtor.it is invoked when we run jsp page.
//so first time no values will display in jsp page
public UserBean()
{
userName ="";
dateOfBirth ="";
email="";
phoneNo="";

userNameError="";
dateOfBirthError="";
emailError="";
phoneNoError="";

action = "submit";
}

public String getDateOfBirth() {
return dateOfBirth;
}

public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getPhoneNo() {
return phoneNo;
}

public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

//setter and getter methods for errors

public String getUserNameError() {
return userNameError;
}

public void setUserNameError(String userNameError) {
this.userNameError = userNameError;
}
public String getDateOfBirthError() {
return dateOfBirthError;
}

public void setDateOfBirthError(String dateOfBirthError) {
this.dateOfBirthError = dateOfBirthError;
}

public String getEmailError() {
return emailError;
}

public void setEmailError(String emailError) {
this.emailError = emailError;
}

public String getPhoneNoError() {
return phoneNoError;
}

public void setPhoneNoError(String phoneNoError) {
this.phoneNoError = phoneNoError;
}

public boolean getIsValid() {
return isValid;
}
public void setIsValid(boolean isValid) {
this.isValid = isValid;
}

public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}

}


in next post we will create a class for validate form
Labels:

MVC Example using Jsp, Servlets and java beans

Posted by Jagadeesh Manne 10 comments
Hi everyone upto now we we have discussed about MVC architecture.many students and beginners are developing projects using servlets or jsp. But it is not good for further modifications of that project.First project i have done using jsp and mysql. i did not use servlets and MVC architecture. So i faced lot of problems to update or modify that project.after that one of my friend told me that is not good way to do project.he told me that better to use MVC. Using MVC we can know where we have to modify code. since we are using MVC we can know easily by following MVC pattern.

Softwares : netbeans, mysql, sqlyog, and editplus.
the aim of this example is developing User Management using MVC architecture in jsp and servlets and java beans and mysql. If you have any doubt while doing this example leave your comment.i am presenting here what ever i know. if any bugs or errors in this example give me  your suggestions to modify.if you want those softwares i will provide link.submit your comment below.now we will proceed first step.

flow of this example
1. creating insertupdate.jsp
2. creating servlet
3. creating bean package and bean class
4. creating database package and database class
5. insert data in insertupdate.jsp and submit
6. get data from insertupdate.jsp and set all values to bean object
7. validate data in servlet.if it is valid send bean object to database class and insert data into  
    database.
     a. create list.jsp page 
     b. show all records from database in list.jsp
8. if it is not valid send errors to insertupdate.jsp page and display errors of errorfileds.
9. now in list.jsp page select a record to update or delete.
10. in servlet get that request from list.jsp and check it is delete or update.
     a. if it is delete send id to database class and delete record.and show the message in list.jsp
      b. if it is update send id to database class and get the details about particular id and send 
        those values to insertupdate.jsp and display all fields in that jsp and modify fields to update 
        and submit
11. get the request from insertupdate.jsp page and send values to database using bean object 
      and update that record and display that message.


Overview of MVC                                                                Creating insertupdate.jsp(View)
Labels:

creating servlet

Tuesday, February 23, 2010 Posted by Jagadeesh Manne 0 comments

Right click on source packages.and select new and select servlet



Enter Servlet name and click next 



click next and finish

then netbeans creates default structure.
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;

/**
 * @author Jagadeesh
 */
public class ControllerServlet extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP GET 
    and POST methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
           
        } finally { 
            out.close();
        }
    } 

   
    /** 
     * Handles the HTTP GET method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP POST method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// 

}

upto now we created jsp page(View) and Servlet(Controller).In next post we will create bean(model).
for this we have to create one package and in that package we create one bean class.if you have any doubts upto now post your comment below

Creating insertupdate.jsp(View)                                                                         Creating Bean(Model)
Labels:

how to start project in netbeans

Monday, February 22, 2010 Posted by Jagadeesh Manne 0 comments
   start netbeans and goto file-->select new project and select web application and click next.



   enter your project name and select your project location


   select server tomcat and click next


    present we are not using framework so click finish.


   then netbeans  will create directorial structure like this.


in next post we will continue

MVC Example                                                                        Creating insertupdate.jsp(View)
Labels:

Creating insertupdate.jsp page

Posted by Jagadeesh Manne 0 comments
<%-- 
    Document   : index
    Author     : Jagadeesh
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!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=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <form method="post" action="ControllerServlet">
          <CENTER>
            <TABLE>
               <TR>
                 <TD>Name:</TD>
                 <TD>
                    <INPUT TYPE="text" NAME="userName">
                 </TD>
               </TR>
               <TR>
                 <TD>Date Of Birth:</TD>
                 <TD>
                    <INPUT TYPE="text" NAME="dateOfBirth">
                 </TD>
               </TR>
               <TR>
                 <TD>E-Mail</TD>
                 <TD>
                    <INPUT TYPE="text" NAME="email">
                 </TD>
               </TR>
               <TR>
                 <TD>Phone no:</TD>
                 <TD>
                    <INPUT TYPE="text" NAME="phoneNo">
                 </TD>
                </TR>
                <TR>
                  <TD colspan="2" align="center">
                    <INPUT TYPE="submit" value="submit" NAME="action>
                 </TD>
                </TR>
            </TABLE>
          </CENTER>
        </form>
    </body>
 </html>
if you run this form then following output will come



Creating project in netbeans                                                            Creating Servlet(Controller)
Labels:

MVC Overview

Friday, February 19, 2010 Posted by Jagadeesh Manne 0 comments
Model :


In the MVC architecture, model components provide an interface to the data and/or services used by an application. This way, controller components don't unnecessarily embed code for manipulating an application's data. Instead, they communicate with the model components that perform the data access and manipulation. Thus, the model component provides the business logic. Model components come in many different forms and can be as simple as a basic Java bean or as intricate as Enterprise JavaBeans (EJBs) or Web services.






View :
View components are used in the MVC architecture to generate the response to the browser. Thus, a view component provides what the user sees. Oftentimes the view components are simple JSPs or HTML pages. However, you can just as easily use WML, a templating engine such as Velocity or FreeMarker, XML with XSLT, or another view technology altogether for this part of the architecture. This is one of the main design advantages of MVC. You can use any view technology that you'd like without impacting the Model (or business) layer of your application.

Controller:
At the core of the MVC architecture are the controller components. The Controller is typically a servlet that receives requests for the application and manages the flow of data between the Model layer and the View layer. Thus, it controls the way that the Model and View layers interact. The Controller often uses helper classes for delegating control over specific requests or processes.

This information gathered from Complete Reference.

Why MVC ?
MVC separates business logic and presentation logic.So if you want to change your front end design you no need to change your back end code.if you want to change your back end you no need to change your front end.So it is very useful for updations of your project. and MVC also providing re-usability.If you want to change your project you just follow the pattern.

now we will see in next post an example of MVC architecture


MVC architecture                                                                                             MVC Example
Labels:

MVC architecture in Java

Posted by Jagadeesh Manne 1 comments

What is MVC architecture?

MVC is a Design pattern. MVC stands for Model View Controller.It contains two models.

1. MVC model 1 Architecture:
A request is made to a JSP and then that JSP handles all responsibilities for the request, including processing the request, validating data, handling the business logic, and generating a response.





2. MVC model 2 Architecture:
In this architecture a central servlet, known as the Controller, receive all requests for the application. The Controller then process the request and works with the Model to prepare any data needed by the View(JSP) and forwards the data to a JSP. The JSP then uses the data prepared by the Controller to generate a response to the browser.





Model - View - Controller:
In the MVC architecture, model components provide an interface to the data and/or services used by an application. This way, controller components don't unnecessarily embed code for manipulating an application's data. Instead, they communicate with the model components that perform the data access and manipulation. Thus, the model component provides the business logic. Model components come in many different forms and can be as simple as a basic Java bean or as intricate as Enterprise JavaBeans (EJBs) or Web services.

This information gathered from Complete Reference
Labels: