posts - 495,  comments - 11,  trackbacks - 0

1.准备工作

建好一个Web项目,加入必要的jar包(见本文末的附图),本文将演示一个用户登录的例子,使用的是struts2.1.6,java ee 5

2.代码

User.java

/*
* @(#)User.java 2009-7-29
*
* Copyright (c) 2009 by jadmin. All Rights Reserved.
*/

package com.jsoft.domain;

/**
* 用户实体类
*
* @author <a href="
mailto:jadmin@126.com">jadmin</a>
* @version $Id: User.java 2009-7-29 下午12:47:16$
* @see <a href="
http://hi.baidu.com/jadmin">myblog</a>
*/
public class User {

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

@Override
public String toString() {
   return super.toString() + "[" + username + ", " + password + "]";
}
}

UserAction.java

/*
* @(#)UserAction.java 2009-7-29
*
* Copyright (c) 2009 by jadmin. All Rights Reserved.
*/

package com.jsoft.web.action;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import com.jsoft.domain.User;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

/**
* Action
*
* @author <a href="
mailto:jadmin@126.com">jadmin</a>
* @version $Id: UserAction.java 2009-7-29 下午12:24:33$
* @see <a href="
http://hi.baidu.com/jadmin">myblog</a>
*/
public class UserAction extends ActionSupport {

private static final long serialVersionUID = 6488865641880260892L;
private User user;

@Action(value = "login",
    results = {
     @Result(name = "success", location = "/login_success.jsp", type = "redirect"),
     @Result(name = "input", location = "/login.jsp", type = "dispatcher")
    })
public String execute() throws Exception {
   System.out.println(user);
   ActionContext.getContext().getSession().put("user", user);
   return SUCCESS;
}

@Override
public void validate() {
   if (!"admin".equals(user.getUsername())) {
    addFieldError("user.username", "登录名不正确!");
   } else if (!"admin".equals(user.getPassword())) {
    addFieldError("user.password", "密码不正确!");
   }
}

public User getUser() {
   return user;
}

public void setUser(User user) {
   this.user = user;
}
}

web.xml文件

<filter>
   <filter-name>struts2</filter-name>
   <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
   <filter-name>struts2</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

<welcome-file-list>
   <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

posted on 2009-07-29 16:25 jadmin 阅读(78) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: