Servlet登錄二-帶數據庫
阿新 • • 發佈:2019-03-21
urn set .com del 目錄 http nec 源碼 項目目錄
預覽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 conDao.java=(Connection) DriverManager.getConnection(url, "root", "AQCTBQLYxingye1."); return con; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } public staticvoid 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); } }LoginServlet.java
項目其他源碼參考 Servlet登錄
百度雲下載鏈接
鏈接:https://pan.baidu.com/s/1yyoCAWcwvq_c2kO84Kpo0A
提取碼:mhe0
Servlet登錄二-帶數據庫