I do the homepage on JSP and came across such a problem:

  • I start the server
  • Waiting for the warm
  • Index.jsp opens
  • Up to this point, all is well, NOOO ....

It does not open due to the fact that I load a list from a database connected to one class that processes my data, and this error occurs:

Mistake

The fact is that after opening it does not connect to the servlet, does not know what is happening there at all, does not know what points.size(); points.get(); points.size(); points.get(); .

But once I write localhost:8080/user , that is, call the servlet:

 public class UserServlet extends javax.servlet.http.HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Connection con = null; Statement st = null; ResultSet rs = null; String url = "jdbc:mysql://localhost:3306/joker"; String user = "user"; String password = "password"; ArrayList<Point> points = new ArrayList<Point>(); String message = null; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection(url, user, password); st = con.createStatement(); rs = st.executeQuery("SELECT * FROM joker.point;"); while (rs.next()) { Point p = new Point(); p.setId(rs.getInt("id")); p.setName(rs.getString("name")); points.add(p); } if (rs.next()) { message = rs.getString(1); } } catch (SQLException | ClassNotFoundException ex) { message = ex.getMessage(); } finally { try { if (rs != null) { rs.close(); } if (st != null) { st.close(); } if (con != null) { con.close(); } } catch (SQLException ex) { message = ex.getMessage(); } } String page; try { page = request.getParameter("page"); } catch (Exception e) { page = "home"; } request.setAttribute("points", points); request.setAttribute("page", page); request.setAttribute("message", message); if (page != null) { switch (page) { case "about": request.getRequestDispatcher("/about.jsp").forward(request, response); break; case "contact": request.getRequestDispatcher("/contact.jsp").forward(request, response); break; default: request.getRequestDispatcher("/index.jsp").forward(request, response); break; } } else { request.getRequestDispatcher("/index.jsp").forward(request, response); } } } 

If I call this servlet, everything will work.

JSP file:

 <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@page import="model.*" %> <%@ page import="java.util.List,java.util.ArrayList,java.util.Iterator"%> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Joker</title> <!-- Bootstrap Core CSS --> <link href="css/bootstrap.css" rel="stylesheet"> <!--[if lt IE 9]> <script src="js/html5shiv.js"></script> <script src="js/respond.js"></script> <![endif]--> </head> <body> <% out.println("Your IP address is " + request.getRemoteAddr()); ArrayList<Point> points = (ArrayList<Point>) request.getAttribute("points"); %> <%@ include file="_menu.jsp" %> <br/> <div class="row"> <div class="col-md-12"> <h1>Home</h1> <p>${page}</p> <p>${message}</p> <ul> <% for (int i = 0; i < points.size(); i++) { %> <li> <%= points.get(i).getId() %> : <%= points.get(i).getName() %> </li> <%}%> </ul> </div> </div> <!-- jQuery --> <script src="js/jquery.js"></script> <!-- Bootstrap Core JavaScript --> <script src="js/bootstrap.js"></script> </body> </html> 

How to make my "super site" immediately open to a servlet when opened?

Or are there alternative methods?

  • I still don’t like the data displayed in your .jsp file. Regardless of whether someone will help you correct the error or not, look at JSTL or something like that. - Regent
  • @Regent I inserted the codes) Everything only works if you write LOCALHOST: 8080 / USER, that is, after you access the servlet, if you work with servlets and you are a master, then tell me how to do so after deploying it immediately to the servlet? PS: I'm not a developer, I'm just learning to master JavaEE) - E1mir
  • And how, by the way, does not work? That is what needs to be written in the browser so that the 500th error appears (what address is displayed in the browser at a delay)? No, I am not a servlet master: I did just one small project. - Regent
  • In WEB-INF / web.xml , by the way, there is a <welcome-file-list><welcome-file>адрес</welcome-file></welcome-file-list> . - Regent

1 answer 1

Probably too late to answer, but still.

If you need to load data from the database before displaying the page, then first you need to start the controller (servlet) , which will load this data, put it in the request attributes and “delegate” the request to the desired page using RequestDispatcher .

In order to ensure that the user cannot open the page directly, you can place the page in the WEB-INF folder. All pages in this folder (and any subfolder) will not be accessible to the user (even if he enters the /RootDir/WEB-INF/page.jsp path to it, the server will return 404).

If you need to load data once immediately after deploying your application, you can use event listeners . The Java Servlet spec is defined by the following listeners:

  • ServletContextListener
  • ServletContextAttributeListener
  • HttpSessionListener
  • HttpSessionActivationListener
  • HttpSessionAttributeListener
  • HttpSessionAttributeListener
  • ServletRequestListener
  • ServletRequestAttributeListener

In this case, you need a ServletContextListener - listens for the creation and destruction events of a ServletContext :

 public class YourListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent event) { ServletContext ctx = event.getServletContext(); /* 1. Соединяетесь с базой данных 2. Достаете данные 3. Кладете их в качестве атрибутов ServletContext: ctx.setAttribute("attributeName", attributeValue) */ } @Override public void contextDestroyed(ServletContextEvent event) {} } 
  • Come on, why it's too late, think two years have passed :) Although the answer will still not be superfluous (if it is correct) if someone else with a similar problem stumbles upon this question. - Peter Samokhin
  • @PeterSamokhin Haha)) Damn, to be honest, I don’t know the correct answer or not, I don’t even remember if I found the answer to it) I already forgot and scored on JSP) :) But thanks guy, reminded me of my past, my first endeavors))) - E1mir
  • one
    @ E1mir,;)))))) - not a Programmer