比较会话值是否与文本框值匹配

时间:2014-10-02 02:43:44

标签: java jsp

您好我可以在我的jsp中获取会话值,现在我想比较会话值是否与文本框匹配,如果匹配,它会将用户重定向到另一个页面,否则它将保持同一页面,我是不知道怎么办,请帮忙。非常感谢!

JSP

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Factorial</title>
</head>
<body>
<form action="fact" method="POST">
Enter a number: <input type="text" name="num">
<input type="submit"/>
<%= session.getAttribute( "money" ) %>,
</form>
</body>
</html>

的Servlet

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub

    HttpSession session = request.getSession();

         String text = request.getParameter("money");

         int money = (Integer)session.getAttribute("money");   

         String testing = String.valueOf(money);

    if(text == testing)
    {

    RequestDispatcher rd = request.getRequestDispatcher("MainPage");
    rd.forward(request, response);
}
else
{
  response.redirect("Errorpage.jsp");
}

1 个答案:

答案 0 :(得分:0)

假设您已经有一个名为&#34; money&#34;的Session属性,您将无需从JSP访问它

  <body>
    <form action="fact" method="POST">
    Enter a number: <input type="text" name="num">
    <input type="submit"/>
    </form>
  </body>




    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {



            HttpSession session = request.getSession();

                 String text = request.getParameter("num");

                 int money = (Integer)session.getAttribute("money");   

                 String testing = String.valueOf(money);

            if(testing.equalsIgnoreCase(text))
            {

            RequestDispatcher rd = request.getRequestDispatcher("MainPage");
            rd.forward(request, response);
        }
        else
        {
          response.sendRedirect("Errorpage.jsp");
        }
        }

如果你还没有创建名为&#34; money&#34;但是想要在jsp中创建它,你必须使用Scriptlet。

        <body>
        <form action="abc.do" method="POST">
        Enter a number: <input type="text" name="num">
        <input type="submit"/>
        <% session.setAttribute("money",1000); %>,
        </form>
        </body>