Crear una página de error no encontrado 404 con Struts 2
Es necesario implementar un Unknown Handler (están disponibles desde la versión Struts 2.1 en adelante)
http://struts.apache.org/docs/unknown-handlers.html
PageNotFoundAction.java
package com.test; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Actions; import org.apache.struts2.convention.annotation.Result; import org.apache.struts2.dispatcher.Dispatcher; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.UnknownHandler; import com.opensymphony.xwork2.XWorkException; import com.opensymphony.xwork2.config.ConfigurationManager; import com.opensymphony.xwork2.config.RuntimeConfiguration; import com.opensymphony.xwork2.config.entities.ActionConfig; public class PageNotFoundAction extends ActionSupport implements UnknownHandler{ private static final long serialVersionUID = 9086900467866735407L; @Actions({ @Action(value = "pageNotFound", results = @Result(name = "success", location = "/error.jsp")) }) public String execute() { ServletActionContext.getResponse().setStatus(HttpServletResponse.SC_NOT_FOUND); return SUCCESS; } @Override public ActionConfig handleUnknownAction(String namespace, String actionName) throws XWorkException { ConfigurationManager configurationManager = Dispatcher.getInstance().getConfigurationManager(); RuntimeConfiguration runtimeConfiguration = configurationManager.getConfiguration().getRuntimeConfiguration(); ActionConfig actionConfig = runtimeConfiguration.getActionConfig(namespace, actionName); if(actionConfig == null) { // invalid url request, and this need to be handled actionConfig = runtimeConfiguration.getActionConfig("", "pageNotFound"); } return actionConfig; } @Override public Object handleUnknownActionMethod(Object arg0, String arg1) throws NoSuchMethodException { // TODO Auto-generated method stub return null; } @Override public com.opensymphony.xwork2.Result handleUnknownResult( ActionContext arg0, String arg1, ActionConfig arg2, String arg3) throws XWorkException { // TODO Auto-generated method stub return null; } }
error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Test</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <p> 404 PAGE NOT FOUND! </p> </body> </html>
struts.xml
- añade la siguiente línea a tu struts.xml
<bean type="com.opensymphony.xwork2.UnknownHandler" name="handler" class="com.test.PageNotFoundAction"/>
Notas
- He estado buscando una manera más elegante para devolver un status 404 con Struts 2. Si lo encuentras dímelo.