struts2的一个登陆的例子程序,非常简单:
java包中的程序:model包中的
package model;
public class User {
private String name;
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
action包中的控制程序:
package action;
import model.User;
import com.opensymphony.xwork2.Action;
public class LoginAction implements Action{
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String execute() throws Exception {
if("seacean".equals(user.getName())&&"12345".equals(user.getPassword())){
return SUCCESS;
}else{
return ERROR;
}
}
}
页面上的起始登陆页面:login.jsp
<form action="Login" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="user.name"/></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="user.password"/></td>
</tr>
<tr>
<td><input type="reset" value="重填"/></td>
<td><input type="submit" value="登陆"/></td>
</tr>
</table>
</form>
登陆成功的页面success.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>登陆成功</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<h3>
<s:property value="user.name"/>,欢迎来到seacean的blog!
</h3>
</body>
</html>
登陆失败的页面,error.jsp
用户名或者密码错误,请重新<a href="login.jsp">登陆</a>。
在struts.xml中的配置:
<package name="default" extends="struts-default">
<action name="Login" class="action.LoginAction">
<result>/success.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
在这里一定要注意,action的name属性的第一个字母要大写,小写的话我试过会报错。result中没有指定name表示成功的页面。
下面这段代码可以在action包下面的控制类中获取运行环境中的request.session.application:
ActionContext context=ActionContext.getContext();
Map request=(Map) context.get("request");
Map session=context.getSession();
Map application=context.getApplication();