对于采用Struts框架的Web应用,我们通过实例来介绍一下其基本流程.
<form action="login.do" method="post"> 用户:<input type="text" name="username"><br> 密码:<input type="password" name="password"></br> <input type="submit" value="登录"> </form>
<servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config2.xml</param-value> </init-param> <init-param> <param-name>debug</param-name> <param-value>2</param-value> </init-param> <init-param> <param-name>detail</param-name> <param-value>2</param-value> </init-param> <load-on-startup>2</load-on-startup> </servlet> <!-- Standard Action Servlet Mapping --> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
<struts-config> <form-beans> <form-bean name="loginForm" type="com.bjpowernode.struts.LoginActionForm"/> </form-beans> <action-mappings> <action path="/login" type="com.bjpowernode.struts.LoginAction" name="loginForm" scope="request" > <forward name="success" path="/login_success.jsp" /> <forward name="error" path="/login_error.jsp"/> </action> </action-mappings> </struts-config>
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("密码错误"); } }}