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!

Monday, September 23, 2013

Web developing using Struts 1 framework

Objective
We will learn how to develop a Web application using Struts 1 framework. This lesson will be illustrated with example of login:
- a Web server running on Tomcat server. This Web server manages a DB containing a table named users which includes at least two columns username, password.
- a login page enabling user to enter username/password and click submit to the server
- the server verifies the login information and return the results on another page: If login success, it forwards to the user's home page. Otherwise, it displays a warning that username/password is incorrect!

Config and development a Web application using Struts 1 framework
- Step 1: Go to the Tomcat/webapps folder, create a web folder 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 three packages: control, dao, entity. And then code them as:

entity.User.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;

/**
 *
 * @author
 */
public class User extends org.apache.struts.action.ActionForm {   
    private String username;
    private String password;
   
    /**
     *
     */
    public User() {
        super();
    }
   
    public User(String x, String y) {
        super();
        username = x;
        password = y;
    }

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param request The HTTP Request we are processing.
     * @return
     */
    public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
        ActionErrors errors = new ActionErrors();
        if (username == null || username.length() < 1) {
            errors.add("userName", new ActionMessage("error.username.required"));
            // TODO: add 'error.name.required' key to your resources
        }
        if (password == null || password.length() < 1) {
            errors.add("password", new ActionMessage("error.password.required"));
            // TODO: add 'error.name.required' key to your resources
        }
        return errors;
    }

    /**
     * @return the userName
     */
    public String getUsername() {
        //System.out.println("Inside getter "+username);
        return username;
    }

    /**
     * @param userName the userName to set
     */
    public void setUsername(String userName) {
        //System.out.println("Inside setter "+userName);
        this.username = userName;
    }

    /**
     * @return the password
     */
    public String getPassword() {
        return password;
    }

    /**
     * @param password the password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }
}

dao.UserDAO.java
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDAO {
    Connection conn = null;
   
    public UserDAO() {
        String dbUsername = "sa";
        String dbPassword = "sa";
        String dbUrl = "jdbc:mysql://localhost:3306/hotelmanagement";
        String dbClass = "com.mysql.jdbc.Driver";

        try {

            Class.forName(dbClass);
            conn = DriverManager.getConnection (dbUrl, dbUsername, dbPassword);

        }catch(ClassNotFoundException e) {
            e.printStackTrace();
        }

        catch(SQLException e) {
            e.printStackTrace();
        }
      }

    public boolean checkLogin(entity.User user){       
        String query = "Select * FROM users WHERE username = ? AND password = ?";
        try {
            PreparedStatement ps = conn.prepareStatement(query);
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
       
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                return true;
            }
        }catch(SQLException e) {
            e.printStackTrace();
        }
        return false;
    }
}


control.LoginAction.java
package control;
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 LoginAction extends org.apache.struts.action.Action {

    /* forward name="success" path="" */
    private final static String SUCCESS = "success";
    private final static String FAILURE = "failure";
    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        entity.User loginForm = (entity.User) form;
        dao.UserDAO userDAO = new dao.UserDAO();
        if (userDAO.checkLogin(loginForm)) {
            return mapping.findForward(SUCCESS);
        } else {
            return mapping.findForward(FAILURE);
        }
    }
}

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:



login.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>JSP Page</title>
    </head>
    <body>
        <div style="color:red">
            <html:errors />
        </div>
        <html:form action="/Login" >
            User Name : <html:text name="User" property="username" /> <br>
            Password  : <html:password name="User" property="password" /> <br>
            <html:submit value="Login" />
        </html:form>
    </body>
</html>

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

success.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>JSP Page</title>
    </head>
    <body>
        <h1>Login Success. Welcome <bean:write name="User" property="username"></bean:write></h1>
    </body>
</html>


failure.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>JSP Page</title>
    </head>
    <body>
        <div style="color:red">
            <h1>Invalid user name  <bean:write name="User" property="username"></bean:write> or password!</h1>
        </div>
    </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>login.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="User" type="entity.User"/>   
    </form-beans>
   
    <global-exceptions>   
    </global-exceptions>

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

    <action-mappings>
        <action input="/login.jsp" name="User" path="/Login" scope="session" type="control.LoginAction">
            <forward name="success" path="/success.jsp" />
            <forward name="failure" path="/failure.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
- login page:



- when login successful:



- when login failed:




No comments:

Post a Comment