Create a Struts2 web project

Preface

Build a Struts2 web project step by step from scratch.

Tool: eclipse

Setup process

First, create a dynamic Web project with the following structure:

Then we add the jar packages needed for some projects, put them under the lib directory under WEB-INF, and add them to the project:

jar package download address: http://download.csdn.net/detail/zjq_1314520/9802042

This contains all the basic jar packages needed, so let's pick some for our simplest project.

Next, let's configure web.xml

Here we configure a permission filter to filter all paths, adding the following code:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>HelloStruts2</display-name>

  <filter>
    <filter-name>hellostruts</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>hellostruts</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

Once the web.xml configuration is complete, let's configure some struts.

Create struts.xml in the src directory with the following code:

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

<struts>
</struts>

Under the src directory, create an Action for Struts2 (HeloStrutsAction in the image below) that inherits the ActionSupport base class.

Add the following code to the Action:

package com.struts.trio;

import com.opensymphony.xwork2.ActionSupport;

public class HelloStrutsAction extends ActionSupport {

    @Override
    public String execute() throws Exception {
        // TODO Auto-generated method stub
        return "index";
    }

}

In the code above, we override the execute() method in the base class that handles user requests.
The return value of the above method is index, so how does the program recognize and return the corresponding interface?

So you need to define the mapping between logical views and physical resources

Add the following code to struts.xml:

<struts>
    <!--Define the link between logical and physical views-->
    <package name="trio" extends="struts-default">
        <action name="index" class="com.struts.trio.HelloStrutsAction">
            <!--Map index to physical address-->
            <result name="index">/index.jsp</result>
        </action>
    </package>
    <!-- end -->
</struts>

This will return to the index.jsp file under the WebContent directory.
Let's create a new index.jsp file and add the following code:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>Insert title here</title>
</head>
<body>
<h1>hello struts2 login success!</h1>
</body>
</html>

At this point, a Struts2 project is finished, put it on the server and run, if the result is as follows, you have also created successfully!

There should be doubts at this time.
Is this return interface not defined by web.xml?So what does the previous definition of Action mean?
In fact, the above is mainly a general model of Struts2. See below for the usage of this Action:

Data Interaction

You will now use the architecture just built above for data interaction.

Let's design an application scenario that defines the following requirements:

  • This is the page where the user logs in (username, password)
  • Logon successful, jump to success.jsp
  • Logon failed, jump to failure.jsp

We build on that to meet this need:

First we'll change index.jsp to a file with a login form:

Introduce the tag library for Struts2:

   <!--Label library for introducing struts-->
<%@ taglib uri="/struts-tags" prefix="s"%>

The final code is as follows:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
   <!-- Introduce struts Label Library-->
<%@ taglib uri="/struts-tags" prefix="s"%>
<!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>Sign in</title>
</head>
<body>
    <s:form action="index">
        <s:textfield name="username" key="User name"></s:textfield>
        <s:textfield name="password" key="dense    name"></s:textfield>
        <s:submit key="Sign in"></s:submit>
    </s:form>
</body>
</html>

Note 1: More information about Struts2 tags is available: Struts2 Tags

Note 2: The submission address (index) in the form corresponds to the configuration here in struts.xml:

Explanation: Click the button and the data will be passed to the com.struts.trio.HelloStrutsAction Action.

Next, let's accept the data from the foreground:

Login succeeds when user name is admin and password is 123456, otherwise fails.

Then, the code in the Action is modified as follows:

package com.struts.trio;

import com.opensymphony.xwork2.ActionSupport;

public class HelloStrutsAction extends ActionSupport {

    //username and password defining request parameters
    //Same name attribute as in the form in the foreground jsp
    private String username;
    private String password;

    public String getUsername() {
        return username;
    }


    public void setUsername(String username) {
        this.username = username;
    }


    public String getPassword() {
        return password;
    }


    public void setPassword(String password) {
        this.password = password;
    }


    @Override
    public String execute() throws Exception {
        // TODO Auto-generated method stub
        String userName=this.getUsername();
        String userPassword=this.getPassword();

        if(userName.equals("admin")&&userPassword.equals("123456")){
            ActionContext.getContext().getSession()
                .put("user", userName); //User names stored in session s are used to return to the interface display
            return "success";
        }
        return "failure";
    }
}

Because the return value of the Action changes, the corresponding mapping in struts.xml changes to:

<struts>
    <!-- Define the relationship between logical and physical views -->
    <package name="trio" extends="struts-default">
        <action name="index" class="com.struts.trio.HelloStrutsAction">
            <result name="success">/jsp/success.jsp</result>
            <result name="failure">/jsp/failure.jsp</result>
        </action>
    </package>
    <!-- end -->
</struts>

Next, we create two jsp files corresponding to the return interface:

The login failure interface directly shows: login failure
In the login success interface: XXX (user name) login success

The corresponding failure.jsp does not go into much detail, so how does the success,jsp file output the username stored in the session in the background?

            ActionContext.getContext().getSession()
                .put("user", userName); //User names stored in session s are used to return to the interface display

That's the code that stores the user name. You know the stored key is "user"
We use the EL expression in JSP to get the value in session, with some code as follows:

</head>
<body>
<h1>${session.user} Login Successful</h1>
</body>

Okay, even if this simple example is finished, check to see if your project can run correctly!

Project testing

Run the project, enter the username password

Click Login

Show login success, so far, instance complete!

Keywords: Struts JSP xml Java

Added by CodeBuddy on Sat, 13 Jul 2019 19:53:14 +0300