Dears,

This blog is moved to a new blog at:

The new update will be found at that new blog, please follow it!
This blog is no more updated.
Thanks for your visit!

Showing posts with label Web service. Show all posts
Showing posts with label Web service. Show all posts

Monday, September 23, 2013

Combination of Struts 1 and Web service in a Web application

Objective
We will learn how to create a Web application using Struts 1 and Web service. A case study will be illustrated as follow:
- a Web server running on Tomcat server.
- a Web page enabling user to enter two numbers and click submit to the server
- the server receives two numbers, then calls a Web service to calculate the sum of the two numbers. And then displays the results in another page.


Config Tomcat server for a Web service
 You could see in the topic: service-oriented programming with web service
- Step 1: Download Tomcat server from Apache site: http://tomcat.apache.org/download-70.cgi (version 6.0 and higher)
- Step 2: Download  web service (AXIS) library of Apache: http://axis.apache.org/axis/
- Step 3: unzip the axis folder, copy axis folder into Tomcat\webapps. And then copy xerces.jar from Tomcat\common\lib into Tomcat\webapps\axis\WEB-INF\lib



 - Step 4: setup your environment variables:
JAVA_HOME = absolute path to your java root directory
AXIS_HOME = absolute path to your unzipped axis folder
CATALINA_HOME = absolute path to your Tomcat folder
DEPLOY_HOME = {CATALINA_HOME}\webapps\axis\WEB-INF\lib


Create a Web service
- Step 5: Go to the directory: \Tomcat\webapps\axis, create a file named Calculators.jws with this content:

public class Calculators{
    public String Add(double x, double y){
        return (x+y)+"";
    }
   
    public String Sub(double x, double y){
        return (x-y)+"";
    }
   
    public String Mul(double x, double y){
        return (x*y)+"";
    }
   
    public String Div(double x, double y){
        return (x/y)+"";
    }
}

- Step 6: Verifying your Web service by running Tomcat server (run the file Tomcat\bin\startup.bat), then running your web browser and typing the URL into address bar:
http://localhost:8080/axis/Calculators.jws?wsdl
If this content appears, your Web service is well created!




Config and development a Web application using Struts 1 framework and Web service
- Step 1: Go to the Tomcat/webapps folder, create a web folder (strutCalculator) with a WEB-INF sub folder. In which, download the struts 1 lib into WEB-INF/lib folder:
link to download Struts 1 lib:http://mirrors.digipower.vn/apache//struts/library/struts-1.3.10-lib.zip



- Step 2: Go to the WEB-INF/src folder, create a Java project with two packages: control, entity. And then code them as:

entity.Calculator.java
package entity;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

public class Calculator extends org.apache.struts.action.ActionForm{
    private String firstnumber;
    private String secondnumber;
    private String result;
   
    public Calculator(){
        super();
    }
   
    public Calculator(String a, String b){
        super();
        firstnumber = a;
        secondnumber = b;
    }

    public String getFirstnumber() {
        return firstnumber;
    }

    public void setFirstnumber(String firstnumber) {
        this.firstnumber = firstnumber;
    }

    public String getSecondnumber() {
        return secondnumber;
    }

    public void setSecondnumber(String secondnumber) {
        this.secondnumber = secondnumber;
    }

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }
   
    public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
        ActionErrors errors = new ActionErrors();
        if (firstnumber == null || firstnumber.length() < 1) {
            errors.add("firstnumber", new ActionMessage("error.firstnumber.required"));
        }else {
            try{
                Double.parseDouble(firstnumber);
            }catch(Exception e){
                errors.add("firstnumber", new ActionMessage("error.firstnumber.double"));
            }
        }
        if (secondnumber == null || secondnumber.length() < 1) {
            errors.add("secondnumber", new ActionMessage("error.secondnumber.required"));
        }else {
            try{
                Double.parseDouble(secondnumber);
            }catch(Exception e){
                errors.add("secondnumber", new ActionMessage("error.secondnumber.double"));
            }
        }
        return errors;
    }
}



control.CalculatorCtr.java
package control;
import org.apache.axis.client.Service;
import org.apache.axis.client.Call;
import org.apache.axis.encoding.XMLType;
import javax.xml.rpc.ParameterMode;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;

public class CalculatorCtr extends org.apache.struts.action.Action{
    private final static String RESULT = "result";
   
