4/14/2012

J2EE#3 JSP + Struts MVC + Service + DAO + JDBC (Oracle) + SP (1)

Reference : http://struts.apache.org/
The Apache Struts web framework is a free open-source solution for creating Java web applications.
Web applications differ from conventional websites in that web applications can create a dynamic response. Many websites deliver only static pages. A web application can interact with databases and business logic engines to customize a response.
Web applications based on JavaServer Pages sometimes commingle database code, page design code, and control flow code. In practice, we find that unless these concerns are separated, larger applications become difficult to maintain.
One way to separate concerns in a software application is to use a Model-View-Controller (MVC) architecture. The Model represents the business or database code, the View represents the page design code, and the Controller represents the navigational code. The Struts framework is designed to help developers create web applications that utilize a MVC architecture.
The framework provides three key components:
  • A "request" handler provided by the application developer that is mapped to a standard URI.
  • A "response" handler that transfers control to another resource which completes the response.
  • A tag library that helps developers create interactive form-based applications with server pages.

Now we build project "Sample02" to realize:

JSP + Struts MVC + Service + DAO + JDBC (Oracle) + SP

First, we new the project, and then add all the libraries it needs to directory "Web Content=>WEB-INF=>lib"
Needed Jar files:
ojdbc14.jar, antlr.jar, commons-beanutils.jar, commons-digester.jar, commons-fileupload.jar, commons-logging.jar, commons-validator.jar, jakarta-oro.jar, struts.jar

Now we can start building the back end part. We can see that the Service + DAO + JDBC + SP parts do not change, so we can copy the three packages "com.company.beans", "com.company.service" and "com.company.daos" in Sample01 to Sample02. The packages can not be copied directly, so we need to new the packages first and copy the files.


Modify the Javabeans file "User.java" to extend "ActionForm":


