与jdbc连接时servlet没有响应

时间:2017-12-31 08:04:29

标签: javascript java servlets jdbc xmlhttprequest

我正在使用java中的servlets类创建一个Web应用程序,用于后端,javascript和html用于前端,我试图访问servlet中的数据库以在post请求中创建验证(即:登录,上传图像),当我创建了一个新的数据库类实例(在servlet类的方法函数中),客户端没有收到服务器应该发送的json。

我没有收到任何错误,只是没有发回回复。

我想知道为什么会发生这种情况,我对servlet来说是个新手

Servlet类,Login.java:

import java.io.IOException;
import java.io.PrintWriter;
import java.util.stream.Collectors;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.json.JSONObject;

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

public Login() {
    super();
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    HttpSession session = request.getSession();
    JSONObject reqBody = new JSONObject(request.getReader().lines().collect(Collectors.joining(System.lineSeparator())));
    JSONObject json = new JSONObject();
    Database db = new Database("postgresql", "localhost", "5432", "first_project", "postgres", "masterkey");
    if(session.isNew()) {
        if(db.checkUser(reqBody.getString("email"), reqBody.getString("pass")) == true) {
                if (db.isAdmin(reqBody.getString("email"))) {
                    storeValue(reqBody.getString("email"), reqBody.getString("pass"), true, session);
                    json.put("status", "200");
                } else {
                    storeValue(reqBody.getString("email"), reqBody.getString("pass"), false, session);
                    json.put("status", "200");
                }
        } else {
                session.invalidate();
            }           
    } else {
        json.put("status", "you're already logged in");
    }   
    out.println(json.toString());       
    }

private void storeValue(String email, String password, boolean admin, HttpSession session) {
    if(email == null) {
        session.setAttribute("email", "");
        session.setAttribute("password", "");
        session.setAttribute("admin", "");
    } else {
        session.setAttribute("email", email);
        session.setAttribute("password", password);
        session.setAttribute("admin", admin);
    }
}

Database.java:

public class Database {

    protected ResultSet rs;
    protected ResultSetMetaData rsmd;
    protected JSONArray table;
    protected JSONObject row;
    protected PreparedStatement pstmt;
    protected Connection con;

    public Database(String jdbc,String host,String port, String db, String user, String pass){
        try {
            Class.forName("org.postgresql.Driver");
            this.con= DriverManager.getConnection("jdbc:"+jdbc+"://"+host+":"+port+"/"+db,user,pass);
        }
        catch(Exception e){
            e.getStackTrace();
        }
    }

    public boolean checkUser(String email, String password) {
        boolean st = false; 
        try {
                this.pstmt = con.prepareStatement("SELECT * FROM users WHERE email=? and password=?");
                this.pstmt.setString(1, email);
                this.pstmt.setString(2, password);
                this.rs = this.pstmt.executeQuery();
                st = this.rs.next();
        } catch (Exception e) { 
            e.printStackTrace();
        }
        return st;
    }

    public boolean isAdmin(String email) {
    boolean st = false;
    try {
        this.pstmt = con.prepareStatement("SELECT admin FROM users WHERE email=?");
        this.pstmt.setString(1, email);
        this.rs = this.pstmt.executeQuery();
        rs.next();
        if(this.rs.getString("admin").equals("t")) 
            st = true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return st;

}

XHR.js:

function XHR() {
        var xmlObject = null;
        const xhr = (method,url,params,headers) => {
            return new Promise((res, rej) => {
                try {
                    xmlObject = new XMLHttpRequest();
                    xmlObject.open(method, url, true);
                    xmlObject.onload = () => {
                        if (xmlObject.status >= 200 && xmlObject.status < 300) {
                            res(JSON.parse(xmlObject.responseText));
                        } else {
                            rej({
                                status: xmlObject.status,
                                statusText: xmlObject.statusText
                            });
                        }
                    };

                    for (var header in headers) {
                        xmlObject.setRequestHeader(header, headers[header]);
                    }
                    if (method === 'POST') {
                        xmlObject.send(JSON.stringify(params));
                    }
                    else{
                        xmlObject.send();
                    }


                } catch (err) {
                    console.log('error');
                    rej(err);
                }
            });
        }

session.js:

var wrapper = new XHR();
    function $(id) {
        return document.getElementById(id);
    }
function login() {
        var email = $('email').value;
        var password = $('password').value;
        wrapper.post('./Login',{email:email, pass:password},{'Content-Type':'application/x-www-form-urlencoded'}).then(function(data){
            console.log(data)
            alert(data);
        });
    }   
   $('login').addEventListener('click', login);

的login.html:

<head>     
    <link rel="stylesheet" type="text/css" href="style/login.css">
          <script src="js/XHR.js"></script>
          <script src="js/w3.js"></script>  
          <title>First project</title>
        </head>
        <body>
          <div w3-include-html="./layout/header.html"></div>
          <div class="login-page">
            <h1> Log in</h1>
            <form class="register-form">
              <div class="form">
                <input id="email" type="text" placeholder="email address"/>
                <input id="password" type="password" placeholder="password"/>   
                <button id="login">login</button>
                <p class="message">Already registered?
                  <a href="./login.html">Sign in </a>
                </p>
              </div>
            </form>
          </div> 
          <script src="js/session.js"></script>  
        </body>
    </html> 

正如我所说我正在使用html所以我正在使用xmlhttprequest对象执行请求,我在session.js文件中调用,服务器处理数据(即以寄存器形式在db中插入用户)但不会回复客户。

如果我从servlet中删除了db请求(类的实例),则客户端会成功接收到msg,这意味着服务器将响应发送回来(作为JSON)。

2 个答案:

答案 0 :(得分:0)

我只是通过在html中更改代码行来修复它:

            <input id="email" type="text" placeholder="email address"/>

为:

            <input id="email" type="email" placeholder="email address"/>

我不知道为什么修复错误,如果有人知道会非常感激和冷静,知道为什么会这样做

答案 1 :(得分:-1)

首先,我认为你需要开始调试。因为通过调试,您可以轻松找出不发送响应的原因。

根据您在servlet中编写的代码,json map将仅包含两个条件中的数据

  • 当session.isNew返回true并且函数checkUser返回true
  • 当您的会话不是新的时。

只有在上述两种情况下,您的地图才会包含一些json数据。函数checkUser主要返回false。 调试一次并检查它将解决问题的值