欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-04-17 08:14:53
...
在前面写的项目中,加入一个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()方法。
相关标签: Struts