项目结构:
第一步:创建一个web项目
第二步:在web-inf下创建lib,把下载好的jar包复制进去,再点击库添加jar文件选该web-inf下的lib
第三步:在web页下创建web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<display-name>struts_lesson1</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
第四步:编写动作类(看清楚包名):
package com.sise.lab1.action;
public class LoginAction {
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;
}
public String execute() throws Exception{
if(null!=username && username.equals("admin") &&null!= password
&&password.equals("sise"))
return "suc";
return "login";
}
}
第五步:在源包的默认包(即是java)创建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.5.dtd">
<struts>
<package name="lab1" extends="struts-default">
<action name="login" class="com.sise.lab1.action.LoginAction">
<result name="suc">/welcome.jsp</result>
<result name="login">/login.jsp</result>
</action>
</package>
</struts>
第六步:在web页,即web-root下创建对应的jsp文件:
login.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String path=request.getContextPath();
String basePath=request.getScheme()+"://"+request.getServerName()+":"
+request.getServerPort()+path+"/";
%>
<html>
<head>
</head>
<body>
<form action="login.action" method="post">
用户名:<input type="text" name="username"/><br/>
密码:<input type="password" name="password"/><br/>
<input type="submit" value="登陆">
</form>
</body>
</html>
welcome.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String path=request.getContextPath();
String basePath=request.getScheme()+"://"+request.getServerName()+":"
+request.getServerPort()+path+"/";
%>
<html>
<head>
</head>
<body>
<h3>${username},您好!欢迎光临!</h3>
</body>
</html>
总结:路径上的错误和变量名get,set经常会发生。