Servlet方法不会重定向页面

时间:2017-11-24 19:06:13

标签: java servlets http-redirect

我正在创建一个应用程序并且我从用户登录开始,我正在尝试当他们登录页面时重定向到另一个页面,我试着用response.sendRedirect做这个但是这不起作用,它只是在控制台日志中显示html的代码。我想知道为什么会发生这种情况

登录课程发布方法:

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", "Reader", "postgres", "kush");
        if(session.isNew()) {
            if(db.checkUser(reqBody.getString("email"), reqBody.getString("pass")) == true) {
                json.put("status", "new session, welcome back");
                storeValue(reqBody.getString("email"), reqBody.getString("pass"), reqBody.getBoolean("admin"), session);
                response.sendRedirect(request.getContextPath() + "/loggedin.html");
            } else {
                json.put("status", "username or password incorrect");
                session.invalidate();
            }
        } else {
            json.put("status", "session updated");
            storeValue(reqBody.getString("email"), reqBody.getString("pass"), reqBody.getBoolean("admin"), session);
        }
        out.println(json.toString());
    }

我尝试过使用

response.sendRedirect("loggedin.html");

response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", "loggedin.html");

ServletContext sc = getServletContext();
sc.getRequestDispatcher("/loggedin.html").forward(request, response);

我的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app>

  <servlet>
    <servlet-name>Login</servlet-name>
    <servlet-class>Login</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>Login</servlet-name>
    <url-pattern>/Login</url-pattern>
  </servlet-mapping>

<servlet>
    <servlet-name>page</servlet-name>
    <jsp-file>/loggedin.html</jsp-file>
</servlet>
<servlet-mapping>
    <servlet-name>page</servlet-name>
    <url-pattern>/Reader/loggedin.html</url-pattern>
</servlet-mapping>
</web-app>

我用xml http请求调用get和post方法

loggedin.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Login successful</title>
</head>
<body>
<h1>Welcome</h1>
</body>
</html>

的index.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Reader | Project</title>
<script src = 'js/XHR.js'><</script>
</head>

<p><input id="email" type="text" name="em"></p>
<p><input id="password" type="password" name="pw"></p>
<p>
<p> Admin user? 
 <select id="admin">
    <option value="true">Si</option>
    <option value="false">No</option>
</select>
</p>

<button onclick='sendValue()'>Send</button>
<button onclick='getValue()'>Get</button>
<button onclick='deleteValue()'>Delete</button>
<body>
<script>
var wrapper = new XHR();
function element(id) {
    return document.getElementById(id);
}

function sendValue() {
    var email = element('email').value;
    var password = element('password').value;
    var is_admin = element('admin').value;
    wrapper.post('./Login',{email:email, pass:password, admin:is_admin},{'Content-Type':'application/x-www-form-urlencoded'})

}

function getValue() {
    wrapper.get('./Login',{},{'Content-Type':'application/x-www-form-urlencoded'})
}

function deleteValue() {
    wrapper.get('./Logout',{},{'Content-Type':'application/x-www-form-urlencoded'})
}

</script>
</body>
</html>

XHR.js

function XHR() {

    var jsonToParams = json => {
        var res = "";
        for (var attr in json) {
            if (res === "") {
                res = attr + "=" + json[attr];
            } else {
                res += "&" + attr + "=" + json[attr];
            }
        }
        return res;
    };

    this.send = function(method, url, params, headers) { 
        return new Promise(function(fullfill, reject) {
            var wrapper = new XMLHttpRequest();
            wrapper.open(method, url);
            wrapper.onload = function()  {
                if (this.status == 200) {
                    fullfill(wrapper.responseText);
                } else {
                    reject({ status: this.status, statusText: wrapper.statusText });
                }
            };

            for (var header in headers) {
                wrapper.setRequestHeader(header, headers[header]);
            }

            if (method === 'POST') {
                wrapper.send(JSON.stringify(params));
            } else {
                wrapper.send();
            }
        });
    }

    this.get = function(url, params, headers) {
        params=typeof params==="string" ? params : jsonToParams(params);
        url += "?" + params;
        this.send('GET', url, params, headers)
            .then(function(data) {
                console.log(data)
            })
            .catch(function(error) {
                console.log(error);
            })
    }

    this.post = function(url, params, headers) {
        this.send('POST', url, params, headers)
            .then(function(data) {
                console.log(data);
            })
            .catch(function(error) {
                console.log(error);
            })
    }
}

1 个答案:

答案 0 :(得分:1)

这可能适合你:)

class Entity1 {
    long id;
    Set<Entity2> entity2;
}

class Entity2 {
    long id;
    boolean active;
}