Saturday, May 22, 2010

Simple MVC using jsp and servlets.



MVC (Model, View , Controller)

Here I am going to create 4 files. 
1)Test1.jsp will simpley containg a link that will transfet control to controller servlet testBeanServlet.java
2)testBeanServlet.java will create an object of testBean class and set private member x by calling setX() method.
3)Then it will put this oblect to session variable and then forward the request to Test.jsp file.
4)Test.jsp file will use the getProperty method to display the value.

Here is the code : 


Test1.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="testBeanServlet">hiii</a>
</body>
----------------------------------------------------------------------------------




testBeanServlet.java

----------------------------------------------------------------------------------
package org.javatrainer;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class testBeanServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
testBean b=new testBean();
b.setX(10);
HttpSession s=request.getSession();
s.setAttribute("value", b);
RequestDispatcher dispatcher =
      request.getRequestDispatcher("test.jsp");
      dispatcher.forward(request, response);
}
}         
-------------------------------------------------------------------------------------------------------------




testBean.java
----------------------------------------------------------------------------------
package org.javatrainer;

public class testBean {
     
      private int x;
     
      public void setX(int x)
      {
            System.out.println("hi");
       this.x=x;
       System.out.println(x);
      }
      public int getX()
      {
            return x;

}
}
-----------------------------------------------------------------------------------------------------------------------------------





Test.jsp


----------------------------------------------------------------------------------
<html>
<head>

<title>Insert title here</title>
</head>
<body>

<jsp:useBean id="value" type="org.javatrainer.testBean" scope="session" />

<jsp:getProperty name="value" property="x"/>

</body>
</html>
-----------------------------------------------------------------------------------------------------------------------------------





No comments:

Post a Comment