`

struts2登录验证

阅读更多
    自己刚开始学习struts2的基础知识,对struts1有点了解。自己利用struts2标签弄了简单的登录验证。自己也是给自己留个记录吧。
    首先是登录的index.jsp页面代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib prefix="z" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'index.jsp' starting page</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>
  <z:form action="login" method="post">
  <z:textfield name="username" label="用户名" />
  <z:password name="password" label="密码"/>
  <z:submit value="登录" align="left"/>
  </z:form>
   </body>
</html>
自己在建立相应的登录成功和失败页面,success.jsp和error.jsp。
在struts2中建立相应的action类:
package com.gb.denglu;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class loginaction  extends ActionSupport{
        private String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}

private String password;

public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String execute() throws Exception{
if(username.equalsIgnoreCase("gb")&& password.equalsIgnoreCase("1")){

ActionContext.getContext().getSession().put("name", username);

return "success";
}else {
return "error";
}                                                             
}
public void validate(){
if(username==null || username.trim().equals("")){

addFieldError("username","姓名不能为空");
}
if(password==null || password.trim().equals("")){
addFieldError("password","密码不能为空 ");
}
}

下面是struts.xml的配置文件信息;
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="cn.gb.struts2" namespace="/test" extends="struts-default">
<action name="hello" class="cn.gb.struts2.helloword">
<result name="success">/index.jsp</result>
</action>
</package>
<package name="num1"  extends="struts-default">
<action name="login" class="com.gb.denglu.loginaction">
<result name="success">/success.jsp</result>
<result name="error">/error.jsp</result>
<result name="input">/index.jsp</result>
</action>
</package>
</struts>   
配置完成了,可以看下验证的页面。






  • 大小: 9.4 KB
  • 大小: 7.5 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics