之前不管是按照书上还是网上的都有错误一直是 struts
The requested resource is not available.
,从其他地方下载的demo包我也不能运行,很郁闷.后来一点点的改好了,写下笔记.
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
1,新建一个项目,名字为struts2test,在在webcontent下新建三个jsp文件,index.jsp ;error.jsp;success.jsp;
2,看到那个web.xml了吗?修改这个文件,修改这个文件后要重启服务器;
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4"
</web-app>
3,修改struts.xml文件,注意那个文件在src目录下;修改这个文件后要重启服务器;
<?xml version="1.0" encoding="UTF-8" ?>
<struts>
<package name="struts2"
extends="struts-default" namespace="/">
<action name="sum" class="struts2.MyAction">
<result name="success">/success.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
</struts>
4,在webcontent的lib下添加如下的包,数据库操作的包也要添加在这里,否则会无法运行;修改这个文件后要重启服务器;
5,编写类文件,返回的是ACtionSopprt包里的SUCCESS预定义的字符串常量,不是自己定义的"success";修改这个文件后要重启服务器;
package struts2;
import com.opensymphony.xwork2.ActionSupport;
public class MyAction extends ActionSupport
{
private String username = null;
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
@Override
public String execute() throws Exception
{
if (username == null || username.equals(""))
{
return ERROR;
} else
{
return SUCCESS;
}
}
}
6,编写前台页面,注意要提交的action里的值用html控件或者服务器控件获取,那么控件的名字要和类中定义的字符串名称一样,既类中的 private String username,那么在页面中提交时要有一个控件的名字为username;
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<%@ page language="java"
pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>8888</title>
</head>
<body>
<br />
<s:form action="sum.action">
<s:textfield name="username" label="username" />
<s:submit value="输出username" />
</s:form>
</body>
</html>
7,运行并检查错误