如何刷新我在 ServletContextListener 中设置的 servlet 上下文变量?
Posted
技术标签:
【中文标题】如何刷新我在 ServletContextListener 中设置的 servlet 上下文变量?【英文标题】:How can i refresh servlet context variables i have set in a ServletContextListener? 【发布时间】:2020-07-28 20:06:44 【问题描述】:我正在使用 Servlet 上下文侦听器进行大学作业,其中一些上下文变量是从数据库中设置的。但是当我将记录添加到数据库中的这些列表时,它们不会更新。他们有办法做到这一点吗?
ServletContextListner:
import edu.witc.pethotel.business.DispositionType;
import edu.witc.pethotel.business.Gender;
import edu.witc.pethotel.business.PetType;
import edu.witc.pethotel.business.State;
import edu.witc.pethotel.data.CustomerDB;
import edu.witc.pethotel.data.TypeDb;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class MyServletContextListener implements ServletContextListener
@Override
public void contextInitialized(ServletContextEvent event)
ServletContext sc = event.getServletContext();
//initialize customer service email
String custServEmail = sc.getInitParameter("custServEmail");
sc.setAttribute("custServeEmail", custServEmail);
//initialize current year
GregorianCalendar currentDate = new GregorianCalendar();
int currentYear = currentDate.get(Calendar.YEAR);
sc.setAttribute("currentYear", currentYear);
//initialize list of gender
ArrayList<Gender> genders = TypeDb.getAllGenders();
sc.setAttribute("genders", genders);
//initialize list of disposition
ArrayList<DispositionType> dispositions = TypeDb.getAllDispositions();
sc.setAttribute("dispositions", dispositions);
//initialize list of state
ArrayList<State> states = CustomerDB.getActiveStates();
sc.setAttribute("states", states);
//initialize list of pet type
ArrayList<PetType> petType = TypeDb.getActivePetTypes();
sc.setAttribute("petTypes", petType);
@Override
public void contextDestroyed(ServletContextEvent event)
ServletContext sc = event.getServletContext();
sc.removeAttribute("genders");
sc.removeAttribute("dispositions");
sc.removeAttribute("states");
sc.removeAttribute("petTypes");
【问题讨论】:
【参考方案1】:在更改数据库后,此方法可用作 servlet 内部的解决方法,只需覆盖已更改的上下文变量
request.getServletContext().setAttribute("states", TypeDb.getActiveStates());
【讨论】:
以上是关于如何刷新我在 ServletContextListener 中设置的 servlet 上下文变量?的主要内容,如果未能解决你的问题,请参考以下文章