Struts2入门示例(Myeclipse)
1.新建Web项目在lib导入struts-2.3.37核心基础jar包
2.在WebRoot新建2个JSP
demo1.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Struts2入门</title>
</head>
<body>
<h1>Struts入门</h1>
<a href="${pageContext.request.contextPath }/strutsDemo1.action">访问Struts的action</a>
</body>
</html>
demo2.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
<h1>跳转成功!</h1>
</body>
</html>
3.在项目中的web.xml中添加代码
<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>
4.建包建类
package com.sve.struts2; public class Demo1 { public String execute() { System.out.println("方法执行了"); return "success"; } }
注意:方法名必须为execute,返回值必须为String,且public
5.在src下创建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="demo" namespace="/" extends="struts-default"> <action name="strutsDemo1" class="com.sve.struts2.Demo1"> <result name="success">/demo2.jsp</result> </action> </package> </struts>
在action中class为你建包名.类名,name为demo1.jsp中访问链接,无须加.action
在result中,name的值为类中的返回值
6.运行项目,访问demo1.jsp,点击链接访问