使用Post方法链接到网页

时间:2015-02-13 13:39:03

标签: servlets post

我正在学习Java Servlets,并在一个页面和一个页面中实现了一个简单的注册表单。登录表单在另一页,

我正在使用Ajax和JQuery来处理表单验证和提交。

当提交表单时,我的两个页面都使用POST方法分别与RegisterServlet.java和LoginServlet.java进行通信。

我正在使用最新版本的Apache Tomcat,

每当我尝试在我的登录表单页面中提供一个注册表单页面的链接时,它会被注册表单页面的Servlet解释为获取请求,显示给我这个错误:

  

HTTP状态405 - 此URL不支持HTTP方法GET

我甚至尝试在RegisterServlet.java中设置一个空白的doGet方法,但是只要从登录表单页面点击链接,它就会返回一个空白页面,

如何提供使用POST方法处理表单请求的Registeration Form页面的链接!

我的代码: 注册表单页面(Register.html):

`<html>
    <head>
        <script src="jquery-2.1.3.js"></script>
        <script src="validatereg.js">
        </script>
    </head>
    <body>
        <form name="regform" id="regform">
            <b>Hi Register</b><br><br>
            First Name:<input type="text" name="firstname" id="firstname"><br><br>
            Last Name:<input type="text" name="lastname" id="lastname"><br><br>
            Username:<input type="text" name="username" id="username">
            <br><br>
            Password: <input type="password" name="password" id="password"><br><br>
            Re-Enter Password:<input type="password" name="repassword" id="repassword"><br><br>
            State:<select id="stateinfo">
                <option value="none">Select State</option>
                <option value="Andaman and Nicobar Islands">Andaman and Nicobar Islands</option>
                <option value="Andhra Pradesh">Andhra Pradesh</option>
                <option value="Arunachal Pradesh">Arunachal Pradesh</option>
            </select><br><br>
            <input type="submit" value="Log In"  >
        </form>
        <div id="msg"></div>

        <div id="contentbutton"></div>
    </body>
</html>`

注册表单页面JS代码(validatereg.js):

