用Struts开发基于MVC的Web应用

http://tech.ddvip.com   2006年11月25日    社区交流

本文详细介绍用Struts开发基于MVC的Web应用

  接着是controller层。controller层由ActionForm、Action两个类实现。ActionForm类很简单,主要是对应model(本例中是一个简单的JavaBean对象)。

package com.samjdalton.struts;
import org.apache.struts.action.ActionForm;
public class LoginForm extends ActionForm {
 private LoginBean bean;
 public LoginForm() {
  this.bean=new LoginBean();
 }
 public LoginForm(LoginBean bean) {
  this.bean = bean;
 }
 public void setUsername(String username) {
  bean.setUsername(username);
 }
 public String getUsername() {
  return bean.getUsername();
 }
 public void setPassword(String password) {
  bean.setPassword(password);
 }
 public String getPassword() {
  return bean.getPassword();
 }
}

  Action类用上面的ActionForm从view获得信息,并且修改model状态。

  Action类代码如下:

package com.samjdalton.struts;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
public class LoginAction extends Action {
 public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm,  javax.servlet.http.HttpServletRequest httpServletRequest,  javax.servlet.http.HttpServletResponse httpServletResponse) throws Exception {
// check the username
 LoginForm form = (LoginForm) actionForm;
 if (form.getUsername().equalsIgnoreCase("sam") &&      form.getPassword().equals("password")) {
 // we are in
  return actionMapping.findForward("success");
 } else {
 // not allowed
  return actionMapping.findForward("failure");
 }
}
public ActionErrors validate(ActionMapping actionMapping
HttpServletRequest httpServletRequest) {
 ActionErrors errors = new ActionErrors();
 if ( getUsername() == null || getUsername().length() < 1 ) {
  errors.add("name",new ActionError("error.name.required"));
 }
 if ( getPassword() == null || getPassword().length() < 1 ) {
  errors.add("pw",new ActionError("error.pw.required"));
 }
 return errors;
}

  可以看到,action检查用户在username、password是否输入了"sam"、"password"。如果输入正确,action指明要调用的下一个view。

责编:豆豆技术应用

正在加载评论...