使用servlet验证用户

时间:2016-02-02 22:27:41

标签: java html sql database servlets

我实现了简单的servlet,用于检查用户是否存在于DB中,如果是,他可以继续访问主站点。

servlet:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //obtain CustomerDB data source from Tomcat's context
            Context context = new InitialContext();
            BasicDataSource ds = (BasicDataSource)context.lookup(testAppConstants.DB_DATASOURCE);
            Connection conn = ds.getConnection();

            //Checks if the username and password exists in the DB
            PreparedStatement ps = conn.prepareStatement(testAppConstants.SELECT_USERS_BY_NAME_STMT);
            ps.setString(1,request.getParameter("username"));
            ResultSet rs  = ps.executeQuery();

            Boolean isMatch = false;

            if(rs.next())
            {

                String a = request.getParameter("password");
                String b = rs.getString("Password");
                if(a.equals(b))
                {
                    response.sendRedirect("success.html");
                    isMatch = true;
                }
            }

            if(!isMatch)
            {
                response.sendRedirect("index.html");
            }

            //commit update
            conn.commit();
            //close statements
            ps.close();
            //close connection
            conn.close();

        } catch (SQLException | NamingException e) {
            getServletContext().log("Error while closing connection", e);
            response.sendError(500);//internal server error
        }

        return;
    }

我正在使用response.sendRedirect()函数,但在成功页面中,我如何验证用户并确定他是否拥有权限。 我不允许使用JSP。

感谢。

1 个答案:

答案 0 :(得分:-1)

如果只想保持简单。

ps=conn.prepareStatement("Select * from Table where uname='?' AND password='?');
ps.setString(1,"uname");
ps.setString(2,"password");
int i=0;
ResultSet rs=ps.executeQuery();
while(rs.next){
i++;
}
if(i>0){
//record exist i.e. valid
}
else{
//no record i.e. invalid
}

请处理例外