使用struts2开发程序的基本步骤
- 加载struts2类库pom.xml
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.5.22</version>
</dependency>
- 配置web.xml文件
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0" >
<!-- struts2 核心配置-->
<filter>
<!-- 过滤器的名称,自定义,命名为struts-->
<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>
3.开发视图层页面
<%@page contentType="text/html; charset=UTF-8" language="java" %>
<html>
<body>
<form action="hello.action" method="post">
<div>
<label>
用户名:
</label>
<input type="text" name="userName">
</div>
<div>
<input type="submit" value="登录">
</div>
</form>
</body>
</html>
- 开发控制层的action
package com.lty.web;
import com.opensymphony.xwork2.Action;
public class HelloAction implements Action {
// 后端获取前端提交的数据
private String userName;
@Override
public String execute() throws Exception {
System.out.println("userName="+userName);
return "success";
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
- 配置struts.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<package name="default" extends="struts-default" namespace="/">
<!-- 配置访问请求-->
<action name="hello" class="com.lty.web.HelloAction">
<result name="success">/show.jsp</result>
</action>
</package>
</struts>
- 部署,运行项目