Simple example of using Struts framework in eclipse

Permanent update address: https://my.oschina.net/bysu/blog/edit/1783513

1. Download the Struts2 framework

http://struts.apache.org/download.cgi

Download full version

There are 5 download options under Struts.
Full Distribution: Download the full version of Struts 2, including the jar package of the Struts 2 framework, examples, and jar packages that depend on
the test;
Example Applications: Download the example application of Struts 2, which is easy to learn Struts 2, the full version already includes
this option;
Essential Dependencies Only: Only download the core library of Struts 2, the full version already includes this option;
Documentation: Download Struts 2 related documents, including Struts 2 development documents, reference manuals and
API documents, etc. The full version already includes this option;
Source : Download the full source code of Struts 2, the full version already includes this option.

After downloading and decompressing, the directory is as follows:


The main file structure after decompression of the Struts 2 framework package is as follows:
apps——This folder contains 5 war files, which are all Web application examples based on Struts 2. Programmers can learn and study Struts 2 through these examples. Technology;
docs - This folder contains Struts 2 development documents, reference manuals and API documents, and you need to consult these help documents frequently during development;

lib——This folder contains the core class library of the Struts 2 framework and the third-party class library of the Struts 2 framework. When developing a Web application based on the Struts 2 framework, you need to copy some jar packages in this directory to the Web application. "WEB-INF/lib" path;

src - This folder contains all the source code of the Struts 2 framework.


When developing a web application based on the Struts2 framework, it is not necessary to apply all the functions of Struts 2, so there is no need to directly copy all the jar packages in the lib subdirectory under the compressed package of the Struts 2 framework to the WEB-INF/ of the web application. lib path, but some basic class libraries required by the Struts 2 framework must be added to the Web application.
Usually, an empty project struts2-blank.war based on the Struts 2 framework is provided in the apps subdirectory under the Struts2 framework compressed package. The jar package in the WEB-INF/ib directory in the empty project is some basic required by the Struts 2 framework. class library.

2. Create an empty web application

For the creation steps, see the blog post "Remedy for not generating web.xml when creating a dynamic web project with eclipse" .

After creation, copy the jar package in the basic class library in the Struts2 framework to the WEB-INF/lib path of the project. As shown below:

3.配置StrutsPrepareAndExecuteFilter

Open the configuration file web.xml of the web application (if the project does not have this file, refer to the blog post mentioned above), and add the Struts2 (different Struts2 version <filter-class> class paths in different versions) to the configuration file. Configuration information of the core controller StrutsPrepareAndExecuteFilter. The code to configure StrutsPrepareAndExecuteFilter is as follows:

<?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_3_1.xsd" version="3.1">
  <display-name>chapter02</display-name>
  <!-- 配置Struts 2框架的核心Filter -->
	<filter>
		<!--过滤器名 -->
		<filter-name>struts2</filter-name>
		<!--  配置Struts 2的核心Filter的实现类  -->
        <!--  <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>  -->
		<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
	</filter>
	<!--  让Struts 2的核心Filter拦截所有请求  -->
	<filter-mapping>
		<!--过滤器名 -->
		<filter-name>struts2</filter-name>
		<!-- 匹配所有请求 -->
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<!--欢迎页面列表 -->
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>input.jsp</welcome-file>
  </welcome-file-list>
</web-app>

After configuring the StrutsPrepareAndExecuteFilter filter in web.xml, the web application has the basic functional support of the Struts2 framework.

4. Create the input view

Create an input.jsp input page in the WebContent root directory of the project to receive data input by the user. code show as below:

<%@ 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=ISO-8859-1">
<title>用户信息采集</title>
</head>
<body>
<form method="post" action="user.action">
用户名:<input type="text" name="userName" /><br/>
地址:<input type="text" name="address" /><br/>
电话:<input type="text" name="telephone" /><br/>
邮箱:<input type="text" name="email" /><br/>
<input type="submit" value="提交" />
</form>
</body>
</html>

The above page code defines a form with 4 text input boxes and a submit button. After the form is submitted, it is handled by user.action.

5. Create a business controller

In the src directory of the project, create the com.bysu package and add the UserAction class of the business controller for processing user data, as shown in the following figure:

The UserAction class code is as follows:

package com.bysu;

public class UserAction {

