在上一篇文章了解了在普通项目中添加struts2支持之后,下面我们来介绍一个struts2实现的简单的登陆实例项目。该项目主要是让大家了解一下struts2项目的工作原理~~
该项目暂时并不使用数据库。所用到的文件为:index.jsp,hello.jsp,fail.jsp,struts.xml和GreetAction.java5个文件。
index.jsp将表单的数据提交到struts中的控制器(其实是个过滤器),控制器转发给相应的action,action将数据处理之后,在跳转到相应的jsp显示页面。逻辑很简单,接下来让我们看看是如何实现的吧!
index.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!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>登陆页面</title>
</head>
<body>
<form action="greet" method="post">
<input type="text" name="userName">
<input type="text" name="password">
<input type="submit" value="登陆">
</form>
</body>
</html>
GreetAction.java
package action;
public class GreetAction {
//userName和password这两个变量名必须和index.jsp中的form表单中的提交的数据的表单名保持一致
private String userName;
private String password;
public String execute(){
if(!userName.trim().equals("root")|| !password.trim().equals("root")){
return "fail";
}
return "hello";
}
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.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.i18n.encoding" value="UTF-8"></constant>
<package name="default" namespace="/" extends="struts-default" >
<action name="greet" class="action.GreetAction">
<result name="hello">hello.jsp</result>
<result name="fail">fail.jsp</result>
</action>
</package>
</struts>
项目的文件结构如下:
对于上面的简单例子大家应该可以从中体会到struts项目的运行原理~~~
更详细的介绍,将在下一篇文章中介绍~~