首页 > 解决方案 > 如何在运行 JSP 页面之前运行 Servlet?

问题描述

目标:我只有一页,当页面加载时,它应该从 servlet 运行查询并在 index.jsp 页面上显示所有值。

存在的问题:当我将页面从“提交”按钮提交到另一个页面时,它工作正常,但是当我加载页面 index.jsp 时,它会给出 NullPointerException,因为 servlet 没有在 index.jsp 页面之前运行。

我的小服务:

public class GetStudentController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        StudentDao sd = new StudentDao();  // model
        StudentInfo si = sd.getInfo();

        request.setAttribute("si", si);

        RequestDispatcher rd = request.getRequestDispatcher("display.jsp");
        rd.forward(request, response);
}
}

我的 JSP:

<body>
<form action="displayStud">         <--my servlet controller name -->
Student id <input type="text" name = "sid">
<button name="test" type="submit"">Primary Button</button>
</body>
</html>

<button type="submit" class="btn btn-primary" name="action" formaction="ddd" value="find">Test2</button>
    <!-- <input type ="submit" value ="Submit"> -->
</form>

StudentDao 里面有查询

再次:我只是希望它在页面加载时运行相同的代码并且所有数据都应该加载(不点击提交)

谢谢您的帮助

标签: javahtmljsp

解决方案


您可以使用 jstl 或表达式语言在请求范围内设置值。

request.setAttribute("si", si);

就像是:

Student id <input type="text" name = "sid" value="${requestScope.si.id}">

推荐阅读