预览1-密码错误
预览二-用户不存在
预览三-登陆成功
项目目录:
项目在 Servlet登录 基础上进行SQL扩展
1.导入mysql.jar包
2.Dao文件
public class Dao { public static Connection getConnection() { try { Class.forName("com.mysql.jdbc.Driver"); String url ="jdbc:mysql://localhost:3306/JavaWeb?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true"; Connection con=(Connection) DriverManager.getConnection(url, "root", "AQCTBQLYxingye1."); return con; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } public static void Insertdata(List<Person> l) throws SQLException { Connection con= getConnection(); Statement stat = (Statement) con.createStatement(); stat.executeUpdate("delete from user"); for(Person p:l) { String str= "insert into user values('"+p.getZh()+"','"+p.getMm()+"')"; System.out.println(str); stat.executeUpdate(str); } stat.close(); con.close(); } public static List<Person> Selectdata(String param) throws SQLException { List<Person> list=new ArrayList<>(); Connection con= getConnection(); Statement stat = (Statement) con.createStatement(); String sql="select *from user"; sql+=" where zh='"+param+"'"; ResultSet result = stat.executeQuery(sql); list.clear(); while (result.next()) { Person p=new Person(result.getString("zh"),result.getString("mm")); list.add(p); } stat.close(); con.close(); return list; } }
3.在LoginServlet中的 init 初始化函数中加入了数据初始化 ,添加了两个用户进入数据库
public class LoginServlet extends HttpServlet { @Override public void init() throws ServletException { // TODO Auto-generated method stub super.init(); List<Person> l=new ArrayList<>(); Person p=new Person("root","admin"); l.add(p); p=new Person("123","123"); l.add(p); try { Dao.Insertdata(l); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub String zh=req.getParameter("zh"); String mm=req.getParameter("mm"); String info=null; try { List<Person> l=Dao.Selectdata(zh); if(l.size()==0) { info="该用户不存在"; } else { if(l.get(0).getMm().equals(mm)) { info="登录成功:账号"+zh+" -密码:"+mm; } else { info="密码错误"; } } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); info=e.getMessage(); } req.getSession(true).setAttribute("info",info); resp.sendRedirect(req.getContextPath()+"/"+"info.jsp"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub doGet(req, resp); } }
项目其他源码参考 Servlet登录
百度云下载链接
链接:https://pan.baidu.com/s/1yyoCAWcwvq_c2kO84Kpo0A
提取码:mhe0