對於采用Struts框架的Web應用,我們通過實例來介紹一下其基本流程.
action org.apache.struts.action.ActionServlet config /WEB-INF/struts-config2.xml debug 2 detail 2 2 action *.do
public class LoginAction extends Action {
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
UserActionForm userForm=(UserActionForm)form;
String userName=userForm.getName();
int password=userForm.getPassword();
UserManage userManage=new UserManage();
User user=new User();
user.setName(userName);
user.setPassword(password);
try {
userManage.ValidateUser(user);
return mapping.findForward("success");
} catch (UserNotFoundException e) {
e.printStackTrace();
request.setAttribute("message", e.getMessage());
}catch(PasswordErrorException e){
e.printStackTrace();
request.setAttribute("message", e.getMessage());
}
return mapping.findForward("fail"); }
public class UserActionForm extends ActionForm {
private String name;
private int password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPassword() {
return password;
}
public void setPassword(int password) {
this.password = password;
}
}
public class UserManage {
public void ValidateUser(User user) {
// 判斷用戶名密碼是否正確
if (!"admin".equals(user.getName())) {
throw new UserNotFoundException("用戶不存在!用戶名為:" + user.getName());
} else if (user.getPassword() != 123456) {
throw new PasswordErrorException("密碼錯誤");
}
}}