java - 如何在运行 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 里面有查询
再次:我只是希望它在页面加载时运行相同的代码并且所有数据都应该加载(不点击提交)
谢谢您的帮助
解决方案
您可以使用 jstl 或表达式语言在请求范围内设置值。
request.setAttribute("si", si);
就像是:
Student id <input type="text" name = "sid" value="${requestScope.si.id}">
推荐阅读
- sql - 如何从 JSON SQL 访问嵌套值(AWS IoT SQL 规则)
- python - 如何在 Python 中访问嵌套字典中的元素
- php - PHP cURL 中的 .P12 证书到端点
- python - 使用 fig.transFigure 在 ylabel 上绘制补丁
- docker - 在 dockerfile [解决] 中将 .zip 转换为 tar.gz
- r - 绘制具有辅助轴的多个值
- firebase - 限制来自其他用户的 Firebase 用户 ID 令牌
- c# - 如何将字符串分隔到其他文本框
- scala - Spark在csv的行首写一个空格
- javascript - 在反应中 - 将数组从子组件更新到父组件