简体   繁体   English

带有Servlet + Java的HttpSession无法正常工作

[英]HttpSession with Servlet + Java not working

i have the following pice of code 'anmelden.java': 我有以下代码'anmelden.java'的价格:

@WebServlet("/anmelden")
public class anmelden extends HttpServlet {
private static final long serialVersionUID = 1L;

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

    String benutzer = request.getParameter("benutzer"); 
    String passwort = request.getParameter("passwort");

    try {
        PrintWriter out = response.getWriter();
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test","admin","*****");
        PreparedStatement stmt = con.prepareStatement("SELECT benutzer,passwort,rolle FROM login WHERE benutzer = ? AND passwort = ?");
        stmt.setString(1, benutzer);
        stmt.setString(2, passwort);
        ResultSet rs = stmt.executeQuery();


        if(rs.next())
        {

            HttpSession session = request.getSession();
            session.setAttribute("benutzer", rs.getString("benutzer"));
            RequestDispatcher dis = request.getRequestDispatcher("mandant.jsp");
            dis.forward(request, response);

            out.print("1");

        }
        else
        {
            out.print("Benutzername und/oder Passwort falsch");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
  }
}

This is my jsp file 'login.jsp': 这是我的jsp文件“ login.jsp”:

        $("#anmelden").click(function(){

            var benutzer = $("#benutzer").val();
            var passwort = $("#passwort").val();

            if(benutzer == "" || passwort == "")
                {
                return;
                }
            $.ajax({
                url:"anmelden",
                type:"POST",
                data:"benutzer="+benutzer+"&passwort="+passwort
            }).success(function(data){              
                var erfolg = data;
                if(erfolg == "1")
                {
                    window.location.href="http://localhost:8080/PSD/mandant.jsp";                       
                    }
                else
                    {
                    $("#ok").text(erfolg);
                    }
            });
        });

As u can see i tries to set the name coming from my DB into my session Attribute. 如您所见,我尝试将来自数据库的名称设置为会话属性。 I want to use the Attribute in my 'mandant.jsp' file. 我想在“ mandant.jsp”文件中使用该属性。 But it dosen't work - all what happens is, that my 'login.jsp' file which makes the ajax call, print the code from 'mandant.jsp' into my div as text . 但这行不通-发生的一切是,我的进行ajax调用的'login.jsp'文件将代码从 'mandant.jsp' 打印 为text到我的div So it dosen't opend the next page as i want -.- 所以它并没有按照我的要求打开下一页-.-

But if i comment out the HttpSession block then it works fine but then i can't use ,of course,the session Attribute. 但是,如果我注释掉HttpSession块,那么它可以正常工作,但是我当然不能使用session Attribute。

So what's wrong or what must i change so that this code works? 那么,什么地方出错或必须更改什么才能使此代码起作用?

Many thanks 非常感谢

This is because this part of the code: 这是因为这部分代码:

RequestDispatcher dis = request.getRequestDispatcher("mandant.jsp");
dis.forward(request, response);

is generating the HTML from mandant.jsp file using the request object (along with HttpSession and ServletContext ) to fulfill any Expression Language and writing this HTML into the response. 正在使用请求对象(以及HttpSessionServletContext )从mandant.jsp文件生成HTML,以实现任何表达式语言并将该HTML写入响应中。 Just remove these lines and you'll be ok. 只需删除这些行,您就可以了。

You are mixing two types of communication here, from the JSP page you are making an ajax call but from the Servlet you are making a Dispatch redirect. 您在这里混合了两种类型的通信,在JSP页面中进行的是ajax调用,而在Servlet中进行的是Dispatch重定向。

If you want the login page to be redirected after aa successful login then don't call the Servlet with an ajax call and better do a form submit. 如果您希望成功登录后重定向登录页面,则不要使用ajax调用来调用Servlet,最好进行表单提交。

If you rather want to only check credentials on the servlet and redirect from the client then keep the ajax call but avoid the request dispatcher in the servlet and return a success/error code instead. 如果您只想检查servlet上的凭据并从客户端重定向,则保留ajax调用,但避免servlet中的请求分配器,而是返回成功/错误代码。 Then capture that code from the ajax response and redirect to a successful page if you want. 然后从ajax响应中捕获该代码,并根据需要重定向到成功的页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM