英文:
How to run Servlet before running JSP page?
问题
目标:
我只有一个页面,当页面加载时,它应该运行来自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(); // 模型
StudentInfo si = sd.getInfo();
request.setAttribute("si", si);
RequestDispatcher rd = request.getRequestDispatcher("display.jsp");
rd.forward(request, response);
}
}
我的JSP:
<body>
<form action="displayStud"> <!--我的servlet控制器名称-->
学生ID <input type="text" name="sid">
<button name="test" type="submit">主要按钮</button>
</form>
<button type="submit" class="btn btn-primary" name="action" formaction="ddd" value="find">Test2</button>
<!-- <input type="submit" value="Submit"> -->
</body>
</html>
StudentDao中有一个查询。
再次强调:
我只想在页面加载时运行相同的代码,并且所有数据都应该加载(无需点击提交按钮)。
感谢您的帮助。
英文:
Goal:
I have only one page and when page loads, it should run the query from servlet and display all values on index.jsp page.
Existing problem:
when i am submitting the page from "Submit" button to another page, it works fine but when i load page index.jsp with values, its gives NullPointerException because servlet didn't run before the index.jsp page.
My Servelet:
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);
}
}
my 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 has query in there
Again:
I just want it to run the same code on page load and all data should load(without click on submit)
Thanks for the help
答案1
得分: 0
你可以使用 jstl 或表达式语言中请求范围中设置的值。
request.setAttribute("si", si);
类似于:
学生ID <input type="text" name="sid" value="${requestScope.si.id}">
英文:
You can use the value set in the request scope using jstl or expression language.
request.setAttribute("si", si);
Something like:
Student id <input type="text" name = "sid" value="${requestScope.si.id}">
专注分享java语言的经验与见解,让所有开发者获益!
评论