    public entity.Calculator calculate(String methodName, entity.Calculator cal){
        String endpointURL="http://localhost:8080/axis/Calculator.jws";
        Service service=new Service();
                try{
                    Call call=(Call)service.createCall();
                    call.setTargetEndpointAddress(new java.net.URL(endpointURL));
                    call.setOperationName(methodName);
                    call.addParameter("a", XMLType.XSD_DOUBLE, ParameterMode.PARAM_MODE_IN);
                    call.addParameter("b", XMLType.XSD_DOUBLE, ParameterMode.PARAM_MODE_IN);
                    String result=(String)call.invoke(new Object[]{Double.parseDouble(cal.getFirstnumber()),Double.parseDouble(cal.getSecondnumber())});
                    cal.setResult(result);
                }catch(Exception ex){
                    System.out.println("Error: "+ex);
                }
         return cal;      
    }
   
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        entity.Calculator calculator = (entity.Calculator) form;
        form = calculate("Add", calculator);
        return mapping.findForward(RESULT);       
    }
}


After compiling these  packages, copy the .class files (including their packages) into the WEB-INF/classes folder.

- Step 3: Return to the Web root directory, create three files .jsp as follow:




add.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<!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>Web service: Add</title>
    </head>
    <body>
        <div style="color:red">
            <html:errors />
        </div>
        <html:form action="/add" >
            First number : <html:text name="Calculator" property="firstnumber" /> <br>
            Second number  : <html:text name="Calculator" property="secondnumber" /> <br>
            <html:submit value="Add" />
        </html:form>
    </body>
</html>

Note that the tags in red are Struts 1 tags, refer from the first line in red.

doAdd.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<!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>Web service: Add result</title>
    </head>
    <body>
        The sum of <bean:write name="Calculator" property="firstnumber"></bean:write>
        and <bean:write name="Calculator" property="secondnumber"></bean:write>
        is <bean:write name="Calculator" property="result"></bean:write>
    </body>
</html>

- Step 4: Go to the WEB-INF folder, copy all .tld and .xml file from Struts 1 lib into this directory as follow:



- Step 5: Edite the file web.xml and struts-config.xml as follow:

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>action</servlet-name>
        <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
        <init-param>
            <param-name>config</param-name>
            <param-value>/WEB-INF/struts-config.xml</param-value>
        </init-param>
        <init-param>
            <param-name>debug</param-name>
            <param-value>2</param-value>
        </init-param>
        <init-param>
            <param-name>detail</param-name>
            <param-value>2</param-value>
        </init-param>
        <load-on-startup>2</load-on-startup>
        </servlet>
    <servlet-mapping>
        <servlet-name>action</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>add.jsp</welcome-file>
        </welcome-file-list>
    <jsp-config>
        <taglib>
            <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
            <taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
        </taglib>
        <taglib>
            <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
            <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
        </taglib>
        <taglib>
            <taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
            <taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
        </taglib>
        <taglib>
            <taglib-uri>/WEB-INF/struts-nested.tld</taglib-uri>
            <taglib-location>/WEB-INF/struts-nested.tld</taglib-location>
        </taglib>
        <taglib>
            <taglib-uri>/WEB-INF/struts-tiles.tld</taglib-uri>
            <taglib-location>/WEB-INF/struts-tiles.tld</taglib-location>
        </taglib>
        </jsp-config>
    </web-app>

Note that all texts in red are the content you need to modify to be appropriated to your Web application.

struts-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
          "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">

<struts-config>
    <form-beans>
        <form-bean name="Caculator" type="entity.Caculator"/>   
    </form-beans>
   
    <global-exceptions>   
    </global-exceptions>

    <global-forwards>
        <forward name="welcome"  path="/Welcome.do"/>
    </global-forwards>

    <action-mappings>
        <action input="/add.jsp" name="Caculator" path="/add" scope="session" type="control.CalculatorCtr">
            <forward name="result" path="/doAdd.jsp" />
        </action>
        <action path="/Welcome" forward="/welcomeStruts.jsp"/>
    </action-mappings>
   
    <controller processorClass="org.apache.struts.tiles.TilesRequestProcessor"/>

    <message-resources parameter="entity/ApplicationResource"/>
   
    <!-- ========================= Tiles plugin ===============================-->
        <plug-in className="org.apache.struts.tiles.TilesPlugin" >
        <set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml" />
        <set-property property="moduleAware" value="true" />
    </plug-in>
   
    <!-- ========================= Validator plugin ================================= -->
    <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
        <set-property
            property="pathnames"
            value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
    </plug-in> 
</struts-config>

Note that all texts in red are the content you need to modify to be appropriated to your Web application.

Results
- add welcome page:


- result page:


- when entering incorrect data type: