Tomcat 7上的@WebServlet获得404错误

时间:2016-10-05 03:52:53

标签: servlets annotations tomcat7 http-status-code-404

使用servlet注释在Windows 7上运行的Tomcat 7在尝试此URL时给出了404错误: http://localhost:8080/LoginExample/ Tomcat正在使用JRE 1.7,而servlet类包含在文件夹... / webapps / LoginExample中。它是使用Java 1.7编译的。我没有Web.xml。它部署没有错误。

这是班级:

package com.journaldev.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet(
        description = "Login Servlet", 
        urlPatterns = { "/LoginServlet" }, 
        initParams = { 
                @WebInitParam(name = "user", value = "Pankaj"), 
                @WebInitParam(name = "password", value = "journaldev")
        })
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;


    public void init() throws ServletException {
        //we can create DB connection resource here and set it to Servlet context
        if(getServletContext().getInitParameter("dbURL").equals("jdbc:mysql://localhost/mysql_db") &&
                getServletContext().getInitParameter("dbUser").equals("mysql_user") &&
                getServletContext().getInitParameter("dbUserPwd").equals("mysql_pwd"))
        getServletContext().setAttribute("DB_Success", "True");
        else throw new ServletException("DB Connection error");
    }


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

        //get request parameters for userID and password
        String user = request.getParameter("user");
        String pwd = request.getParameter("pwd");

        //get servlet config init params
        String userID = getServletConfig().getInitParameter("user");
        String password = getServletConfig().getInitParameter("password");
        //logging example
        log("User="+user+"::password="+pwd);

        if(userID.equals(user) && password.equals(pwd)){
            response.sendRedirect("LoginSuccess.jsp");
        }else{
            RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
            PrintWriter out= response.getWriter();
            out.println("<font color=red>Either user name or password is wrong.</font>");
            rd.include(request, response);

        }

    }

}

1 个答案:

答案 0 :(得分:0)

您的servlet类http://localhost:8080/LoginExample/旨在仅处理'/ LoginServlet'网址,并在http://localhost:8080/LoginExample/LoginServlet中使用'/'作为网址。

您必须使用<form action="LoginServlet" method="post"> .... .... </form>
或者

// save result in a variable and then run a loop and echo 
$result = $stmt->execute(); 

foreach($result as $val){ 
    echo $val->item_name; 
}