如何更正调用URL?

时间:2017-03-30 11:24:40

标签: java servlets

我正在使用Eclipse IDE中的Servlet创建一个基于登录的基本项目。我制作了一个jdbc文件,首先从数据库验证用户,然后将页面重定向到欢迎页面,即html文件。 一切都保存在默认文件夹中。但每当我尝试执行我的项目时,我都会收到此错误 - Http Status 404 - /Diary/welcome。此处的被叫URL为localhost:8080/Diary/welcome,但被叫URL应为localhost:8080/Diary/welcome.html。 我该如何解决?

Login.java

import java.sql.*;
public class Login {

    public static boolean validate(String user,String pass){
        boolean status=false;
        try{
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Diary", "root", "root");
            PreparedStatement ps=con.prepareStatement("SELECT * FROM trial WHERE user=? and pass=? and authorized=?");
            ps.setString(1,user);
            ps.setString(2,pass);
            ps.setString(3,"yes");
            ResultSet rs=ps.executeQuery();
            if(rs.next()){
                status=true;
            }

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

        return status;
    }
}

LoginServlet.java

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

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

        res.setContentType("text/html");
        PrintWriter out=res.getWriter();        
        String user=req.getParameter("user");
        String pass=req.getParameter("pass");
        if(Login.validate(user, pass)){
            out.println("you are successfully logged in!");
            req.getSession().setAttribute("login", "true");
            req.getSession().setAttribute("user", user);
            res.sendRedirect("welcome.html");

        }else{
            out.println("<p>Sorry, username or password error</p>");
            req.getRequestDispatcher("login.html").include(req, res);
        }

        out.close();
    }

}

1 个答案:

答案 0 :(得分:1)

您正确地重定向到了&#39; welcome.html&#39;文件。项目中必须有一个拦截器,用于删除&#39; .html&#39;一部分。