首先用myeclipse创建一个web project ,然后将下面几个包放入WEB-INF/lib中,如下图:
如果看不到WEB-INF文件夹之下的classes文件夹,可以利用如下方法解决该问题:
打开Navigator视图就可以看到(在bin文件夹下),打开改视图的方法:Window→Show View→Navigator。
然后在classes文件夹下面新建一个struts.xml文件。结果如下:
下面对整个示例程序做一个介绍,实现的功能主要是:
下面分别给出各个文件的详细内容:
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app> <display-name>first struts 2 project</display-name> <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> </web-app>
struts.xml
<?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> <include file="struts-default.xml"/> <package name="struts2_login" extends="struts-default" namespace="/login"> <action name="checkLogin" class="act.LoginAction" method="checkLogin"> <result name="success">/index.jsp</result> <result name="login">/login.jsp</result> </action> </package> </struts>
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html><body>登录成功,欢迎您!</body></html>
login.jsp
<%@ page language="java" pageEncoding="UTF-8"%> <%@taglib prefix="s" uri="/struts-tags"%> <style type="text/css"> *{font-size:12px;} </style> <html> <body> <div style="margin:30px 50px 20px 50px; text-align:center"> <div> <s:form action="checkLogin" namespace="/login"> <s:textfield name="username" label="登录名称"/> <s:password name="password" label="登录密码"/> <s:submit value="登录"/> </s:form> </div> </div> </body> </html>
LoginAction.java
package act;
import com.opensymphony.xwork2.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;
}
public String checkLogin()
{
if(this.username.equals("davenzhang")&&this.password.equals("123456"))
return SUCCESS;
else
return LOGIN;
}
}
登录界面如下
加入的lib包有以下一些:
不然会报错!