struts2学习之二------基本验证

struts2学习之二----基本验证
1、使用标签将原来“struts2学习之一”中的lonin.jsp替换为login2.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<s:form action="login">

<s:textfield name="username" label="username"></s:textfield>
<s:password name="password" label="password"></s:password>

<s:submit label="submit"></s:submit>

</s:form>

</body>
</html>

 
2、修改原“struts2学习之一”中loginAction,使它继承自ActionSupport
这样一来可以使用ActionSupport类的许多方法,如valildate()验证方法等

package com.test.action;

import java.util.Map;

import com.opensymphony.xwork2.ActionContext;
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;
 }

 @SuppressWarnings("unchecked")
 //带逻辑的验证还是放在excute()方法里
 public String execute() throws Exception
 {
  if ("hello".equals(this.getUsername().trim())
    && "world".equals(this.getPassword().trim()))
  {
   Map map = ActionContext.getContext().getSession();
   
   map.put("user","valid");
   
   return "success";
  }
  else
  {//struts2框架会自动显示FieldError的内容,此处如果出错就会显示在字段username上出错信息username or password error
   this.addFieldError("username", "username or password error");
   return "failer";
  }

 }

 @Override
 //validate方法用来验证是否为空或是长度等简单的验证
 public void validate()
 {
  if (null == this.getUsername() || "".equals(this.getUsername().trim()))
  {
   this.addFieldError("username", "username required");
  }
  if (null == this.getPassword() || "".equals(this.getPassword().trim()))
  {
   this.addFieldError("password", "password required");
  }
 }

}

 

3、strurt.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.0.dtd">  
  
<struts>  
    
 <package name="struts2" extends="struts-default">  
      
  <action name="login" class="com.test.action.LoginAction">  
   <result name="input">/login2.jsp</result>  
   <result name="success">result.jsp</result>  
   <result name="failer">/login2.jsp</result>
      
  </action>    
 </package>  
  
</struts>  

 

你可能感兴趣的:(apache,html,jsp,xml,struts)