01 package com.company.beans;
02 import org.apache.struts.action.ActionForm;
03
04 @SuppressWarnings("serial")
05 public class User extends ActionForm{
06
07     private String name;
08     private int age;
09     public String getName() {
10         return name;
11     }
12     public void setName(String name{
13         this.name = name;
14     }
15     public int getAge() {
16         return age;
17     }
18     public void setAge(int age{
19         this.age = age;
20     }
21 }

Now we should add actions into project. Create new package "com.company.actions", and create "HelloAction.java" under that package with code:


01 package com.company.actions;
02
03 import javax.servlet.http.HttpServletRequest;
04 import javax.servlet.http.HttpServletResponse;
05 import org.apache.struts.action.Action;
06 import org.apache.struts.action.ActionForm;
07 import org.apache.struts.action.ActionForward;
08 import org.apache.struts.action.ActionMapping;
09 import com.company.beans.User;
10 import com.company.services.HelloService;
11
12 public class HelloAction extends Action {
13
14     private HelloService hs;
15 
16     public HelloAction(){
17         super();
18         if(hs==null){
19             hs = new HelloService();
20         }
21     }
22     @Override
23     public ActionForward execute (ActionMapping mapping, ActionForm form,
24             HttpServletRequest request, HttpServletResponse response){
25         User user = (Userform;  // downcast 
26         request.setAttribute("userInfo", hs.process(user));
27         return mapping.findForward("result"); //forward
28     }
29 }



Next step we need to modify "Web.xml" and create "struts-config.xml" under "WebContent":


Web.xml:


01 <?xml version="1.0" encoding="ISO-8859-1"?>
02 <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
03   "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
04 <web-app>
05     <display-name>Sample02</display-name>
06     <servlet>
07         <servlet-name>action</servlet-name>
08            <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
09            <init-param>
10             <param-name>config</param-name>
11             <param-value>/WEB-INF/struts-config.xml</param-value>
12            </init-param>
13              <init-param>
14                  <param-name>debug</param-name>
15                  <param-value>1</param-value>
16              </init-param>
17              <init-param>
18                  <param-name>detail</param-name>
19                  <param-value>1</param-value>
20         </init-param>
21         <load-on-startup>1</load-on-startup>
22     </servlet>
23     <servlet-mapping>
24         <servlet-name>action</servlet-name>
25         <url-pattern>*.do</url-pattern>
26     </servlet-mapping>
27     <welcome-file-list>
28         <welcome-file>index.jsp</welcome-file>
29     </welcome-file-list>
30 </web-app>


struts-config.xml:
01 <?xml version="1.0" encoding="UTF-8"?>
02 <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">
03 <struts-config>
04     <form-beans>
05         <form-bean name="userForm" type="com.mercury.beans.User"/>
06     </form-beans>
07     <action-mappings>
08         <action name="userForm" path="/hello" type="com.mercury.actions.HelloAction"
09             scope="request" input="/hello.jsp">
10             <forward name="result" path="/result.jsp" />
11         </action>
12          <action path="/index" type="org.apache.struts.actions.ForwardAction"
13             parameter="/hello.jsp">
14         </action>
15     </action-mappings>
16 
</struts-config>    




Now we copy the "hello.jsp" and "result.jsp" from Sample01 to Sample02.
In hello.jsp, we need to modify the code to use struts html tag, bean tag and logic tag.
Also, we should add validation. Create a new package in src with name "com.company.validate". In the package, create a File "ApplicationResources.properties"


hello.jsp:


01 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
02     pageEncoding="ISO-8859-1"%>
03 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
04 <%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
05 <%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
06
07 <html>
08 <head>
09 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
10 <title>Hello Page</title>
11 <style type = "text/css">
12     .error {color:red}
13 </style>
14
15 </head>
16
17 <body>
18 <h2><font color="blue">Sample02: JSP + Struts MVC + Service + DAO + JDBC + SP</font></h2>
19 <p class="error"><html:messages id="errors">
20     <bean:write name="errors" />
21 </html:messages></p>
22
23 <html:form action="/hello">
24     <table>
25         <tr>
26             <td><bean:message key="user.name" /></td>
27             <td><html:text property="name" /></td>
28         </tr>
29         <tr>
30             <td><bean:message key="user.age" /></td>
31             <td><html:text property="age" value="" /></td>
32         </tr>
33         <tr>
34             <td></td>
35             <td><html:reset value="Clear" /> <html:submit value="Submit" />
36             </td>
37         </tr>
38     </table>
39 </html:form>
40 </body>
41 </html>



result.jsp:
01 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
02     pageEncoding="ISO-8859-1"%>
03 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
04 <%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
05 <%@taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
06
07 <html>
08 <head>
09 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
10 <title>Insert title here</title>
11 </head>
12 <body>
13 <jsp:useBean id = "userInfo" scope= "request" class = "com.company.beans.UserInfo"/>
14
15     <h2><font color="blue"><jsp:getProperty name = "userInfo" property = "msg"/></font></h2>
16    
17     <table width = "200" border = "1">
18     <tr>
19         <th><bean:message key = "user.name"/></th>
20         <th><bean:message key = "user.age"/></th>
21     </tr>
22     <logic:iterate id="user" name="userInfo" property="users"
23         type="com.company.beans.User" scope="request">
24             <tr>
25                 <td><bean:write name="user" property="name"/></td>
26                 <td><bean:write name="user" property="age"/></td>
27             </tr>
28     </logic:iterate>
29
30     </table>
31    
32 </body>
33 </html>



ApplicationResources.properties


1 #User Information
2 user.name=User Name
3 user.age=User Age
4
5 #Error message
6 error.name = Invalid name
7 error.age = Invalid age



Modify "User.java"


01 package com.company.beans;
02 import javax.servlet.http.HttpServletRequest;
03
04 import org.apache.struts.action.ActionErrors;
05 import org.apache.struts.action.ActionMapping;
06 import org.apache.struts.action.ActionMessage;
07 import org.apache.struts.validator.ValidatorForm;
08
09 @SuppressWarnings("serial")
10 public class User extends ValidatorForm{
11
12     private String name;
13     private int age;
14     public String getName() {
15         return name;
16     }
17     public void setName(String name{
18         this.name = name;
19     }
20     public int getAge() {
21         return age;
22     }
23     public void setAge(int age{
24         this.age = age;
25     }
26    
27     @Override
28     public ActionErrors validate(ActionMapping mapping, HttpServletRequest request{
29         ActionErrors actionErrors = new ActionErrors();
30         if (name==null || name.length()<3{
31             actionErrors.add("name", new ActionMessage("error.name"));
32         }
33         if (age<=0{
34             actionErrors.add("age", new ActionMessage("error.age"));
35         }
36         return actionErrors;
37         }
38    
39 }



Now we are done! We can run the "Hello.jsp" to test the project. It works fine.

No comments:

Post a Comment