2020年12月11日
试着写了写,没有遇到问题,明天继续学习java
package Dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.List; import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException; import DBUtil.DBUtil; import DengBean.BookBean; import DengBean.DengBean; public class Dao { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); public boolean insert(DengBean bean) {//插入数据的方法 boolean f=false; String sql="insert into deng(id,user,password) values('"+bean.getId()+"','"+bean.getUser()+"','"+bean.getPassword()+"')"; Connection conn=DBUtil.getConnection();//数据库连接,加载驱动 Statement state=null; try { state=conn.createStatement();//实例化Statement对象,方便对sql语句进行操作 System.out.println(conn); state.executeUpdate(sql); f=true; //执行数据库更新操作用于执行INSERT、UPDATE或DELETE语句以及SQLDDL(数据定义语言)语句, //例如CREATETABLE和DROPTABLE,(创建表和删除表) }catch(Exception e)//当try语句中s出现异常时,会执行catch中的语句 { e.printStackTrace();//捕获异常的语句 } finally //finally作为异常处理的一部分,它只能用在try/catch语句中,并且附带一个语句块,表示这段语句最终一定会被执行(不管有没有抛出异常),经常被用在需要释放资源的情况下。 { DBUtil.close(conn); } return f; } public boolean delete(int id) {//删除方法 String sql="delete from deng where id='"+id+"'"; boolean f=false; Connection conn =DBUtil.getConnection(); Statement st=null; try { st=conn.createStatement(); st.executeUpdate(sql); f=true; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ DBUtil.close(st, conn); } return f; } public boolean login(String user,int password) { boolean f=false; String sql="select id from deng where username= '"+user+"' and password='"+password+"'"; Connection conn=DBUtil.getConnection(); Statement st=null; List<DengBean> list=new ArrayList<>(); ResultSet rs=null; DengBean bean=null; try { st=conn.createStatement(); st.executeQuery(sql); rs=st.executeQuery(sql); while(rs.next()) { int id=rs.getInt("id"); user = rs.getString("user"); password=rs.getInt("password"); bean=new DengBean(id,user,password); System.out.print(id+" "); System.out.print(user+" "); System.out.println(password+" "); list.add(bean); f=true; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { DBUtil.close(rs, st, conn); } return f; } public boolean update(DengBean bean) {//更新方法 String sql="update deng set id='"+bean.getId()+"',user='"+bean.getUser()+"',password='"+bean.getPassword()+"'"; Connection conn=DBUtil.getConnection(); boolean f=false; Statement st=null; try { st=conn.createStatement(); st.executeUpdate(sql); f=true; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return f; } public List<DengBean> list(){//查询所有方法 String sql="select * from deng order by id ASC"; Connection conn=DBUtil.getConnection(); Statement st=null; List<DengBean> list=new ArrayList<>(); ResultSet rs=null; DengBean bean=null; try { st=conn.createStatement(); st.executeQuery(sql); rs=st.executeQuery(sql); while(rs.next()) { int id=rs.getInt("id"); String user = rs.getString("user"); int password=rs.getInt("password"); bean=new DengBean(id,user,password); System.out.print(id+" "); System.out.print(user+" "); System.out.println(password+" "); list.add(bean); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { DBUtil.close(rs, st, conn); } return list; } public List<DengBean> searchById(String a) throws SQLException{//条件查询 int aa = Integer.parseInt(a); String sql="select * from deng where(id like '%"+a+"%')"; Connection conn=DBUtil.getConnection(); Statement st=null; PreparedStatement pt = conn.prepareStatement(sql); List<DengBean> list=new ArrayList<>(); ResultSet rs=null; DengBean bean=null; try { pt=conn.prepareStatement(sql); rs=pt.executeQuery(); while(rs.next()) { int id=rs.getInt("id"); String user = rs.getString("user"); int password=rs.getInt("password"); bean=new DengBean(id,user,password); System.out.print(id+" "); System.out.print(user+" "); System.out.println(password+" "); list.add(bean); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { DBUtil.close(rs, st, conn); } return list; } public List<DengBean> searchByUser(String str) throws SQLException{//条件查询模糊查询 String sql="select * from deng where(user like '%"+str+"%')"; Connection conn=DBUtil.getConnection(); Statement st=null; PreparedStatement pt = conn.prepareStatement(sql); List<DengBean> list=new ArrayList<>(); ResultSet rs=null; DengBean bean=null; try { pt=conn.prepareStatement(sql); rs=pt.executeQuery(); while(rs.next()) { int id=rs.getInt("id"); String user = rs.getString("user"); int password=rs.getInt("password"); bean=new DengBean(id,user,password); System.out.print(id+" "); System.out.print(user+" "); System.out.println(password+" "); list.add(bean); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { DBUtil.close(rs, st, conn); } return list; } public int searchid(String username,int password) { Connection conn = DBUtil.getConnection(); Statement state = null; ResultSet rs = null; int id=0; try { String sql="select id from deng where username= '"+username+"' and password='"+password+"'"; state = conn.createStatement(); rs = state.executeQuery(sql); while(rs.next()){ id = rs.getInt("id"); } } catch(SQLException e) { e.printStackTrace(); } finally { DBUtil.close(state, conn); } return id; } public boolean insertbook(BookBean bean) {//插入数据的方法 boolean f=false; String sql="insert into book(id,bookname,date) values('"+bean.getId()+"','"+bean.getBookname()+"','"+bean.getTime()+"')"; Connection conn=DBUtil.getConnection();//数据库连接,加载驱动 Statement state=null; try { state=conn.createStatement();//实例化Statement对象,方便对sql语句进行操作 System.out.println(conn); state.executeUpdate(sql); f=true; //执行数据库更新操作用于执行INSERT、UPDATE或DELETE语句以及SQLDDL(数据定义语言)语句, //例如CREATETABLE和DROPTABLE,(创建表和删除表) }catch(Exception e)//当try语句中s出现异常时,会执行catch中的语句 { e.printStackTrace();//捕获异常的语句 } finally //finally作为异常处理的一部分,它只能用在try/catch语句中,并且附带一个语句块,表示这段语句最终一定会被执行(不管有没有抛出异常),经常被用在需要释放资源的情况下。 { DBUtil.close(conn); } return f; } public boolean deletebook(int id) {//删除方法 String sql="delete from book where id='"+id+"'"; boolean f=false; Connection conn =DBUtil.getConnection(); Statement st=null; try { st=conn.createStatement(); st.executeUpdate(sql); f=true; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ DBUtil.close(st, conn); } return f; } public boolean updatebook(BookBean bean) {//更新方法 String sql="update book set id='"+bean.getId()+"',bookname='"+bean.getBookname()+"',date='"+bean.getTime()+"'"; Connection conn=DBUtil.getConnection(); boolean f=false; Statement st=null; try { st=conn.createStatement(); st.executeUpdate(sql); f=true; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return f; } public List<BookBean> listbook()throws SQLException{//查询所有方法 String sql="select * from book order by id ASC"; Connection conn=DBUtil.getConnection(); Statement st=null; List<BookBean> list=new ArrayList<>(); ResultSet rs=null; DengBean bean=null; try { st=conn.createStatement(); st.executeQuery(sql); rs=st.executeQuery(sql); while(rs.next()) { int id=rs.getInt("id"); String bookname = rs.getString("bookname"); String time = rs.getString("time"); java.sql.Date sqlDate = null;// sql包中的Date try { java.util.Date utildate = simpleDateFormat.parse(str); sqlDate = new java.sql.Date(utildate.getTime()); } catch (ParseException e) { e.printStackTrace(); } bean=new DengBean(id,bookname,); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { DBUtil.close(rs, st, conn); } return list; } public static void main(String[] args) { Dao dao=new Dao(); dao.list(); System.out.print("chenggg"); } }
package DBUtil; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DBUtil { private static String url = "jdbc:mysql://localhost:3306/denglu?useSSL=true&serverTimezone=UTC"; private static String user = "root"; private static String password = "789987"; private static String jdbcName="com.mysql.jdbc.Driver"; private Connection con=null; public static Connection getConnection() { Connection con=null; try { Class.forName(jdbcName); con=DriverManager.getConnection(url, user, password); //System.out.println("数据库连接成功"); } catch (Exception e) { // TODO Auto-generated catch block //System.out.println("数据库连接失败"); e.printStackTrace(); } try { con = DriverManager.getConnection(url,user,password); System.out.println("连接成功"); } catch (SQLException e) { // TODO: handle exception e.printStackTrace(); } return con; } public static void main(String[] args)throws SQLException { Connection conn = getConnection(); PreparedStatement pstmt = null; ResultSet rs = null; String sql ="select * from deng"; pstmt = conn.prepareStatement(sql); rs = pstmt.executeQuery(); System.out.println(getConnection()); while(rs.next()){ System.out.println("成功"); } } // return con; public static void close(Connection con) { if(con!=null) try { con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void close(Statement state, Connection conn) { if(state!=null) { try { state.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn!=null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void close(ResultSet rs, Statement state, Connection conn) { if(rs!=null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if(state!=null) { try { state.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn!=null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
package DengBean; import java.sql.Date; public class BookBean { private int id; private String bookname; private Date time; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getBookname() { return bookname; } public void setBookname(String bookname) { this.bookname = bookname; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } public BookBean(int id, String bookname, Date time) { super(); this.id = id; this.bookname = bookname; this.time = time; } @Override public String toString() { return "BookBean [id=" + id + ", bookname=" + bookname + ", time=" + time + "]"; } }
package DengBean; public class DengBean { private int id; private String user; private int password; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public int getPassword() { return password; } public void setPassword(int password) { this.password = password; } public DengBean(int id, String user, int password) { super(); this.id = id; this.user = user; this.password = password; } @Override public String toString() { return "DengBean [id=" + id + ", user=" + user + ", password=" + password + "]"; } }
package dengServlet; import java.io.IOException; import java.sql.SQLException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import Dao.Dao; import DengBean.DengBean; /** * Servlet implementation class dengServlet */ @WebServlet("/dengServlet") public class dengServlet extends HttpServlet { Dao dao = new Dao(); private static final long serialVersionUID = 1L; /** * Default constructor. */ public dengServlet() { // TODO Auto-generated constructor stub } private void insert(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // TODO Auto-generated method stub request.setCharacterEncoding("utf-8"); int id = Integer.parseInt(request.getParameter("id")); String user = request.getParameter("user"); int password = Integer.parseInt(request.getParameter("password")); DengBean bean = new DengBean(id, user, password); if (dao.insert(bean)) { request.setAttribute("message", "添加成功"); request.getRequestDispatcher("index.jsp").forward(request, response); } } private void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.setCharacterEncoding("utf-8"); int id = Integer.parseInt(request.getParameter("id")); String user = request.getParameter("user"); int password = Integer.parseInt(request.getParameter("password")); /* int id = Integer.parseInt(request.getParameter("id")); String user = request.getParameter("user"); int password = Integer.parseInt(request.getParameter("password")); DengBean bean = new DengBean(id, user, password); */ DengBean bean = new DengBean(id, user, password); dao.update(bean); request.setAttribute("message", "修改成功"); request.getRequestDispatcher("dengServlet?method=list").forward(request, response); } private void delete(HttpServletRequest request, HttpServletResponse response) throws Exception, IOException { // TODO Auto-generated method stub request.setCharacterEncoding("UTF-8"); int id = Integer.parseInt(request.getParameter("id")); dao.delete(id); // 进行数据库的删除操作 request.setAttribute("message", "删除成功"); request.getRequestDispatcher("dengServlet?method=list").forward(request, response); } private void login(HttpServletRequest request, HttpServletResponse response) throws Exception { // TODO Auto-generated method stub request.setCharacterEncoding("utf-8"); List<DengBean> list = dao.list(); request.setAttribute("list", list); request.getRequestDispatcher("list.jsp").forward(request, response); } private void search(HttpServletRequest request, HttpServletResponse response) throws Exception { // TODO Auto-generated method stub request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); String cxfs = request.getParameter("cxfs"); System.out.print(cxfs); String str = request.getParameter("value"); Dao dao = new Dao(); List<DengBean> list = null; try { if ("1".equals(cxfs)) { list = dao.searchById(str); } if ("2".equals(cxfs)) { list = dao.searchByUser(str); } } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } request.setAttribute("search", "查询成功"); request.setAttribute("list", list); request.getRequestDispatcher("list.jsp").forward(request, response); } /* @SuppressWarnings("unused") private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub /* String username = request.getParameter("username"); int password = Integer.parseInt(request.getParameter("password")); //int id=dao.searchid(username,password); /* if(dao.login(username,password)) { //dengluchenggong req.getSession().setAttribute("message", "登陆成功"); req.getRequestDispatcher("index.jsp").forward(req, resp); }else { //denglushibai req.getSession().setAttribute("message", "登陆失败"); req.getRequestDispatcher("index.jsp").forward(req, resp); } System.out.println(id); request.setCharacterEncoding("utf-8"); List<DengBean> list = dao.list(); request.setAttribute("list", list); request.getRequestDispatcher("list.jsp").forward(request, response); } */ /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String method = request.getParameter("method"); if ("insert".equals(method)) { insert(request, response); } else if ("delete".equals(method)) { try { delete(request, response); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if ("update".equals(method)) { update(request, response); } else if ("login".equals(method)) { try { login(request, response); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if ("search".equals(method)) { try { search(request, response); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <title>用户登录</title> </head> <body> session.setAttribute("user",model); <table align="center" border="0px" cellpadding="10px" cellspacing="10px"> <form action="dengServlet?method=login" method="post" > <!-- <tr> <td>用户名:</td> <td><input type="text" name="username" id="username"></td> </tr> <tr> <td>密码:</td> <td><input type="password" name="password" id="password"></td> </tr> <tr align="center"> <th colspan="2"> --> <input type="submit" value="登录" > </th> </tr> </form> </table> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <%@include file="sessionCheck.jsp"%> <% Object message =request.getAttribute("message"); if(message!=null&&!"".equals(message)){ %> <script type="text/javascript"> alert("<%=request.getAttribute("message")%>"); </script> <%}%> <div align="center" font-size="30px"> <h1>用户信息查询系统</h1> <div> <a href="insert.jsp">信息登记</a> </div> <div> <a href="dengServlet?method=list">信息修改</a> </div> <div> <a href="dengServlet?method=list">信息删除</a> </div> <div> <a href="dengServlet?method=list">浏览信息</a> </div> <div> <a href="dengServlet?method=list">查询信息</a> </div> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>添加</title> </head> <body> <% Object message = request.getAttribute("message"); if (message != null && !"".equals(message)) { %> <script type="text/javascript"> alert("<%=request.getAttribute("message")%>"); //弹出对话框 </script> <% } %> <div align="center"> <h1>添加信息,注册页面</h1> <a href="index.jsp">返回主页</a> <form action="dengServlet?method=insert" method="post"> <table id="addTable" class="table table-bordered "> <tr class="text-center row"> <tr> <td class="col-sm-2"> id </td> <td class="col-sm-4"> <input type="text" class="form-control" name="id" id="id" > </td> <tr class="text-center row"> <td class="col-sm-2"> 账号 </td> <td class="col-sm-4"> <input type="text" class="form-control" name="user" id="user" > </td> <tr class="text-center row"> <td class="col-sm-2"> 密码 </td> <td class="col-sm-4"> <input type="text" class="form-control" name="password" id="password" > </td> <tr class="text-center row"> <td class="col-sm-2"> </table> <input type="submit" value="添加" onclick= "return check()" /> </form> </div> </body> <script type="text/javascript"> function check() //封装一个<body>中做成点击事件的函数 { if(document.getElementById('id').value=='') { alert('id不能为空!'); document.getElementById('area').focus(); return false; } if(document.getElementById('user').value=='') { alert('用户名不能为空!'); document.getElementById('roomnum').focus(); return false; } if(document.getElementById('password').value=='') { alert('密码不能为空!'); document.getElementById('password').focus(); return false; } } </script> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <% Object message = request.getAttribute("search"); Object grade_list = request.getAttribute("grade_list"); if(message!=null && !"".equals(message)){ %> <script type="text/javascript"> alert("<%=request.getAttribute("search")%>"); </script> <%} %> <div align="center"> <h1 >信息列表</h1> <h1> <form action="dengServlet?method=search" method="post"> <select name="cxfs"> <option id="cxfs"value ="1">id</option> <option id="cxfs" value ="2">使用者</option> <option id="cxfs"value="3">密码</option> </select> <input type="text" id="value" name="value" placeholder="请输入条件"> <input type="submit" id="select" name="select" value="查询" /> </form> </h1> <a href="index.jsp">返回主页</a> <table > <tr> <td>id</td> <td>账户</td> <td>密码</td> </tr> <c:forEach items="${list}" var="item"> <tr> <td>${item.id}</td> <td>${item.user}</td> <td>${item.password}</td> <td><a href="update.jsp?id=${item.id}&user=${item.user}&password=${item.password}">修改</a></td> <td><a href="dengServlet?method=delete&id=${item.id}">删除</a></td> </tr> </c:forEach> </table> </div> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <% Object obj = session.getAttribute("user"); if(obj==null){ out.print("你没有登录"); response.sendRedirect("denglu.jsp"); }else{ } %> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <% Object message =request.getAttribute("message"); if(message!=null&&!"".equals(message)){ %> <script type="text/javascript"> alert("<%=request.getAttribute("message")%>"); </script> <%}%> <div align="center"> <h1>修改</h1> <a href="index.jsp">返回主页</a> <form action="dengServlet?method=update" method="post"> <div> id:<input type="text" id="id" name="id" readonly="true" value="${param.id}" /> </div> <div> 用户:<input type="text" id="user" name="user" value="${param.user}" /> </div> <div> 密码:<input type="text" id="password" name="password" value="${param.password}"/> </div> <div> <input type="submit" value="修改" onclick="return check()" /> </div> </body> <script type="text/javascript"> function check() //封装一个<body>中做成点击事件的函数 { if(document.getElementById('id').value=='') { alert('id不能为空!'); document.getElementById('area').focus(); return false; } if(document.getElementById('user').value=='') { alert('用户名不能为空!'); document.getElementById('roomnum').focus(); return false; } if(document.getElementById('password').value=='') { alert('密码不能为空!'); document.getElementById('password').focus(); return false; } } </html>