刚学习Struts2,按网上的例子新建了一个jsp项目,添加了全部struts的jar,项目BuildPath设置为WEB-INF/classes。
项目结构为:
web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>struts2_demo2</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <!-- Struts2配置 --> <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 在src目录下,编译后在WEB-INF/classes/下,内容为:
<?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="struts2" extends="struts-default"> <action name="HelloWorld" class="struts2_demo2.HelloWorld"> <result>/HelloWorld.jsp</result> </action> </package> </struts>
HelloWorld.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<h2><s:property value="message" /></h2>
</body>
</html>
HelloWorld.java:
package struts2_demo2; import com.opensymphony.xwork2.ActionSupport; public class HelloWorld extends ActionSupport { public final static String MESSAGE = "Struts2 is up and running ..."; private String message; // /** * @return the message */ public String getMessage() { return message; } /** * @param message the message to set */ public void setMessage(String message) { this.message = message; } public String execute() throws Exception { setMessage(MESSAGE); return SUCCESS; } }
但访问总是404:
其实已经做过很多demo,都是404,是因为什么原因?谢谢!
问题解决了,原因是我用了最新的Struts 2.5,这个版本已经去除了org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter,换成了
org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter
上下文确认下是否是struts2_demo2
服务启动的时候是否报错
确认服务器启动是否报错?直接localhost:8080/struts2_demo2看看