LoginAction
package k.action; import k.form.UserForm; import org.apache.struts.action.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginAction extends Action { @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { UserForm userForm = (UserForm) form; System.out.println(userForm.getUserName() + "=====" + userForm.getPassword()); if ("1".equals(userForm.getPassword())) { return mapping.findForward("ok"); } else { return mapping.findForward("err"); } } }
UserForm
package k.form; import org.apache.struts.action.ActionForm; public class UserForm extends ActionForm { private String userName; private String password; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
struts-config.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd"> <struts-config> <form-beans> <form-bean name="userForm" type="k.form.UserForm"></form-bean> </form-beans> <action-mappings> <!-- name用于关联某个表单 【path 需要 加 “/”】--> <action name="userForm" path="/login" type="k.action.LoginAction"> <forward name="ok" path="/WEB-INF/wel.jsp"></forward> <forward name="err" path="/WEB-INF/err.jsp"></forward> </action> </action-mappings> </struts-config>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <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-config.xml</param-value> </init-param> <load-on-startup>2</load-on-startup> </servlet> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
index.jsp
<body> <jsp:forward page="WEB-INF/login.jsp"></jsp:forward> </body>
login.jsp
<form action="/login.do" method="post"> 账号:<input type="text" name="userName"> <br> 密码: <input type="password" name="password"> <br> <input type="submit" value="submit"> <br> </form>