response.sendRedirect不使用angular js和java servlet?

时间:2016-03-26 07:47:35

标签: java angularjs servlets

我有以下网络应用程序:

我的html页面: -

    <!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html ng-app="app">
    <title>BPL Auction 2016</title>
    <head>
    <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
    <meta content="utf-8" http-equiv="encoding">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="" />
    <!-- css -->
    <link href="css/bootstrap.min.css" rel="stylesheet" />
    <link href="css/style1.css" rel="stylesheet" />
    <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]>
          <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
    <script src="js/angularref.js"></script>
    </head>
    <body ng-controller="MyController">
    <div id ="header">
    <h3 id="title">BPL Auction 2016</h3>
    </div>
    <!-- Top content -->
            <div class="top-content">

                <div class="inner-bg">
                    <div class="container">
                        <div class="row">
                            <div class="col-sm-8 col-sm-offset-2 text">
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-sm-6 col-sm-offset-3 form-box">
                                <div class="form-top">
                                    <div class="form-top-left">
                                        <h3>Login to our site</h3>
                                        <p>Enter your username and password to log on:</p>
                                    </div>
                                    <div class="form-top-right">
                                        <i class="fa fa-lock"></i>
                                    </div>
                                </div>
                                <div class="form-bottom">
                                    <form name="loginForm" role="form" method="post" class="login-form">
                                        <div class="form-group">
                                            <label class="sr-only" for="form-username">Username or Company Email Id</label>
                                            <input type="text" ng-model="username" name="form-username" placeholder="Username or Email Id..." class="form-username form-control" id="form-username" required>

                                        </div>
                                        <div class="form-group">
                                            <label class="sr-only" for="form-password">Password</label>
                                            <input type="password" ng-model="password" name="form-password" placeholder="Password..." class="form-password form-control" id="form-password" required>
                                            <span>{{validationMessage}}</span>
                                        </div>
    <div class="social-login-buttons">

                                        <button type="submit" ng-click="getDataFromServer()" class="btn">Sign in!</button>
    </div>
                                    </form>
                                </div>
                            </div>
                        </div>

                    </div>
                </div>

            </div>
    <script src="js/jquery.js"></script>
    <script src="js/jquery.easing.1.3.js"></script>
    <script src="js/bootstrap.min.js"></script>

    </body>
    </html>

我的角度控制器页面

angularref.js

angular.module("app",[]).controller("MyController",function ($scope,$http){
    $scope.getDataFromServer = function() {
        $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8";
        $http({
            method:'post',
            url:'login',
            data : {
                'username' : $scope.username,
                'password' : $scope.password
            }
        }).success(function(data,status,headers,config){

            $scope.validationMessage = data;

        }).error(function(data, status) {
              alert('Error with status code: ' + status); 
              alert(headers);
          });
    };
});

我的Servlet课程: -

package com.bpl.loginservlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

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 org.json.JSONObject;

/**
 * Servlet implementation class LoginBPLServler
 */
public class LoginBPLServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final String SALT = "my-salt-text";

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        StringBuilder sb = new StringBuilder();
        BufferedReader br = request.getReader();
        String str = null;
        while ((str = br.readLine()) != null) {
            sb.append(str);
        }
        JSONObject jObj = new JSONObject(sb.toString());


        String username = jObj.getString("username");
        String unHashedPassword = jObj.getString("password");
        //signup(username, unHashedPassword);
        //response.sendRedirect("/BPL2016/second.html");

        // login should succeed.
        if (login(username, unHashedPassword))
        {
            System.out.println("user login successfull.");


            /*String successMessage ="Login Success. Redirecting ...";
            response.setContentType("text/plain");
            response.getWriter().write(successMessage);*/
            response.sendRedirect("http:/localhost:8080/BPL2016/second.html");
        }

        else
        {



        String error ="Invalid UserName or Password";
        response.setContentType("text/plain");
        response.getWriter().write(error);


        }

    }


    public void signup(String username, String password) {
    String saltedPassword = SALT + password;
    String hashedPassword = generateHash(saltedPassword);
    insertIntoDB(username,hashedPassword);
}

public void insertIntoDB(String username,String hashedPassword)
{
     Connection con;
        PreparedStatement pst;


            try{

                //MAKE SURE YOU KEEP THE mysql_connector.jar file in java/lib folder
                //ALSO SET THE CLASSPATH
                Class.forName("com.mysql.jdbc.Driver");
                con=DriverManager.getConnection("jdbc:mysql://localhost:3306/bpl","root","root");
                            pst=con.prepareStatement("insert into tb_bpl_user_login(username,password) values(?,?)");
                            pst.setString(1, username);
                            pst.setString(2, hashedPassword);
                            pst.executeUpdate();


               }
            catch (Exception e) 
            {
                System.out.println(e);
            }


}
public Boolean login(String username, String password) {
    Boolean isAuthenticated = false;

    // remember to use the same SALT value use used while storing password
    // for the first time.
    String saltedPassword = SALT + password;
    String hashedPassword = generateHash(saltedPassword);
    System.out.println(hashedPassword);
    String storedPasswordHash = getFromDB(username);
    if(hashedPassword.equals(storedPasswordHash)){
        isAuthenticated = true;
    }else{
        isAuthenticated = false;
    }
    return isAuthenticated;
}

public String getFromDB(String username)
{
    Connection con;
    PreparedStatement pst;
    String storedPassword = "";
    ResultSet rs;
    try
    {
     Class.forName("com.mysql.jdbc.Driver");
     con=DriverManager.getConnection("jdbc:mysql://localhost:3306/bpl","root","root");
                 pst=con.prepareStatement("select password from tb_bpl_user_login where username =?");
                 pst.setString(1, username);
                rs = pst.executeQuery();
                while(rs.next())
                {
                    storedPassword = rs.getString("password");
                    break;
                }


    }
    catch(Exception e)
    {
        System.out.println(e.getMessage());
    }
    return storedPassword;
}
public static String generateHash(String input) {
    StringBuilder hash = new StringBuilder();

    try {
        MessageDigest sha = MessageDigest.getInstance("SHA-1");
        byte[] hashedBytes = sha.digest(input.getBytes());
        char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f' };
        for (int idx = 0; idx < hashedBytes.length; ++idx) {
            byte b = hashedBytes[idx];
            hash.append(digits[(b & 0xf0) >> 4]);
            hash.append(digits[b & 0x0f]);
        }
    } catch (NoSuchAlgorithmException e) {
        // handle error here.
    }

    return hash.toString();
}


}

输入正确的记录凭据后,我无法重定向到second.html页面。我收到的答复是: -

我应该做出哪些改变?

0 个答案:

没有答案