$(document).ready(function() {

            $.post('Login', "username=&password=", giveLoginResponse);

            $('#submitform').submit(function() {

                var username = $('#username').val();
                var password = $('#password').val();
                var pattern = /^(?=.*[0-9])(?=.*[!@#$%^&*()_+/-])[a-zA-Z0-9!@#$%^&*()_+/-]{8,}$/;
                var isCorrect = pattern.test(password);
                $('#iderror').html("");
                $('#paserror').html("");
                if (username === '') {
                    $('#iderror').html("<b>Please Enter a Username!</b>");
                    return false;
                } else if (password === '') {
                    $('#paserror').html("<b>Please Enter a Password</b>.");
                    return false;
                } else if (username.length < 6) {
                    $('#iderror').html("Invalid Username");
                    return false;
                } else if (isCorrect === false) {
                    $('#paserror').html("Invalid Password.");
                    return false;
                } else {
                    var formData = $('#submitform').serialize();

                    $.post('Login', formData, giveLoginResponse);
                    return false;
                }
            });

            $('#contentbutton').on("click", '#LogoutButton', function() {
                $.post('Logout', "", giveLogoutResponse);
                return false;
            });

            function giveLoginResponse(data) {
                $('#msg').html(data);
                if (data === 'Successfully Logged in!') {
                    $('#submitform')[0].reset();
                    $('#submitform').hide();
                    $('#contentbutton').html('<br><input type="button" value="Logout" id=LogoutButton>');

                }
            }

            function giveLogoutResponse(data) {
                if (data === 'Successfully Logged Out!') {

                    $('#LogoutButton').hide();
                    $('#submitform').show();
                    $('#msg').html(data);
                    setTimeout(function() {
                        $('#msg').html('');
                    }, 10000);
                }
            }

            $('#regform').submit(function() {
                var firstname = $('#firstname').val();
                var lastname = $('#lastname').val();
                var username = $('#username').val();
                var password = $('#password').val();
                var repassword = $('#repassword').val();
                var state = $('#stateinfo').val();
                var pattern = /^(?=.*[0-9])(?=.*[!@#$%^&*()_+/-])[a-zA-Z0-9!@#$%^&*()_+/-]{8,}$/;
                var isCorrect = pattern.test(password);
                if (firstname === '' || lastname === '' || username === '' || password === '' || repassword === '' || state === 'none') {
                    $('#msg').html("All Field are Mandatory.Please Enter Details in all fields.");
                    return false;
                } else if (username.length < 6) {
                    $('#msg').html("Length of username should be atleast 6!");
                    return false;
                } else if (!(password === repassword)) {
                    $('#msg').html("These Passwords don't match.Try Again? <br> Rules: Password length should be of minimum 8 chracters and must include 1 special character and 1 number!");
                    return false;
                } else if (isCorrect === false) {
                    $('#msg').html("Incorrect Password Format! <br>Rules: Password length should be of minimum 8 characters and must include 1 special character and 1 number!");
                    return false;
                } else {
                    var regData = $('#regform').serialize();
                    $.post('Register', regData, giveRegResponse);
                    return false;
                }
            });

            function giveRegResponse(data) {
                if (data === 'false') {
                    $('#msg').html("Username already Exist! Please Select a different username!");
                } else if (data === '' {
                        $('#regform').hide();
                        $('#msg').html("Successfully Created Account!");
                    }
                }

            });

RegisterServlet.java

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import java.io.PrintWriter;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author VJ
 */
public class RegisterServlet extends HttpServlet {

    DBHandle regdb = new DBHandle();

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

        PrintWriter write = response.getWriter();
        response.setContentType("text/html");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String fullname = request.getParameter("firstname") + " " + request.getParameter("lastname");
        try {
            if (regdb.RegisterUser(username, password, fullname)) {

                Cookie regCookie = new Cookie("ECI_User", regdb.GenerateUserUID(username));
                regCookie.setMaxAge(60 * 60 * 24);
                regCookie.setPath("/");
                response.addCookie(regCookie);
                request.getRequestDispatcher("Login").forward(request, response);
            } else {
                write.print("false");
            }
        } catch (SQLException ex) {

            System.out.println("Exception in RegisterServlet doPost Method:" + ex);
        }

    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

    }
}

登录表单页面(index.html):

<html>
    <head>
        <script src="jquery-2.1.3.js"></script>
        <script src="validate.js">
        </script>
    </head>
    <body>
        Not Registered Yet?<a href="Register"> Click Here! </a>
        <form name="loginform"method="post" action="" id="submitform">
            <b>Hi Please Login!</b><br><br>
            Username:<input type="text" name="username" id="username"><div id="iderror"></div><br><br>
            Password: <input type="password" name="password" id="password">
            <div id="paserror"></div><br><br>
            <input type="submit" value="Log In"  >
        </form>
        <div id="msg"></div>

        <div id="contentbutton"></div>
    </body>
</html>

登录表单JS代码(validate.js):

$(document).ready(function() {
            $('#regform').submit(function() {
                var firstname = $('#firstname').val();
                var lastname = $('#lastname').val();
                var username = $('#username').val();
                var password = $('#password').val();
                var repassword = $('#repassword').val();
                var state = $('#stateinfo').val();
                var pattern = /^(?=.*[0-9])(?=.*[!@#$%^&*()_+/-])[a-zA-Z0-9!@#$%^&*()_+/-]{8,}$/;
                var isCorrect = pattern.test(password);
                if (firstname === '' || lastname === '' || username === '' || password === '' || repassword === '' || state === 'none') {
                    $('#msg').html("All Field are Mandatory.Please Enter Details in all fields.");
                    return false;
                } else if (username.length < 6) {
                    $('#msg').html("Length of username should be atleast 6!");
                    return false;
                } else if (!(password === repassword)) {
                    $('#msg').html("These Passwords don't match.Try Again? <br> Rules: Password length should be of minimum 8 chracters and must include 1 special character and 1 number!");
                    return false;
                } else if (isCorrect === false) {
                    $('#msg').html("Incorrect Password Format! <br>Rules: Password length should be of minimum 8 characters and must include 1 special character and 1 number!");
                    return false;
                } else {
                    var regData = $('#regform').serialize();
                    $.post('Register', regData, giveRegResponse);
                    return false;
                }
            });

            function giveRegResponse(data) {
                if (data === 'false') {
                    $('#msg').html("Username already Exist! Please Select a different username!");
                } else if (data === '' {
                        $('#regform').hide();
                        $('#msg').html("Successfully Created Account!");
                    }
                }

            });

LoginServlet.java

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.http.Cookie;

/**
 *
 * @author VJ
 */
public class LoginServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter write = response.getWriter();
        DBHandle CheckDB = new DBHandle();

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Cookie[] oldCookie = request.getCookies();
        try {
            if (oldCookie != null) {
                for (Cookie checkData : oldCookie) {
                    if (checkData.getName().equals("ECI_User")) {
                        if (!CheckDB.getUserFromUID(checkData.getValue()).equals("null")) {
                            write.print("Successfully Logged in!");
                        } else {
                            checkData.setMaxAge(0);
                            checkData.setPath("/");
                            response.addCookie(checkData);
                        }
                    }

                }
            } else if (CheckDB.LoginUser(username, password)) {
                Cookie newcookie = new Cookie("ECI_User", CheckDB.GenerateUserUID(username));
                newcookie.setMaxAge(60 * 60 * 24);
                newcookie.setPath("/");
                response.addCookie(newcookie);
                write.print("Successfully Logged in!");

            } else if (!username.equals("") && !password.equals("")) {
                write.print("Sorry! Username/Password is Incorrect");

            }
        } catch (SQLException sqle) {
            System.out.println("Exception in doPost Method of LoginServlet : " + sqle);

        }
    }

}

的web.xml

<web-app>
<servlet>
<servlet-name>LoginPage</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>

<servlet-mapping>
<http-method>POST</http-method>
<servlet-name>LoginPage</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>


<servlet>
<servlet-name>LogoutPage</servlet-name>
<servlet-class>LogoutServlet</servlet-class>
</servlet>

<servlet-mapping>
<http-method>POST</http-method>
<servlet-name>LogoutPage</servlet-name>
<url-pattern>/Logout</url-pattern>
</servlet-mapping>


<servlet>
<servlet-name>RegisterPage</servlet-name>
<servlet-class>RegisterServlet</servlet-class>
</servlet>

<servlet-mapping>
<http-method>POST</http-method>
<servlet-name>RegisterPage</servlet-name>
<url-pattern>/Register</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>Register.html</welcome-file>
</welcome-file-list>

</web-app>

1 个答案:

答案 0 :(得分:0)

好的,所以我意识到自己的错误,真的很傻。在我的登录表单页面的注册表单页面的链接中我没有添加扩展名“.html”,因此tomcat试图找到一个Servlet名称注册而不是Register.html的链接