编写流程:
1.创建WEB 工程
2.导入必要jar包
3.编写JSP 页面
4.编写Action 服务器端处理逻辑
5.进行框架配置web.xml、struts.xml
6.运行测试
1.创建WEB 工程
2.导入必要jar包
3.编写JSP 页面
index.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
<a href="${pageContext.request.contextPath}/hello.action">helloworld</a>
</body>
</html>
success.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
Hello Struts2
</body>
</html>
4.编写Action 服务器端处理逻辑
Action可以是普通的Java类,可以实现Action接口,也可以继承ActionSupport,推荐使用继承ActionSupport。
HelloAction.java
package com.my.action;
import com.opensymphony.xwork2.ActionSupport;
public class HelloAction extends ActionSupport{
@Override
public String execute() throws Exception {
System.out.println("hello world");
return SUCCESS;
}
}
5.进行框架配置web.xml、struts.xml
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
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_3_0.xsd">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
struts.xml,
<?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>
<!--
确定包package
name属性,必须确保在当前xml文档中唯一,提供给其他package继承
namespace属性,命名空间,url的前缀
extends属性,用于继承struts其他的package,struts提供默认的package名称固定值:struts-default
确定action
name属性,url中方法的名称
class属性,url需要处理类
确定result
name属性:action中方法的返回值
-->
<package name="helloWord" namespace="/" extends="struts-default">
<action name="hello" class="com.my.action.HelloAction">
<result name="success">/success.jsp</result>
</action>
</package>
</struts>
注意:文件名必须为struts.xml, 如果修改需要在web.xml文件中加
<init-param>
<param-name>config</param-name>
<param-value>struts-default.xml,struts-plugin.xml,struts.xml,自定义的文件名.xml</param-value>
</init-param>
6.运行测试
请求页面:
结果页面:
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/12080.html