Getting errors in servlet and display errors in jsp page

Thursday, February 25, 2010 Posted by Unknown
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:

Post a Comment