Velocity与Struts验证用户登录

velocity-tools-1.4-src中自带的一个例子,位于目录/velocity-tools-1.4-src/examples/struts下面。

测试工程目录结构如下所示:

VelocityStrutsA
│ .classpath
│ .mymetadata
│ .mymetadata.bak
│ .mystrutsdata
│ .project

├─.myeclipse
├─src
│ │ hibernate.cfg.xml
│ │ velocity.properties
│ │
│ └─org
│      └─shirdrn
│          │ HibernateSessionFactory.java
│          │
│          ├─struts
│          │ │ ApplicationResources.properties
│          │ │
│          │ ├─action
│          │ │      EnterAction.java
│          │ │      LoginAction.java
│          │ │
│          │ └─form
│          │          LoginForm.java
│          │
│          └─velocity
│              ├─dao
│              │      VelocityUserDao.java
│              │
│              ├─entity
│              │      VelocityUser.hbm.xml
│              │      VelocityUser.java
│              │
│              └─service
│                      VelocityUserService.java

└─WebRoot
    ├─log
    │      velocity.log
    │
    ├─META-INF
    │      MANIFEST.MF
    │
    ├─templates
    │      index.vm
    │      login.vm
    │
    └─WEB-INF
        │ .struts-config.mex
        │ struts-config.xml
        │ toolbox.xml
        │ web.xml
        │
        ├─classes
        │ │ hibernate.cfg.xml
        │ │ velocity.properties
        │ │
        │ └─org
        │      └─shirdrn
        │          │ HibernateSessionFactory.class
        │          │
        │          ├─struts
        │          │ │ ApplicationResources.properties
        │          │ │
        │          │ ├─action
        │          │ │      EnterAction.class
        │          │ │      LoginAction.class
        │          │ │
        │          │ └─form
        │          │          LoginForm.class
        │          │
        │          └─velocity
        │              ├─dao
        │              │      VelocityUserDao.class
        │              │
        │              ├─entity
        │              │      VelocityUser.class
        │              │      VelocityUser.hbm.xml
        │              │
        │              └─service
        │                      VelocityUserService.class
        │
        └─lib
                antlr-2.7.5H3.jar
                antlr.jar
                asm-attrs.jar
                asm.jar
                cglib-2.1.jar
                commons-beanutils.jar
                commons-collections-2.1.1.jar
                commons-digester.jar
                commons-fileupload.jar
                commons-logging-1.0.4.jar
                commons-logging.jar
                commons-validator.jar
                dom4j-1.6.jar
                ehcache-1.1.jar
                hibernate3.jar
                jaas.jar
                jakarta-oro.jar
                jaxen-1.1-beta-4.jar
                jdbc2_0-stdext.jar
                jta.jar
                log4j-1.2.9.jar
                msbase.jar
                mssqlserver.jar
                msutil.jar
                struts.jar
                velocity-1.4.jar
                velocity-dep-1.4.jar
                velocity-tools-1.4.jar
                velocity-tools-view-1.4.jar
                xerces-2.6.2.jar
                xml-apis.jar

准备工作

VelocityUser.hbm.xml是映射数据库表的,VelocityUser.java中包含了三个字段:id、name、password。

VelocityUserDao是VelocityUserService的接口,实现了查询VelocityUser的功能。

关于Velocity

这里使用了velocity.properties属性文件,设置编码,内容如下所示:

default.contentType=text/html; charset=UTF-8
input.encoding=UTF-8
output.encoding=UTF-8
file.resource.loader.path = templates
runtime.log = log/velocity.log

使用到了两个Velocity模板文件,分别为login.vm和index.vm。

login.vm文件如下所示:

<HTML>
<HEAD>
    <TITLE>用户登录页面-当前时间为: $date.get('yyyy-M-d H:m:s')</TITLE>
</HEAD>
<BODY bgcolor="">
<center>
#errorMarkup()
    <FORM method="POST" action="$link.action.login">
      <h2>用户登录</h2>
      <br>
      用户名:<INPUT type="text" name="name" alue=""><br>
      密 码:<INPUT type="password" name="password"><br>
      <INPUT type="submit" value="Submit" name="submit">
    </FORM>
    <br>
    </center>
    #macro (errorMarkup)
            #if ($errors.exist() )
                <ul>
                #foreach ($e in $errors.all )
                    $e
                #end
                </ul>
            #end
    #end
</BODY>
</HTML>

这里用到了toolbox.xml中指定的一些工具,如:org.apache.velocity.tools.generic.ComparisonDateTool工具、org.apache.velocity.tools.struts.StrutsLinkTool工具。

在定义的Velocity宏中,这里用到了toolbox.xml中的org.apache.velocity.tools.struts.ErrorsTool工具,即对登录用户名和密码为空时进行验证。

其中,登录成功后,进入index.vm页面,如下所示:

<html>
<head>
   <title>首页-欢迎成功登录</title>
</head>
<body>
#if($velocityUser)
   <h3>您好,当前时间为: $date.get('yyyy-M-d H:m:s')</h3>
   <center>
    您的登录用户名为:$velocityUser.name,密码为:$velocityUser.password。
   </center>
#end
</body>
</html>

一些Velocity工具在toolbox.xml中定义,toolbox.xml的内容如下所示:

<?xml version="1.0"?>
<toolbox>
   <tool>
    <key>date</key>
    <scope>application</scope>
    <class>org.apache.velocity.tools.generic.ComparisonDateTool</class>
    <parameter name="format" value="yyyy-MM-dd"/>
    <parameter name="depth" value="2"/>
    <parameter name="skip" value="month"/>
