登录及登录后第几个人访问
Posted lxc127136
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了登录及登录后第几个人访问相关的知识,希望对你有一定的参考价值。
1.创建一个动态的web--->Dynamic web project
2.创建结果如下:
3.在WebContent 里面创建jsp
红色部分需要自己写;
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="/WEB02/LoginServlet" method="post"> //action 是要访问的地址 method是属性附加到 URL 上 用户名:<input type="text" name="username"></br> 密码:<input type="text" name="pwd"></br> <input type="submit" value="登录"> </form> </body> </html>
第二步:在web src上创建四个包 web包创建servlet包 dao、service、创建java包 tools放入连接数据库的包;
第三步:
public class LoginServlet extends HttpServlet { private Userservice userservice=new Userservice(); @Override public void init() throws ServletException { int sum=0; ServletContext context = getServletContext(); //存值 context.setAttribute("sum", sum); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("username"); //必须和前面那个jsp文件中一样 String pwd = request.getParameter("pwd"); int i=userservice.login(name, pwd); if(i>0){ //获取ServletContext对象 ServletContext context = getServletContext(); //强转 int sum=(int)context.getAttribute("sum"); sum++; context.setAttribute("sum", sum); response.getWriter().write("你是第几个"+sum+"登录的"); }else{ response.getWriter().write("no"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
第四步: service层处理异常
public class Userservice { private Userdao userdao=new Userdao(); public int login(String uname,String pwd){ int row=0; try { row=userdao.login(uname, pwd); } catch (SQLException e) { e.printStackTrace(); } return row; } }
第五步:
public class Userdao { public int login(String uname,String pwd) throws SQLException{ Connection conn = JDBCUtils.getConn(); String sql="select count(*) from user where uname=? and pwd=?"; PreparedStatement pst = conn.prepareStatement(sql); pst.setString(1, uname); //给占位符赋值 pst.setString(2, pwd); //给占位符赋值
ResultSet rs = pst.executeQuery(); int count=0; while(rs.next()){ count=rs.getInt(1); } JDBCUtils.close(rs, pst, conn); return count; } }
第六步:启动服务器
第七步:运行结果如下:
欢迎各位大神指点和评论;
以上是关于登录及登录后第几个人访问的主要内容,如果未能解决你的问题,请参考以下文章
4 使用Selenium模拟登录csdn,取出cookie信息,再用requests.session访问个人中心(保持登录状态)