用户登录案例

  • 文件目录
    这里写图片描述
  • 导包
    这里写图片描述
  • 记得配置c3p0-config.xml
    这里写图片描述
  • html表单的action路径需要填写正确
  • web.xml的Servlet配置要配置正确
C3P0DBUtils
package bull.userLogin;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class C3P0JDBCUtils {
    private static final ComboPooledDataSource dataSource = new ComboPooledDataSource("bull");

    public static Connection getConnection() {
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    public static DataSource getDataSource() {
        return dataSource;
    }

    public static void closeResource(ResultSet rs,PreparedStatement psmt,Connection conn) {
        if(rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            rs = null;
        }
        if(psmt != null) {
            try {
                psmt.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            psmt = null;
        }
        if(conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            conn = null;
        }
    }
}
User
package bull.userLogin;
/**
 * 用户类
 * @author 45度炸
 *
 */
public class User {
    private Integer id;
    private String username;
    private String password;
    private String nickname;

    public User() {

    }

    public User(Integer id, String username, String password, String nickname) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.nickname = nickname;
    }

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getNickname() {
        return nickname;
    }
    public void setNickname(String nickname) {
        this.nickname = nickname;
    }


}
UserDao
package bull.userLogin;

import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

/**
 * User的Dao类
 * @author 45度炸
 *
 */
public class UserDao {
    //连接数据库
    public User login(User user) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(C3P0JDBCUtils.getDataSource());
        String sql = "select * from user where username = ? and password = ?";
        User existUser = queryRunner.query(sql, new BeanHandler<User>(User.class), user.getUsername(),user.getPassword());
        return existUser;
    }

}
UserService
package bull.userLogin;

import java.sql.SQLException;

/**
 * Service类
 * @author 45度炸
 *
 */
public class UserService {

    public User login(User user) throws SQLException {
        UserDao userDao = new UserDao();
        return userDao.login(user);
    }

}
UserServlet
package bull.userLogin;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            //接收数据
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            //封装数据
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);

            //业务层处理数据
            UserService userService = new UserService();
            User existUser = userService.login(user);
            //验证数据
            if(existUser == null) {
                response.getWriter().println("fail");
            } else {
                response.getWriter().println("success");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 一次请求过来的时候,首先调用的是service方法
     * 然后根据你的form表单是post则调用doPost()方法,get则调用doGet()方法,如果不写,默认为doGet方法
     * 所以,一般情况下,doGet()和doPost()是有一个要被执行的
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //form表单时post,所以这里要调用doget,因为方法都写在doget那边
        doGet(request, response);
    }

}

登陆后实现跳转到首页

UserRefreshServlet:
package bull.userRefresh;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bull.userLogin.User;
import bull.userLogin.UserService;

public class UserRefreshServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            //解决向页面输出的乱码问题
            response.setContentType("text/html;charset=UTF-8");
            //接收数据
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            //封装数据
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);

            //业务层处理数据
            UserService userService = new UserService();
            User existUser = userService.login(user);
            //验证数据
            if(existUser == null) {
                response.getWriter().println("<h2>对不住了这位壮士,此次登录失败...</h2>");
            } else {
//              response.getWriter().println("<font size='5' style='font-weight:bold;'>登录成功!欢迎这位壮士:<span style='color:blue'>"+existUser.getNickname()+"</span></font>");
//              response.getWriter().println("<h3>页面将在5秒后跳转...</h3>");
                //Refresh定时跳转
//              response.setHeader("Refresh", "5;url=/Web01/userRefresh/index.html");
                //设置状态码
                response.setStatus(302);
                //Location直接跳转
                response.setHeader("Location", "/Web01/userRefresh/success.html");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 一次请求过来的时候,首先调用的是service方法
     * 然后根据你的form表单是post则调用doPost()方法,get则调用doGet()方法,如果不写,默认为doGet方法
     * 所以,一般情况下,doGet()和doPost()是有一个要被执行的
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //form表单时post,所以这里要调用doget,因为方法都写在doget那边
        doGet(request, response);
    }

}
<!DOCTYPE html>
<html>
  <head>
    <title>success.html</title>

    <meta name="keywords" content="keyword1,keyword2,keyword3">
    <meta name="description" content="this is my page">
    <meta name="content-type" content="text/html; charset=UTF-8">
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->

     <!-- 设置跳转到首页 -->
    <meta http-equiv="Refresh" content="5;url=/Web01/userRefresh/index.html"/>
    <!-- 设置计时器 -->
    <script type="text/javascript">
        var time = 5;
        window.onload = function() {
            setInterval('changeTime()',1000);
        }

        function changeTime() {
            time--;
            document.getElementById("number").innerHTML = time;
        }
    </script>
  </head>   

  <body>
    <h1>登录成功!欢迎您!</h1>
    <h3>页面将在<span id="number" style="color:red">5</span>秒内跳转...</h3>
  </body>
</html>

记录网站登录人次

UserCountServlet:
package bull.userCount;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bull.userLogin.User;
import bull.userLogin.UserService;

public class UserCountServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    /**
     * Servlet创建时就初始化一个count值
     */
    public void init() throws ServletException {
        //初始化一个count值
        int count = 0;
        //将count值存入ServletCount
        this.getServletContext().setAttribute("count", count);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            //解决向页面输出的乱码问题
            response.setContentType("text/html;charset=UTF-8");
            //接收数据
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            //封装数据
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);

            //业务层处理数据
            UserService userService = new UserService();
            User existUser = userService.login(user);
            //验证数据
            if(existUser == null) {
                response.getWriter().println("<h2>对不住了这位壮士,此次登录失败...</h2>");
            } else {
                response.getWriter().println("<font size='5' style='font-weight:bold;'>登录成功!欢迎这位壮士:<span style='color:blue'>"+existUser.getNickname()+"</span></font>");
                response.getWriter().println("<h3>页面将在5秒后跳转...</h3>");
                //Refresh定时跳转
                response.setHeader("Refresh", "5;url=/Web01/CountServlet");
                //设置状态码
                //response.setStatus(302);
                //Location直接跳转
                //response.setHeader("Location", "/Web01/userRefresh/success.html");

                //登录成功获取count值并加1,增加一次登录人次。
                int count = (int) this.getServletContext().getAttribute("count");//object类型要强转
                count++;
                this.getServletContext().setAttribute("count", count);

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 一次请求过来的时候,首先调用的是service方法
     * 然后根据你的form表单是post则调用doPost()方法,get则调用doGet()方法,如果不写,默认为doGet方法
     * 所以,一般情况下,doGet()和doPost()是有一个要被执行的
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //form表单时post,所以这里要调用doget,因为方法都写在doget那边
        doGet(request, response);
    }

}
CountServlet
package bull.userCount;

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

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CountServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //解决向页面输出的乱码问题
        response.setContentType("text/html;charset=UTF-8");
        //获取count值,原本是object类型要强转。
        int count = (int) this.getServletContext().getAttribute("count");
        response.getWriter().print("<font size='5' style='font-weight:bold;'>Welcome!此次是本网站的第<span style='color:red'>"+count+"</span>次用户登录!</font>");
        //response.getWriter().println("<font size='5' style='font-weight:bold;'>登录成功!欢迎这位壮士:<span style='color:blue'>"+existUser.getNickname()+"</span></font>");

    }


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

    }

}

猜你喜欢

转载自blog.csdn.net/sinat_40662281/article/details/80358425
今日推荐