`
yeluowuhen
  • 浏览: 155947 次
  • 性别: Icon_minigender_2
  • 来自: 北京
社区版块
存档分类
最新评论

基于Struts的第一个项目(续)

阅读更多
    在前面写的项目中,加入一个UserManger类,处理从ActionForm中传来的参数,并加入异常处理机制,当用户名及密码有一个出错时,给出警告。下面是Action类的源码:
public class LoginAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse resp) throws Exception {
		// TODO Auto-generated method stub
		LoginActionForm laf = (LoginActionForm)form;
		String username = laf.getUsername();
		String password = laf.getPassword();
		
		String errorInfo="";
		try{
			UserManager.getInstance().login(username, password);
			System.out.println("success");
			req.setAttribute("username", username);
			return mapping.findForward("success");
		}catch(UsernameNotFoundException e){
			errorInfo = "未找到用户名为["+username+"]";
			e.printStackTrace();
		}catch(PasswordErrorException e){
			errorInfo = "密码错误";
			e.printStackTrace();
		}
		req.setAttribute("errorInfo", errorInfo);
		System.out.println(errorInfo);
		return mapping.findForward("error");
	}
	
}

UserMananger的源码如下所示,其中运用到的单一模式:
public class UserManager {
	private static  UserManager instance = new UserManager();
	private UserManager(){
		
	}
	public static UserManager getInstance(){
		return instance;
	}
	public void login(String username,String password){
		if(!"admin".equals(username)){
			throw new UsernameNotFoundException();
		}
		if(!"admin".equals(password)){
			throw new PasswordErrorException();
		}
	}
}

UsernameNotFoundException及PasswordErrorException继承了RuntimeException类。在修改过程中出现又因为粗心出现结果相反的情形,并且在页面中获得参数,为request.getAttribute()方法。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics