1.建立web project工程,我的结构如下:
2.这一步非常重要:引入必要的jar包,很多博客丫的就给出7个jar包,别理他们!根本不完整!版本2.3.8的struts2需要的jar包如下:一共11个!
引入方法是:右键工程->properties->java build path->Libraries->add external jar 把这11个jar包引入进去!(顺便强烈鄙视某些博客在2.3.8的版本下只引入7个包,请问你们是如何做到的?)
3.修改WEB-INF/lib下的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>
注:filter-class中与之前不同
4. 编写action类
package com.action;
import com.opensymphony.xwork2.ActionSupport;
public class IndexAction extends ActionSupport{
private static final long serialVersionUID = 1L;
private static final String MESSAGE = "struct is running";
private String message = "";
@Override
public String execute() throws Exception {
setMessage(MESSAGE);
return SUCCESS;
}
public String getMessage(){
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
5. 编写view的jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'success.jsp' starting page</title>
</head>
<body>
<h2><s:property value="message"/></h2><br>
</body>
</html>
6. 编写struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" extends="struts-default">
<action name="HelloWorld" class="com.action.IndexAction">
<result name="success">/views/success.jsp</result>
</action>
</package>
</struts>
注:<action name="HelloWorld"中的HelloWorld对应浏览器上输入的地址,class对应要调用的action类。<result name="success">对应action类的execute方法返回的string。我的jsp页面放在项目根目录的views文件夹下。此struts.xml放在src目录下!
7. 部署编译
在浏览器上输入http://localhost:8080/xxx/HelloWorld.action
Ok~~输出struct is running 就成功啦 为表成功 有图有真相