	private String userName;
	private String address;
	private String telephone;
	private String email;
	
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public String getTelephone() {
		return telephone;
	}
	public void setTelephone(String telephone) {
		this.telephone = telephone;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	
	public String execute() throws Exception{
		if(userName.length() > 0 && address.equals("青岛")) {
			return "success";
		}else {
			return "error";
		}
	}
}


In the above code, UserAction is a POJO that defines 4 attributes: userNamedrss, telephone and email. These 4 attribute names must correspond to the name attribute value of the input text box in the input.jsp page; then, for these 4 attributes Provide the corresponding getter/settert methods. In this way, when the user submits the form in the input.jsp page, the input data in the form will be set to the corresponding attribute through the stter method. In the business processing method execute() method, it is judged whether the data meets the requirements, and the string "success" or "error" is returned.

6. Configure the business controller

In the project src directory, add the Struts2 configuration file struts.xml. As shown below:

Open the struts.xml configuration file and configure UserAtion in this file, the code is as follows:

<?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>
	<!-- 指定Struts2处于开发阶段,可以进行调试 -->
	<constant name="struts.devMode" value="true" />

	<!-- Struts2的Action都必须配置在package里,此处使用默认package -->
	<package name="default" namespace="/" extends="struts-default">
		<!-- 定义一个名为user的Action,实现类为com.bysu.UserAction -->
<action name="a" class="com.bysu.UserAction">
			<!-- 配置execute()方法返回值与视图资源之间的映射关系 -->
			<result name="success">/result.jsp</result>
			<result name="error">/error.jsp</result>
		</action>
	</package>

</struts>

In the struts.xml configuration file, an Action named a is configured, and the implementation class corresponding to the Action is specified as com.bysu.UserAction. In fact, the Action is also related to the action attribute in the form in the input.jsp above. In the <result> element, specify the mapping relationship between the return value of the execute() method and the view page resources.

7. Create a Results View

Create the result.jsp result view in the WebContent root directory of the project. code show as below:

<%@ 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=ISO-8859-1">
<title>显示用户信息</title>
</head>
<body>
用户名:${param.userName}</br>
地址:${param.address}</br>
电话:${param.telephone}</br>
邮箱:${param.email}</br>
</body>
</html>

The above page uses EL expressions to display user information.

The error page error.jsp code is as follows:

<%@ 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=ISO-8859-1">
<title>错误页面</title>
</head>
<body>
你输入的信息不符合要求,请重新输入。
</body>
</html>

After the above construction, it is only running. But it was this operation that took me a whole afternoon. Now let's illustrate the steps of operation first! Exception handling is put later.

run:

1. Start the tomcat server.

Double-click the tomcat installation directory\bin\startup.bat file to run.

2. Select the project, right-click - Run As - Run on Server (you may need to create a Server before this step)

The steps to create a Server are as follows:

If the operation is successful, the following interface will appear:

 

If the operation fails, look at your specific error~ My error interface (both external browsers and internal browsers) is as follows:

After running, it is found that the webapps in the installation directory of tomcat does not have the project name established, but open http://localhost:8080 on the external browser and the expected kitten screen appears, which proves that my tomcat configuration should be fine. .

After searching on the Internet: it turns out that unlike MyEclipse, the project is deployed to the webapps in the tomcat installation directory by default, but is deployed to .metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps in the working directory by default. , the tmp1 folder contains the information of the project.

For the above problems, solutions are given online, as follows:

In order to deploy the project to the webapps in the tomcat installation directory by default, show view—>servers—>find the tomcat that needs to be modified—>right-click ①Stop the Tomcat server in eclipse (stop) ②Delete the project deployed in the container (add and remove) ③Clear the relevant data of the container (clean) ④Open the modification interface of tomcat (open)

⑤Find the servers location and select the second one (User tomcat Installation) ⑥Modify the deploy path to webapps ⑦Save and close

It should be noted that ①②③ must be operated, otherwise the following steps will be grayed out and cannot be operated.

After the above is completed, finally restart eclipse. Otherwise, even if it is set, it does not seem to take effect. I just restarted the tomcat service, and then continued to tinker for an entire afternoon. Engage in a lot of places, after restarting eclipse on it. So I'm not sure exactly how I tinkered with it.

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325144580&siteId=291194637