登录及登录后第几个人访问
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; } }
第六步:启动服务器
第七步:运行结果如下:
欢迎各位大神指点和评论;
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程