我的目标是提供在网站上发送评论或评论的能力。当我从表单中获取参数时,它们被正确地添加到我的评论数据库中。但问题是URL包含参数。因此,当我填写表单并按下提交按钮时,数据库中有一条新记录,但注释不会立即显示在页面上。此外,当我刷新页面时,相同的记录在数据库中重复。我希望用户填写表单,按下按钮,然后使用他的评论或评论重定向到同一页面。这是我的servlet doGet方法代码:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Query query = new Query();
Object allReviews = query.getAllReviews();
request.setAttribute("allReviews", allReviews);
RequestDispatcher rd = request.getRequestDispatcher("reviews.jsp");
rd.forward(request, response);
if (request.getParameter("sendReviewButton") != null){
String userName = request.getParameter("reviewName");
String eMail = request.getParameter("reviewMail");
String reviewList = request.getParameter("reviewText");
query.addReview(userName, eMail, reviewList);
}
}
我在jsp中的表单:
<form action = "${pageContext.request.contextPath}/Reviews" method="get">
<p>Your name: <input type="text" size="107" name="reviewName" required></p>
<p>Your e-mail: <input type="text" size="90" name="reviewMail" required></p>
<p>Your review:</p>
<p><textarea rows="15" cols="135" name="reviewText" ></textarea></p>
<input type="submit" value="Send" name="sendReviewButton" class="btn btn-primary btn-lg" id="send-btn">
</form>
答案 0 :(得分:1)
答案 1 :(得分:0)
您正在转发到JSP页面,但这并不能解决刷新问题。正如您在问题中已经说过的那样,解决方案是重定向到JSP:
response.sendRedirect("reviews.jsp"); // url of the JSP page.
这会将HTTP重定向发送回浏览器,然后浏览器会对reviews.jsp
执行新的GET。
答案 2 :(得分:0)
我添加了else语句。因此,正确添加了新的评论,它会立即显示在页面上。当我刷新页面时,数据库中的记录不会重复:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Query query = new Query();
if (request.getParameter("sendReviewButton") != null){
String userName = request.getParameter("reviewName");
String eMail = request.getParameter("reviewMail");
String reviewList = request.getParameter("reviewText");
query.addReview(userName, eMail, reviewList);
Object allReviews = query.getAllReviews();
request.setAttribute("allReviews", allReviews);
response.sendRedirect("/ScopeSoftware/Reviews");
}else {
Object allReviews = query.getAllReviews();
request.setAttribute("allReviews", allReviews);
RequestDispatcher rd = request.getRequestDispatcher("reviews.jsp");
rd.forward(request, response);
}
}