El último artículo configuró el entorno del blog.
Este blog iniciará el aprendizaje básico de Struts1.
1. Primero, comprenda el flujo de trabajo de Struts1:
2. Action, ActionForm, ActionForward, estos tres objetos forman el núcleo de Struts.
El controlador central de Struts es ActionServlet, que intercepta las solicitudes de los usuarios y las transfiere al sistema Struts.
3. Agregue la configuración en web.xml:
<servlet>
<!-- ActionServlet 的名 -->
<servlet-name>action</servlet-name>
<!-- 配置Servlet 的实现类 -->
<servlet-class>
org.apache.struts.action.ActionServlet
</servlet-class>
<!-- 指定Struts 的第一个配置文件 -->
<init-param>
<!-- 指定配置文件的映射 -->
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.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>
<!-- 将ActionServlet配置成自启动Servlet -->
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
4. Implementar y configurar ActionForm:
ActionForm debe heredar la clase base ActionForm proporcionada por Struts. Esta clase es simplemente un JavaBean simple que contiene métodos get y set para cada propiedad.
* El nombre del atributo debe ser el mismo que el nombre en el formulario.
①Realización:
@SuppressWarnings("serial")
public class LoginActionForm extends ActionForm{
private String userName;
private String pswd;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPswd() {
return pswd;
}
public void setPswd(String pswd) {
this.pswd = pswd;
}
}
②Configuración: cree el archivo de configuración struts-config.xml especificado en el archivo web.xml y agregue el atributo <form-beans>
<struts-config>
<form-beans>
<!-- 定义ActionForm,至少指定两个属性: name(自定义) , type LoginActionForm的路径 -->
<form-bean name="loginActionForm" type="com.example.LoginActionForm" />
</form-beans>
</struts-config>
5. Implementar y configurar la acción:
Herede la clase base Action proporcionada por struts, implemente el método de ejecución del tipo ActionFoward y devuelva una URL directa de ActionMapping.
La acción no es segura para subprocesos porque todas las solicitudes comparten una instancia de acción.
①Realización:
public class LoginAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
LoginActionForm lForm = (LoginActionForm) form;
String userName = lForm.getUserName();
String pswd = lForm.getPswd();
if (userName.equals("") || pswd.equals("") || pswd == null
|| userName == null) {
userName = "admin";
pswd = "admin";
}
if ("admin".equals(userName) && "admin".equals(pswd)) {
return mapping.findForward("welcome");
}
return mapping.findForward("error");
}
}
②Configuración:
<struts-config>
<!-- path:定义的路径;type:Action的路径;name:<form-beans>中定义的name,scope范围 -->
<action-mappings>
<action path="/login" type="com.example.LoginAction" name="loginActionForm"
scope="request">
<!-- 配置局部Forward -->
<forward name="welcome" path="/index.jsp" />
<forward name="input" path="/login.jsp" />
</action>
</action-mappings>
</struts-config>
6. Configure el reenvío, incluidos dos tipos de reenvío global y reenvío local. El local es como se muestra arriba, y el nombre es la URL que ejecutará reenviará.
redireccionar: controle si reenviar o redireccionar. Reenvío falso predeterminado: RequestDispatch.forward , redirección verdadera: HttpServletResponse.sendRedirects
reenvío global:
<!--配置全局Forward对象 -->
<global-forwards>
<!--该Forward对象的name 属性为error. 映射资源为/WEB-INF/jsp/error.jsp -->
<forward name="error" path="/error.jsp" />
</global-forwards>
7. Todos los atributos struts-config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration1.2//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">
<struts-config>
<form-beans>
<!-- 定义ActionForm,至少指定两个属性: name(自定义) , type 路径 -->
<form-bean name="loginActionForm" type="com.example.LoginActionForm" />
</form-beans>
<!--配置全局Forward对象 -->
<global-forwards>
<!--该Forward对象的name 属性为error. 映射资源为/WEB-INF/jsp/error.jsp -->
<forward name="error" path="/error.jsp" />
</global-forwards>
<!-- path:定义的路径;type:Action的路径;name:<form-beans>中定义的name,scope范围 -->
<action-mappings>
<action path="/login" type="com.example.LoginAction" name="loginActionForm"
scope="request">
<!-- 配置局部Forward -->
<forward name="welcome" path="/index.jsp" />
<forward name="input" path="/login.jsp" />
</action>
</action-mappings>
</struts-config>
8.login.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="login.do" method="post">
<p>用户名:</p><input name="userName" type="text"/><br>
<p>密码:</p><input name="pswd" type="password"/> <br>
<input type="submit" value="登陆" />
</form>
</body>
</html>