最近刚刚完成数据库与后台的交接,下面来写写体会与经验吧。
后台和数据库是什么呢?
通俗的讲,后台指的是服务器,数据库是服务器端用来存放数据的;用户通过前台操作,数据传递到服务器端,服务器上的程序操作数据库,处理数据;处理完毕,反馈结果,或者数据给前台,显示数据或结果。
举个例子:
简单的用户登录页面与后台数据库的交互
当用户登录时,如果用户名和密码都正确的时候会进入成功页面。在validate.jsp里会先获得用户名,然后再数据里查找此用户名是否已经存在,若存在则再与所对应的密码进行对比,若都相同则返回flag为2,成功登录,若用户名存在而密码不正确,则返回flag为1,提示密码错误;若在数据库里找不到对应的用户名,则返回flag为0,提示用户名错误。
login.jsp
<body> <form action="validate.jsp" method="post"> <table> <tr> <td>用户名:</td> <td><input type="text" name="loginName"></td> <td><font color="red"><%=request.getAttribute("loginNameError")==null ? "":request.getAttribute("loginNameError") %></font></td> </tr> <tr> <td> 密码:</td> <td><input type="password" name="loginPass"></td> <td><font color="red"><%=request.getAttribute("loginPassError")==null?"":request.getAttribute("loginPassError") %></font></td> </tr> <tr> <td><input type="submit" value="提交"></td> <td><input type="reset" value="重置"></td> </tr> </table> </form> </body>
validate.jsp
<body> <% String loginName=request.getParameter("loginName"); String loginPass=request.getParameter("loginPass"); User user=new User(); user.setUsername(loginName); user.setPassword(loginPass); LoginDao loginDao=new LoginDaoImpl(); int flag=loginDao.login(user); if(flag==2){ session.setAttribute("loginName", loginName); response.sendRedirect(request.getContextPath()+"/index.jsp"); }else { if(flag==1){ request.setAttribute("loginPassError", "loginPass is error"); }else if(flag==0){ request.setAttribute("loginNameError", "loginName is error"); } request.getRequestDispatcher("/login.jsp").forward(request, response); } %> </body>
//编写一个接口,只定义方法,具体实现让实现它的接口去完成。
LoginDao.java
package com.dao.dao; import com.jdbc.jdbc.User; public interface LoginDao { int login(User user); }
//实现接口的类,实现了具体的操作
LoginDaoImpl.java
package com.impls.impls; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import com.jdbc.common.ConnectionUtils; import com.dao.dao.LoginDao; import com.jdbc.jdbc.User; public class LoginDaoImpl implements LoginDao{ Connection con=null; PreparedStatement pstm=null; ResultSet rs=null; public int login(User user) { //连接数据库 con=ConnectionUtils.getConnection(); int flag=0; try { //发送sql文 String sql="select t_name,t_pass from t_user where t_name=?"; pstm=con.prepareStatement(sql); pstm.setString(1, user.getUsername()); rs=pstm.executeQuery(); //处理结果集 while(rs.next()){ String temp=rs.getString("t_pass"); if(temp.equals(user.getPassword())){ flag=2; //用户名和密码都正确 }else{ flag=1;//密码错误 } } } catch (SQLException e) { e.printStackTrace(); }finally{ //资源释放(逆序释放) ConnectionUtils.close(rs, pstm, con); } return flag; } }
[代码参考:http://hryblog.cn http://www.javashuo.com/article/p-rnhspzmp-bg.html]
最后,在个大家分享一个:经典图书管理系统后台数据库https://blog.csdn.net/shiweisi_hqu/article/details/6047916