Saturday, May 22, 2010

MVC with mysql Servlet and JSP

In this example I will be creating a simple application in which I will transfer the control from main page to controller servlet where it will establish database connection and store the result to a bean class.It will put the object to the session attribute and then transfer the control to jsp page where the result will be displayed.

Lets create a Home Page called a.jsp under WebContents which contains a link. This link will redirect the flow to a.java file.
a.jsp
-----------------------------------------------------------------------------------------------------------









<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="a">click me</a>
</body>
</html>    
                                          


------------------------------------------------------------------------------------------------------------



 a.java

------------------------------------------------------------------------------------------------------------
package mit.mvc;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class a extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException
{
       PrintWriter out = response.getWriter();
       Connection con;
       ResultSet rs;
       DbBean bb=new DbBean();
       int[] id=new int[10];
      
       try
       {             con=DriverManager.getConnection("jdbc:mysql://localhost/student","root", "");
             
              Statement st=con.createStatement();
              rs=st.executeQuery("select * from stud");
              int i=0;
              while(rs.next())
              {             id[i]=Integer.parseInt(rs.getString("id"));
                     i++;
              }
             
              bb.setid(id);
       }catch(Exception e)
       {}
       HttpSession s=request.getSession();
       s.setAttribute("result", bb);
       RequestDispatcher dispatcher = request.getRequestDispatcher("c.jsp");
       dispatcher.forward(request, response);
}

public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException
{
       doGet(request,response);
}
}              
-------------------------------------------------------------------------------------------------------

Explanation : For this application to work we need to create a student database with stud table. stud table have id and name column.
This file simply creates database connection and creates and walk through the stud table and puts the id that is  fetched from the database into integer array id. After that DbBean class is initialized and its id attribute is set to the the id attribute of the servlets class. The initialized bean object is putted into session and the control is transfered to c.java

Lets see DbBean.java
------------------------------------------------------------------------------------------------------------------------









package mit.mvc;
import java.io.*;
public class DbBean {
     
      private int[] id=new int[10];
      public void setid(int[] id)
      {
            this.id=id;
      }
      public int getid(int i)
      {
            return id[i];
      }    
}          
----------------------------------------------------------------------------------------------------
c.java
----------------------------------------------------------------------------------------------------









<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@ page language="java" import="java.sql.*" %>

<%@page import="mit.mvc.DbBean"%><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<jsp:useBean id="result" scope="session" type="mit.mvc.DbBean"/>

<%=result.getid(1) %>

</body>
</html>

Struts2 Login

Here I am going to simple login application using struts2.

First create a dynamic web project.

Jar files that are used required :
you can download jar files from here.

Lets modify the web.xml File. Location of the file is : WebContent/WEB-INF
-------------------------------------------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>test1</display-name>
   <filter>
  <filter-name>struts2</filter-name>
  <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
  </filter>
   <filter-mapping>
   <filter-name>struts2</filter-name>
   <url-pattern>/*</url-pattern>
    </filter-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
-------------------------------------------------------------------------------------------------------------



Now Lets create index.jsp under WebContent directory
Copy and paste the following code :
-------------------------------------------------------------------------------------------------------------
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<s:form action="loadMitesh">
<s:textfield label="User Name" name="userName"></s:textfield>
<s:submit name="submit"></s:submit>
</s:form>
</body>
</html>
-------------------------------------------------------------------------------------------------------------


Note : Here loadMitesh is the logical name that is mapped by struts.xml file by the actual file name.
Now lets create struts.xml file  This file should be created under the src folder.

-------------------------------------------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
    "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
        <package name="Mitesh" namespace="/" extends="struts-default">
        <action name="displayLogin">
        <result>/index.jsp</result>
        </action>
        <action name="loadMitesh" class="org.mitesh.miteshAction">
                        <result name="success">/welcome.jsp</result>
                        <result name="error">/goout.jsp</result>
                </action>
        </package>
</struts>
-------------------------------------------------------------------------------------------------------------


Here org.mitesh.miteshAction is fully classified name of the java class that is to be executed when action name is loadMitesh. So, This is called when the form is submitted.
miteshAction contains execute() method that is executed and based on the user name provided it will return success or error. And according to that flow of program will go ahead.

Lets see miteshAction.java

create a package org.mitesh under src directory and create a class miteshAction.java.

-------------------------------------------------------------------------------------------------------------
package org.mitesh;
import com.opensymphony.xwork2.ActionSupport;
public class miteshAction extends ActionSupport{
private String userName;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
System.out.println("setting user name : " + userName);
this.userName = userName;
}
public String execute() {
if(userName.equals("mitesh"))
{
return SUCCESS;
}
else
{
System.out.println("in else");
return "error";
}
}
}
-------------------------------------------------------------------------------------------------------------


when the user will submit the user name as mitesh the execute method will return SUCCESS that is caught by strut.xml's result under

<action name="loadMitesh" class="org.mitesh.miteshAction"> 
                         
                        <result name="success">/welcome.jsp</result>
                        <result name="error">/goout.jsp</result> 
</action>

 and the control will go to welcome.jsp



Lets see welcome.jsp
-------------------------------------------------------------------------------------------------------------

this file uses struts property tag to display the userName value that is set in miteshAction class.

if user name is wrong execute() method will return error and the  control will transfer to goout.jsp
lets see goout.jsp  


-------------------------------------------------------------------------------------------------------------
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Sorry Wrong User Name
<a href="displayLogin">Try Again</a>
</body>
</html>
-------------------------------------------------------------------------------------------------------------

here I have provided link with logical name displayLogin which will be mapped by struts.xml file to index.jsp

<action name="displayLogin">
        <result>/index.jsp</result>
</action>


right click on the project and run it........


Final directory structure :