在eclipse中配置struts
1.进入struts网址:http://struts.apache.org/downloads.html
2.下载struts开发包
3.解压下载的开发包,目录结构如下:
4. 打开eclipse,选择新建Dynamic Web Project
注:如果新建菜单里里面没有Dynamic Web Project选项,可选择Other..,在Web节点下选择
5.配置项目名称,Target runtime,Dynamic web module version,直接点Finish即可
6. 打开apps示例程序
示例程序(apps)目录下的文件
7.打开解压后的文件
WEB-INF目录下的文件
8.打开web.xml,将filter拷贝到WebContent/WEB-INF/web.xml中
做好上述步骤后,项目结构如下:
使用struts创建简单的helloworld例子
步骤:
a)创建一个类储存欢迎信息(model)
b)创建一个JSP展现欢迎信息(view)
c)创建一个Action去控制用户(user),模型(model),视图(view)之间的交互
d)创建一个映射文件(struts.xml)关联Action类和视图(view)
具体操作:
1) 创建一个模型类,MessageStore.java,对应的包为model
package model;
public class MessageStore {
private String message;
public MessageStore() {
setMessage("Hello Struts User");
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
2)创建一个Action类HelloWorldAction.java,对应的包为action
package action;
import model.MessageStore;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class HelloWorldAction extends ActionSupport {
private MessageStore messageStore;
public String execute() throws Exception {
messageStore = new MessageStore();
return SUCCESS;
}
public MessageStore getMessageStore() {
return messageStore;
}
public void setMessageStore(MessageStore messageStore) {
this.messageStore = messageStore;
}
}
3) 创建一个视图,HelloWorld.jsp,放在WebContent目录下
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!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>Hello World!</title>
</head>
<body>
<h2><s:property value="messageStore.message" /></h2>
</body>
</html>
4)在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> <constant name="struts.devMode" value="true" /> <package name="basicstruts2" extends="struts-default"> <action name="index"> <result>/index.jsp</result> </action> <action name="hello" class="action.HelloWorldAction" method="execute"> <result name="success">/HelloWorld.jsp</result> </action> </package> </struts>
5)创建index.jsp并添加URL Action
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!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>Basic Struts 2 Application - Welcome</title>
</head>
<body>
<h1>Welcome To Struts 2!</h1>
<p><a href="<s:url action='hello'/>">Hello World</a></p>
</body>
</html>
将项目部署到tomcat服务器上,运行,在浏览器中输入http://localhost:8080/项目名称/index.jsp
点击Hello World链接