提示:現代項目請使用 Spring Boot + Spring MVC,本文僅作為遺留系統維護參考。
Welcome_SS/
├── WebRoot/
│ ├── index.jsp
│ ├── login.jsp
│ ├── reinput_blank.jsp
│ ├── reinput_error.jsp
│ └── success.jsp
├── src/
│ └── com/yourcompany/struts/
│ ├── LoginAction.java
│ └── LoginForm.java
└── WEB-INF/
├── struts-config.xml
├── applicationContext.xml
└── web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<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>1</load-on-startup>
</servlet>
<bean name="/login" class="com.yourcompany.struts.LoginAction">
<property name="userService" ref="userService"/>
</bean>
<bean id="userService" class="com.yourcompany.service.UserServiceImpl"/>
<form-beans>
<form-bean name="loginForm" type="com.yourcompany.struts.LoginForm"/>
</form-beans>
<action-mappings>
<action path="/login" type="/login" name="loginForm" scope="request" validate="true" input="/login.jsp">
<forward name="success" path="/success.jsp"/>
<forward name="blank" path="/reinput_blank.jsp"/>
<forward name="error" path="/reinput_error.jsp"/>
</action>
</action-mappings>
public class LoginForm extends ActionForm {
private String username;
private String password;
// getter/setter
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if (username == null || username.trim().isEmpty())
errors.add("username", new ActionMessage("error.username.required"));
if (password == null || password.trim().isEmpty())
errors.add("password", new ActionMessage("error.password.required"));
return errors;
}
}
public class LoginAction extends Action {
private UserService userService; // Spring 注入
public void setUserService(UserService userService) { this.userService = userService; }
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
LoginForm lf = (LoginForm) form;
if (userService.authenticate(lf.getUsername(), lf.getPassword())) {
request.getSession().setAttribute("user", lf.getUsername());
return mapping.findForward("success");
}
return mapping.findForward("error");
}
}
index.jsp → 點擊登錄鏈接 → login.jsp/login.do → LoginAction 處理reinput_blank.jsp 或 reinput_error.jspsuccess.jsp 顯示歡迎信息scope="prototype" 或使用 DelegatingActionProxy。<html:text property="username"/> 自動回顯。