![](/img/trans.png)
[英]How can I access the servlet application context from Struts 2 tags?
[英]How can i refresh servlet context variables i have set in a ServletContextListener?
我正在使用 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");
}
}
在更改數據庫后,此方法可用作 servlet 內部的解決方法,只需覆蓋已更改的上下文變量
request.getServletContext().setAttribute("states", TypeDb.getActiveStates());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.