【发布时间】:2021-06-07 15:37:14
【问题描述】:
我有 ServletContextListener,我在其中初始化数据库 JNDI 轮询,如果发生异常,我发现我将 Attribute 设置为 Servlet Context。
听众:
@WebListener
public class ApplicationListener implements ServletContextListener {
private static final Logger LOGGER = LogManager.getLogger(ApplicationListener.class);
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext ctx = sce.getServletContext();
DAOFactory dao = DAOFactory.getDAOFactory(1);
try {
MySQLDAOFactory.dataSourceInit();
QueriesUtil.getQueries();
} catch (SQLException | NamingException throwables) {
LOGGER.error(throwables);
ctx.setAttribute("Error",throwables.getMessage());
}
ctx.setAttribute("MySQLFactory",dao);
Locale.setDefault(new Locale("ua"));
}
}
前端控制器:
@WebServlet(name = "FrontController", value = "/pages/*")
public class FrontController extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = getServletContext();
String error = (String)context.getAttribute("Error");
if(error!=null){
resp.sendRedirect(req.getContextPath()+"/WEB-INF/view/error.jsp?errorMessage="+error);
}
try {
View view = new View(req, resp);
Action action = ActionFactory.getInstance().getAction(req);
action.execute(view);
view.navigate();
} catch (Exception e) {
resp.sendRedirect(req.getContextPath()+"/WEB-INF/view/error.jsp?errorMessage="+e.getMessage());
}
}
}
FrontController 检查 servlet 上下文以找到此属性,如果它存在,我应该将重定向发送到 errorPage,但我无法访问它。我该如何解决?
【问题讨论】:
标签: java redirect servlets custom-error-pages