最近学习struts2时,遇到了不少问题,记录以便查阅。
1.下载struts2包,http://struts.apache.org 我用的是struts-2.3.24.1-all.zip的包,解压后在struts-2.3.24.1\lib目录下选择需要添加的包。
如果不知道 可以在struts-2.3.24.1\apps下解压struts2-blank.war,这是一个简单的struts2的示例,复制在struts2-blank\WEB-INF\lib下所有jar包到你自己项目的WEB-INF\lib即可。
2.在项目WEB-INF目录下新建了classes文件夹。(好像并不影响?)
<!-- 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>
4.配置struts.xml(注意不是struts2.xml。。。。没有就自己新建一个xml文件)。
在src目录下(不是包下)添加struts.xml。
<struts>
<package name="struts2" extends="struts-default">
<action name="Helloworld" class="com.ss.struts2.HelloWorld">
<result name="success">/hello.jsp</result>
</action>
</package>
</struts>
action name是struts2中action的要唯一(名字可随意取),class 中 “com.ss.struts2″为包名”Helloworld”为类名。result中“/hello.jsp”为跳转的页面。
5.写action类
struts2跳转action ,默认执行 execute()方法,返回结果通过struts.xml跳转到页面。
package com.ss.struts2;
public class Helloworld {
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
{
message = "helloworld";
setMessage(message);
return "success";
}
}
6.编写struts.xml要跳转的hello.jsp页面。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>HelloWord</title>
</head>
<body>
<!-- 传统java代码方式 -->
<%String message =(String)request.getAttribute("message");
%>
<%=message %></br>
<!-- EL标签方式 -->
${message };
</body>
</html>
7.启动tomcat服务器 访问4中的action name即可,如http://localhost:8080/JavaEE_struts2/Helloworld (JavaEE_struts2是我的项目名)
注:本文编写参考文献
1.百度经验:http://jingyan.baidu.com/article/73c3ce28e66799e50243d972.html
2. Struts2入门教程 http://blog.youkuaiyun.com/wwwgeyang777/article/details/19078545
3. 本条目发布于2015年12月10日。属于JavaEE分类,被贴了 struts2 标签
欢迎访问 https://loli.monster