Struts

Configuration
  • We need struts2-core dependency.
  • Setup your basic pom.xml as follows
    •  <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
        <modelVersion>4.0.0</modelVersion>  
        <groupId>com.javaimplant</groupId>  
        <artifactId>SocialNetwork</artifactId>  
        <version>0.0.1-SNAPSHOT</version>  
        <packaging>jar</packaging>  
        <name>SocialNetwork</name>  
        <url>http://maven.apache.org</url>  
        <properties>  
         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
        </properties>  
        <dependencies>  
         <dependency>  
          <groupId>junit</groupId>  
          <artifactId>junit</artifactId>  
          <version>3.8.1</version>  
          <scope>test</scope>  
         </dependency>  
         <dependency>  
              <groupId>org.apache.struts</groupId>  
              <artifactId>struts2-core</artifactId>  
              <version>2.5.22</version>  
         </dependency>  
         <dependency>  
              <groupId>mysql</groupId>  
              <artifactId>mysql-connector-java</artifactId>  
              <version>8.0.19</version>  
         </dependency>  
         <dependency>  
              <groupId>org.hibernate</groupId>  
              <artifactId>hibernate-core</artifactId>  
              <version>6.0.0.Alpha4</version>  
         </dependency>  
         <dependency>  
              <groupId>org.hibernate</groupId>  
              <artifactId>hibernate-entitymanager</artifactId>  
              <version>6.0.0.Alpha4</version>  
         </dependency>  
        </dependencies>  
       </project>  
      
  • To create a configurable web.xml for struts
    • Create a filter in web.xml
    • Create a filter mapping
    • We are offloading all of our requests that come in the tomcat(web.xml) to struts2
    • Struts2 passes it to the StrutsPrepareAndExecuteFilter.
    • This filter then executes request based on struts code written
    •  <?xml version="1.0" encoding="UTF-8"?>  
       <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0">  
        <display-name>SocialNetwork</display-name>  
        <welcome-file-list>  
         <welcome-file>index.jsp</welcome-file>  
        </welcome-file-list> .
        <filter>  
             <filter-name>Struts2</filter-name>  
             <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>  
        </filter>  
        <filter-mapping>  
             <filter-name>Struts2</filter-name>  
             <url-pattern>/*</url-pattern>  
        </filter-mapping>  
       </web-app>  
      
  • We will be using xml based configuration here since annotation based is not much supported in Struts.
  • For this we will create 2 xml files for Struts and Hibernate configuration as follows
  • Make sure you copy mapping as defined on top of both of these files .
  • Struts.xml
    •  <?xml version="1.0" encoding="UTF-8"?>  
       <!DOCTYPE struts PUBLIC  
         "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
         "http://struts.apache.org/dtds/struts-2.0.dtd">  
       <struts>  
       </struts>  
      
  • hibernate.cfg.xml
    •  <?xml version="1.0" encoding="UTF-8"?>  
       <!DOCTYPE hibernate-mapping PUBLIC   
       "-//Hibernate/Hibernate Mapping DTD//EN"  
       "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">  
      
Struct Action
    • We configure the action in struts.xml class.
      • We configure the action with name property.
      • This property defines the name of the action that will be passed to url with an extension ".action".
    • Create a class and define method "execute" in it which will return a String.
      • The jsp to be called based on String is configured in struts.xml file based on the response from the execute method.
    struts.xml
     <?xml version="1.0" encoding="UTF-8"?>  
     <!DOCTYPE struts PUBLIC  
       "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
       "http://struts.apache.org/dtds/struts-2.0.dtd">  
     <struts>  
               <package name="AccountSystem" extends="struts-default">  
                    <action name="login" class="com.javaimplant.socialnetwork.action.LoginAction">  
                         <result name="success">/loginSuccess.jsp</result>  
                    </action>  
               </package>  
     </struts>  
    
    LoginAction.java
     package com.javaimplant.socialnetwork.action;  
     public class LoginAction {  
          public String execute() {  
               System.out.println("We are executing login action!");  
               return "success";  
          }  
     }  
    

    Action Class
    • The action classes contain the Business Logic of the application.
    • The class has predefined methods and constants that can be overridden to support more enhanced functionality in Business Logic.
      • Functions such as validate and execute
     package com.javaimplant.socialnetwork.action;  
     import com.javaimplant.socialnetwork.model.User;  
     import com.opensymphony.xwork2.ActionSupport;  
     public class LoginAction extends ActionSupport {  
          private static final long serialVersionUID = 1L;  
          private User user;  
          @Override  
          public void validate() {  
          }  
          @Override  
          public String execute() {  
               System.out.println("We are executing login action!");  
               System.out.println(user.getUserName());  
               System.out.println(user.getPassword());  
               return SUCCESS;  
          }  
          public User getUser() {  
               return user;  
          }  
          public void setUser(User user) {  
               this.user = user;  
          }  
     }  
    
      Views
      • Struts has its own tag library
      • To include and use tag library in struts see snippet below
        • See Taglib tag to include library
        • See <S:form> tag to create struts form.
       <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
         pageEncoding="ISO-8859-1"%>  
       <!DOCTYPE html>  
       <%@ taglib prefix="s" uri="/struts-tags" %>  
       <html>  
       <head>  
       <meta charset="ISO-8859-1">  
       <title>Welcome to our Social Network</title>  
       </head>  
       <body>  
       Welcome to our Social Network  
       <s:form action="login">  
            <s:textfield key="user.userName" label="User Name"></s:textfield>  
            <s:password key="user.password" label="Password"></s:password>  
            <s:submit/>  
       </s:form>  
       </body>  
       </html>  
      

      Validation in Struts
      • To add validation in Struts we use the method addFieldError() as shown in snippet
        •  package com.javaimplant.socialnetwork.action;  
           import java.util.List;  
           import org.apache.commons.lang3.StringUtils;  
           import com.javaimplant.socialnetwork.dao.UserDAO;  
           import com.javaimplant.socialnetwork.model.User;  
           import com.opensymphony.xwork2.ActionSupport;  
           public class LoginAction extends ActionSupport {  
                private static final long serialVersionUID = 1L;  
                private User user;  
                @Override  
                public void validate() {  
                     UserDAO dao=new UserDAO();  
                     if(StringUtils.isEmpty(user.getUserName()))  
                     {  
                          addFieldError("user.userName","User Name cannot be blank");  
                          return;  
                     }  
                     List<User> users=dao.getUserByName(user.getUserName());  
                     if(users.isEmpty())  
                     {  
                          addFieldError("user.userName","User Not Found");  
                          return;  
                     }  
                     if(!users.get(0).getPassword().equals(user.getPassword()))  
                     {  
                          addFieldError("user.password","Password mismatch");  
                          return;                 
                     }  
                     this.user=users.get(0);  
                }  
                @Override  
                public String execute() {  
                     System.out.println("We are executing login action!");  
                     System.out.println(user.getUserName());  
                     System.out.println(user.getPassword());  
                     return SUCCESS;  
                }  
                public String insertUser()  
                {  
                     UserDAO dao=new UserDAO();  
                     dao.insertUser(user);  
                     return SUCCESS;  
                }  
                public String addUser()  
                {  
                     return SUCCESS;  
                }  
                public User getUser() {  
                     return user;  
                }  
                public void setUser(User user) {  
                     this.user = user;  
                }  
           }  
          
        • This adds validation to our field in view.
      • Each validation when triggered gives a result of type input for the action in concern which needs to be handled in struts.xml as follows
        •  <?xml version="1.0" encoding="UTF-8"?>  
           <!DOCTYPE struts PUBLIC  
             "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
             "http://struts.apache.org/dtds/struts-2.0.dtd">  
           <struts>  
                     <package name="AccountSystem" extends="struts-default">  
                          <action name="login" class="com.javaimplant.socialnetwork.action.LoginAction">  
                               <result name="success">/loginSuccess.jsp</result>  
                               <result name="input">/index.jsp</result>  
                          </action>  
                     </package>  
           </struts>  
          
      Session in Struts
      1. Define as attribute in class of type Map
        1.       private Map<String,Object> userSession;  
                public Map<String, Object> getUserSession() {  
                     return userSession;  
                }  
                public void setUserSession(Map<String, Object> userSession) {  
                     this.userSession = userSession;  
                }  
          
      2. Generate getter and setter of this session object.
      3. Add into session object MAP as follows
        1.  userSession.put("user",this.user);  
          
      4. The action must implement the following SessionAware interface
        1. The interface has a method setSession which is used to set the session MAP variable into as the session.
        2.  public class LoginAction extends ActionSupport implements SessionAware {  
                private User user;  
                private Map<String,Object> userSession;  
                public Map<String, Object> getUserSession() {  
                     return userSession;  
                }  
                public void setUserSession(Map<String, Object> userSession) {  
                     this.userSession = userSession;  
                }  
                @Override  
                public void validate() {  
                     UserDAO dao=new UserDAO();  
                     if(StringUtils.isEmpty(user.getUserName()))  
                     {  
                          addFieldError("user.userName","User Name cannot be blank");  
                          return;  
                     }  
                     List<User> users=dao.getUserByName(user.getUserName());  
                     if(users.isEmpty())  
                     {  
                          addFieldError("user.userName","User Not Found");  
                          return;  
                     }  
                     if(!users.get(0).getPassword().equals(user.getPassword()))  
                     {  
                          addFieldError("user.password","Password mismatch");  
                          return;                 
                     }  
                     this.user=users.get(0);  
                     userSession.put("currentUser",this.user);  
                     dao.close();  
                }  
                @Override  
                public String execute() {  
                     System.out.println("We are executing login action!");  
                     System.out.println(user.getUserName());  
                     System.out.println(user.getPassword());  
                     return SUCCESS;  
                }  
                @Override  
                public void setSession(Map<String, Object> session) {  
                     this.userSession=session;  
                }  
           }  
          
      d

        No comments:

        Post a Comment