</tool>
<!-- Struts Tools -->
<tool>
     <key>link</key>
     <scope>request</scope>
     <class>
       org.apache.velocity.tools.struts.StrutsLinkTool
     </class>
</tool>
<tool>
     <key>msg</key>
     <scope>request</scope>
     <class>
       org.apache.velocity.tools.struts.MessageTool
     </class>
</tool>
<tool>
     <key>errors</key>
     <scope>request</scope>
     <class>
       org.apache.velocity.tools.struts.ErrorsTool
     </class>
</tool>
<tool>
     <key>form</key>
     <scope>request</scope>
     <class>
       org.apache.velocity.tools.struts.FormTool
     </class>
</tool>
<tool>
     <key>tiles</key>
     <scope>request</scope>
     <class>
       org.apache.velocity.tools.struts.TilesTool
     </class>
</tool>
<tool>
     <key>validator</key>
     <scope>request</scope>
     <class>
       org.apache.velocity.tools.struts.ValidatorTool
     </class>
</tool>
</toolbox>

而且,还要将toolbox.xml在web.xml中配置好,当应用启动的时候会根据初始化配置参数加载所有可用的Velocity工具。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
      <param-name>config</param-name>
      <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
    <init-param>
      <param-name>debug</param-name>
      <param-value>3</param-value>
    </init-param>
    <init-param>
      <param-name>detail</param-name>
      <param-value>3</param-value>
    </init-param>
    <load-on-startup>0</load-on-startup>
</servlet>

<servlet>
<servlet-name>velocity</servlet-name>
<servlet-class>org.apache.velocity.tools.view.servlet.VelocityViewServlet</servlet-class>
<init-param>
    <param-name>org.apache.velocity.properties</param-name>
    <param-value>/WEB-INF/classes/velocity.properties</param-value>
</init-param>                                           
<init-param>
    <param-name>org.apache.velocity.toolbox</param-name>
    <param-value>/WEB-INF/toolbox.xml</param-value>     
   </init-param>                                                
   <load-on-startup>10</load-on-startup>
</servlet>


<servlet-mapping>
<servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>velocity</servlet-name>
<url-pattern>*.vm</url-pattern>     
</servlet-mapping>
</web-app>

关于Struts

Struts的配置文件struts-config.xml配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">

<struts-config>
<data-sources />
<form-beans >
    <form-bean name="loginForm" type="org.shirdrn.struts.form.LoginForm" />

</form-beans>

<global-exceptions />
<global-forwards />

<action-mappings >
    <action
    path="/enter"
    type="org.shirdrn.struts.action.EnterAction" >
    <forward name="enter" path="/templates/login.vm" />
    </action>
    <action
      attribute="loginForm"
      name="loginForm"
      path="/login"
      scope="request"
      input="/templates/login.vm"
      validate="true"
      type="org.shirdrn.struts.action.LoginAction">
      <forward
        name="error"
        path="/templates/login.vm" />
      <forward
        name="success"
        path="/templates/index.vm"
        redirect="true" />
    </action>
</action-mappings>

<message-resources parameter="org.shirdrn.struts.ApplicationResources" />
</struts-config>

其中,当登录用户名和密码都为空的时候,则提示错误信息,在 ApplicationResources.properties中添加:

error.name.required=<li><font color="red">Name is required</font></li>
error.password.required=<li><font color="red">Password is required</font></li>

Struts的Action有两个。

EnterAction就起到跳转到login.vm模板页面的作用,当然也可以让其继承ForwardAction,如下:

package org.shirdrn.struts.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class EnterAction extends Action {

public ActionForward execute(ActionMapping mapping, ActionForm form,
    HttpServletRequest request, HttpServletResponse response) {
   return mapping.findForward("enter");
}
}

LoginAction关联了LoginForm,如下所示:


package org.shirdrn.struts.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.shirdrn.struts.form.LoginForm;
import org.shirdrn.velocity.dao.VelocityUserDao;
import org.shirdrn.velocity.entity.VelocityUser;
import org.shirdrn.velocity.service.VelocityUserService;

public class LoginAction extends Action {

public ActionForward execute(ActionMapping mapping, ActionForm form,
    HttpServletRequest request, HttpServletResponse response) {
   LoginForm loginForm = (LoginForm)form;
   VelocityUser vu = new VelocityUser();
   vu.setName(loginForm.getName().trim());
   vu.setPassword(loginForm.getPassword().trim());
   VelocityUserDao velocityUserDao = new VelocityUserService();
   List list = velocityUserDao.queryVelocityUser(vu);
   HttpSession session = request.getSession();
   session.setAttribute("velocityUser", vu);
   if(list.size() <1){
    return mapping.findForward("error");    //   登录失败则回到登录页面
   }
   return mapping.findForward("success");
}
}

对应的LoginForm如下:

package org.shirdrn.struts.form;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

public class LoginForm extends ActionForm {

private String name;
private String password;

public ActionErrors validate(ActionMapping mapping,
    HttpServletRequest request) {     // 验证登录表单
   ActionErrors errors = new ActionErrors();
        if ((name == null) || (name.length() < 1))
            errors.add("name", new ActionMessage("error.name.required"));
        if ((password == null) || (password.length() < 1))
            errors.add("password", new ActionMessage("error.password.required"));
        return errors;
}

public void reset(ActionMapping mapping, HttpServletRequest request) {
  
}

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;
}
}

验证表单的时候,将错误信息存储到errors中,通过Velocity的org.apache.velocity.tools.struts.ErrorsTool工具,定义一个Velocity宏来实现错误信息的显示。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值