第一步:创建web project工程
打开MyEclipse,创建一个Web Project,如下图所示:

我的工程名叫struts2.2。
第二步:引入jar文件
导入相应的jar包

第三步:配置web.xml文件
配置web.xml,配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<filter>
<filter-name>strutsFilter</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>strutsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
第四步:编写JSP页面
(1)index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" contentType="text/html; charset=utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Login Demo</title>
</head>
<body>
<fieldset >
<legend >登陆页面</legend>
<form action="login" method="post" >
姓名:<input type="text" name="name"/><br/>
密码:<input type="password" name="pwd"/><br/>
<p><input type="submit" value="登录"/></p>
</form>
</fieldset>
</body>
</html>
(2)ok.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" contentType="text/html; charset=utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>登陆成功</title>
</head>
<body>
<span style="color: blue;">登陆成功</span>
</body>
</html>
第五步:编写Action组件
写一个Java类,类名叫LoginAction
package web;
public class LoginAction {
private String name;
private String pwd;
public String execute() {
if ("scott".equals(name) && "1234".equals(pwd)) {
return "success";
}
return "login";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
第六步:配置struts.xml(在src目录下)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
<!-- 配置当前环境为开发模式 -->
<constant name="strutts.devMode" value="false" />
<package name="struts1-demo" namespace="/" extends="struts-default">
<action name="login" class="web.LoginAction">
<result name="success">/ok.jsp</result>
<result name="login">/index.jsp</result>
</action>
</package>
</struts>
第七步:启动TomCat服务器,部署项目,并在浏览器地址栏进行访问:
访问地址:http://localhost:8080/struts2.2/

点击“登录”按钮,此时会跳转到ok.jsp页面。


804

被折叠的 条评论
为什么被折叠?



