我正在编写一个JSP页面,用户可以通过单选按钮选择一个选项 按下提交后,该值将传递给servlet,它将检查值并更改为某个页面, 这是代码: JSP
<form method="GET" action='Controller' name=main>
<input type="radio" name=dorr value=dog>dog<br>
<input type="radio" name=dorr value=rabbit>rabbit<br>
<input type="submit"name=sub value=submit>
</form>
的Servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String forward="";
String temp = request.getParameter("dorr");
if (temp=="dog"){
forward = DOG_JSP;
} else if (temp=="rabbit"){
forward = RABBIT_JSP;
} else forward = MAIN_JSP;
RequestDispatcher view = request.getRequestDispatcher(forward);
view.forward(request, response); }
奇怪的是,页面不断变换到同一页面(正确意味着temp
没有正确的值),但我检查了它正常工作的参数(显示狗或兔子)
为什么页面没有改变?
答案 0 :(得分:1)
这是因为您使用==
来比较字符串值。
因此,请始终使用equals()
来比较字符串值,而不是==
。
了解更多: Difference between Equals/equals and == operator?
试试这个。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String forward="";
String temp = request.getParameter("dorr");
if (temp.equals("dog")){
forward = DOG_JSP;
} else if (temp.equals("rabbit")){
forward = RABBIT_JSP;
} else {
forward = MAIN_JSP;
}
RequestDispatcher view = request.getRequestDispatcher(forward);
view.forward(request, response);
}