目标: 我只有一页,当页面加载时,它应该从 servlet 运行查询并在 index.jsp 页面上显示所有值。
现有问题: 当我从“提交”按钮将页面提交到另一个页面时,它工作正常,但是当我使用值加载页面index.jsp时,它会给出NullPointerException,因为servlet没有在index.jsp页面之前运行。
我的Servlet:
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 中有查询
再次: 我只是希望它在页面加载时运行相同的代码,并且所有数据都应该加载(无需单击提交)
感谢您的帮助
最佳答案
您可以使用jSTL或表达式语言在请求范围内设置的值。
request.setAttribute("si", si);
类似于:
Student id <input type="text" name = "sid" value="${requestScope.si.id}">
关于java - 如何在运行JSP页面之前运行Servlet?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61600545/