在我提交作业之前,老师告诉我,该项目的一个要求是使用servletcontextlistener。我阅读了所有相关内容,但我没有实际操作技能。有人可以解释我如何在我的程序中轻松实现这个方法,它仍然有用吗?谢谢。
任务是建立一个网站(前端)并制作一个表格(后端)。这是servlet代码,我认为你不需要看到HTML和JavaScript。
@WebServlet("/ServletProjekt")
public class ServletProjekt extends HttpServlet{
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String firstName = request.getParameter("förnamn");
String lastName = request.getParameter("efternamn");
String address = request.getParameter("address");
String email = request.getParameter("email");
String howoften = request.getParameter("howoften");
String newsabout = request.getParameter("news");
String[] age = request.getParameterValues("age");
Cookie firstname = new Cookie ("firstname", firstName);
Cookie lastname = new Cookie ("lastname", lastName);
Cookie Address = new Cookie ("Address", address);
Cookie mail = new Cookie ("mail", email);
Cookie HowOften = new Cookie ("HowOften?", howoften);
Cookie news = new Cookie ("news", newsabout);
firstname.setMaxAge(60 * 60 * 24);
lastname.setMaxAge(60 * 60 * 24);
Address.setMaxAge(60 * 60 * 24);
mail.setMaxAge(60 * 60 * 24);
HowOften.setMaxAge(60 * 60 * 24);
news.setMaxAge(60 * 60 * 24);
response.addCookie(firstname);
response.addCookie(lastname);
response.addCookie(Address);
response.addCookie(mail);
response.addCookie(HowOften);
response.addCookie(news );
response.setContentType("text/html");
PrintWriter printWriter = response.getWriter();
printWriter.write("<html>");
printWriter.write("<h1> THANK YOU FOR YOUR INFORMATION</h1>");
printWriter.write("<body>");
printWriter.write("<p>Your name:</p>" + firstName);
printWriter.write("<br>");
printWriter.write("<p>Your last name:</p>" +lastName + "<br>");
printWriter.write("<p>Your address:</p>" +address + "<br>");
printWriter.write("<p>Your choice of often:</p>" +howoften + "<br>");
printWriter.write("<p>Your choice of news:</p>" +newsabout + "<br>");
printWriter.write("<p>Your email:</p>" +email + "<br>");
for (String ages : age) {
printWriter.write("<p>Your age:</p>" +ages + "<br>");
}
printWriter.write("<a href =\"GetAllCookies\">View All Cookies</a>");
printWriter.write("</body>");
printWriter.write("</html>");
}
}
答案 0 :(得分:0)
实现以下界面:
javax.servlet.ServletContextListener
并在web.xml中包含以下内容(将类名替换为正确的名称):
<listener>
<listener-class>com.something.MyContextListener</listener-class>
</listener>
答案 1 :(得分:0)
首先你需要像这样创建
public class yourServletContextListener
implements ServletContextListener{
@Override
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("ServletContextListener destroyed");
}
//Run this before web application is started
@Override
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("ServletContextListener started");
}
}
并将其写入您的web.xml
<listener>
<listener-class>
fully qualified name for yourServletContextListener
</listener-class>