1.下载struts库 打开网址:http://struts.apache.org/ 点击download,点击下载:struts-2.3.31-all.zip (65MB)
2.解压struts-2.3.31-all.zip ,进入目录apps,解压struts2-blank.war,进入WEB-INF/lib,复制所有jar包,保存一个自己喜欢的目录,比如:D:\javaEE\struct2.3lib\
3.打开eclipse,点击File–>New–>Dynamic Web Project(起个工程名)–>Next–>Next(勾选生成web.xml)
4.点击window–>preferences–>java–>Build Path–>User Libraries–>New(起个库名字:struts)–>Add Extenal Jars–>选择刚刚保存的struts目录,比如:D:\javaEE\struct2.3lib\ –>打开 –>Ok
5.右击刚刚创建的工程目录,选择Build Path,选择configure build path,点击Add Library–》User Library–》struts–》apply–》OK ,并把依赖库的所有jar包复制到工程目录WebContent/WEB-INF/lib目录下
1.在WebContent/WEB-INF/web.xml中进行配置:
添加拦截:
<filter>
<filter-name>struts2filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
filter-class>
filter>
<filter-mapping>
<filter-name>struts2filter-name>
/*
filter-mapping>
2.右击工程目录–》New–》JSP File–》login.jsp 创建login.jsp文件
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title heretitle>
head>
<body>
<s:form action="login_action">
<s:textfield name="username" value="user">s:textfield>
<s:textfield name="password" value="pass">s:textfield>
<s:submit key="login">s:submit>
s:form>
body>
html>
3.创建Action,LoginAction.java
import com.opensymphony.xwork2.ActionSupport;
(继承struts内置ActionSupport)
public class LoginAction extends ActionSupport {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
//struts会自动执行这个方法
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
return SUCCESS;//返回处理结果
}
}
4.在src目录下创建struts.xml ,并做配置(注意文件所在的路径)
<struts>
<package name="随便起" extends="struts-default">
<action name="login_action" class="com.sdw.action.LoginAction">
<result name="success">welcome.jspresult>
<result name="error" >error.jspresult>
action>
package>
struts>
5.创建相应响应的页面:welcome.jsp和error.jsp
welcome.jsp内容如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title heretitle>
head>
<body>
welcome
body>
html>
error.jsp页面内容不给了,自己随便写吧
这样就大功告成了,保存全部文件,右击index.jsp,run as –》run onserver(前提需要配置好Tomcat服务器)
如果顺利的话应该会出现下面的结果:
如有错误,欢迎指出