一、视图层
Login.java(登录界面)
LoginCl.java(验证用户)
Wel.java(欢迎界面)
二、模型层
ConnDB.java(数据库连接)
UserBean.java(表示users表)
UserBeanCl.java(业务逻辑控制)
三、注意:
1.部署web.xml
2.添加mysql数据库
create database spdb; use spdb; create table users( userId int auto_increment primary key not null, username varchar(20), passwd varchar(30), email varchar(30), grade int );
四、参考代码如下:
视图层
Login.java(登录界面)
package com.tsinghua; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class Login extends HttpServlet { public Login(){ super(); } public void init() throws ServletException{} public void process(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException{ try{ //中文乱码解决 res.setContentType("text/html;charset=UTF-8"); //业务逻辑 PrintWriter pw=res.getWriter(); //返回登录界面 pw.println("<html>"); pw.println("<body>"); //得到erro信息 String info=(String)req.getParameter("info"); if(info!=null){ pw.println("<h1>你的用户名或是密码错误!</h1><br>"); } pw.println("<h1>登录界面</h1>"); pw.println("<form action=logincl method=post>"); pw.println("用户名:<input type=text name=username><br>"); pw.println("密码:<input type=password name=passwd><br>"); pw.println("<input type=checkbox name=keep value=2>两周内不用重新登录<br>"); pw.println("<input type=submit value=loging><br>"); pw.println("</form>"); pw.println("</body>"); pw.println("</html>"); }catch(Exception ex){ ex.printStackTrace(); } } public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException{ process(req,res); } public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException{ process(req,res); } public void destroy(){ super.destroy(); } }
LoginCl.java(验证用户)
package com.tsinghua; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.sql.*; public class LoginCl extends HttpServlet { public LoginCl() { super(); } public void init() throws ServletException { } // req:用于获得浏览器的信息 // res:用于向浏览器返回信息(我就是服务器) public void process(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html;charset=UTF-8");// 处理中文乱码 try { // 接收用户名和密码 String u = req.getParameter("username"); String p = req.getParameter("passwd"); System.out.println("创建一个对象"); //调用UserBeanCl,1.创建一个对象 UserBeanCl ubc=new UserBeanCl(); //2.使用UserBeanCl的方法 if (ubc.checkUser(u, p)) { // 合法用户 String keep = req.getParameter("keep"); if (keep != null) { // 将用户名和密码保存在客户端(cookie) // 创建 Cookie name = new Cookie("myname", u); Cookie pass = new Cookie("mypasswd", p); // 设置时间 name.setMaxAge(14 * 24 * 3600); name.setMaxAge(14 * 24 * 3600); // 回写到客户端 res.addCookie(name); res.addCookie(pass); } // 将用户信息存入session中 HttpSession hs = req.getSession(true); hs.setMaxInactiveInterval(30); hs.setAttribute("name", u); res.sendRedirect("welcome");// 跳转 } else { //不合法用户 System.out.println("用户或密码错了"); res.sendRedirect("login"); } } catch (Exception ex) { ex.printStackTrace(); } } public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { process(req, res); } public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { process(req, res); } public void destroy() { } }
Wel.java(欢迎界面)
package com.tsinghua; import java.io.*; import java.sql.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class Wel extends HttpServlet { public Wel() { super(); } public void init() throws ServletException { } public void process(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html;charset=UTF-8"); PrintWriter pw = res.getWriter(); try { // 从session中得到用户名 HttpSession hs = req.getSession(true); String myName = (String) hs.getAttribute("name"); String name=""; String passwd=""; if (myName == null) { // 如果session中没有用户信息,再看看有没有cookie信息 // 从客户端得到所有的cookie信息 Cookie[] allCookies = req.getCookies(); int i = 0; // 如果allCookies不为空 if (allCookies != null) { for (i = 0; i < allCookies.length; i++) {// 从中取出cookie // 依次取出 Cookie temp = allCookies[i]; if (temp.getName().equals("myname")) { // 得到cookie的值 name = temp.getValue(); } else if (temp.getName().equals("mypasswd")) { passwd = temp.getValue(); } } if(!name.equals("")&&!passwd.equals("")){ //到LoginCl.java去验证 res.sendRedirect("logincl?username="+name+"&passwd="+passwd); return; } } // 返回登陆界面 res.sendRedirect("login?info=error1"); return; } // 调整格式 pw.println("<body><center>"); // 在servlet中显示图片 pw.println("<img src="images/lola.gif" mce_src="images/lola.gif"><br>"); pw.println("Welcom,hello<br>"); pw.println("你的用户名是:" + myName); // 做个超链接 pw.println("<br><a href="login" mce_href="login">返回重新登录</a>"); // ================分页功能=============== int pageSize = 3;// 一页显示几条记录(规定) int pageNow = 1;// 希望显示第几页(规定) // 动态的接收pageNow String sPageNow = req.getParameter("pageNow"); if (sPageNow != null) { pageNow = Integer.parseInt(sPageNow);// 转换成整数 } //调用userBeanCl UserBeanCl ubc=new UserBeanCl(); ArrayList al=ubc.getResultByPage(pageNow, pageSize); // 表头 pw.println("<table border=1>"); pw.println("<tr><th>id</th><th>name</th><th>passwd</th><th>email</th><th>grade</th></tr>"); for(int i=0;i<al.size();i++){ UserBean ub=(UserBean)al.get(i); pw.println("<tr>"); pw.println("<td>" + ub.getUserId() + "</td>"); pw.println("<td>" + ub.getUsername() + "</td>"); pw.println("<td>" + ub.getPasswd() + "</td>"); pw.println("<td>" + ub.getEmail() + "</td>"); pw.println("<td>" + ub.getGrade() + "</td>"); pw.println("</tr>"); } pw.println("</table>"); // ================分页功能=============== // 上一页 if (pageNow != 1) { pw.println("<a href="welcome?pageNow=" mce_href="welcome?pageNow="" + (pageNow - 1) + ">上一页</a>"); } // 显示超链接 // for (int i = 1; i <= pageCount; i++) { for (int i = pageNow; i <= pageNow + 4; i++) { pw.println("<a href="welcome?pageNow=" mce_href="welcome?pageNow="" + i + ">" + i + "</a>"); } int pageCount=ubc.getPageCount(); if (pageNow != pageCount) { pw.println("<a href="welcome?pageNow=" mce_href="welcome?pageNow="" + (pageNow + 1) + ">下一页</a>"); } pw.println("</center></body>"); // String u = req.getParameter("uname");// 得到从LoginCl传递的用户名 // String p = req.getParameter("pass"); } catch (Exception ex) { ex.printStackTrace(); } } public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { process(req, res); } public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { process(req, res); } public void destroy() { } }
模型层
ConnDB.java(数据库连接)
//从数据库中得到连接 package com.tsinghua; import java.sql.*; public class ConnDB{ private Connection ct=null; public Connection getConn(){ try{ // 连接数据库 Class.forName("com.mysql.jdbc.Driver");// 加载驱动 // 得到连接 ct = DriverManager.getConnection( "jdbc:mysql://localhost:3306/spdb", "root", "root"); }catch(Exception ex){ ex.printStackTrace(); } return ct; } }
UserBean.java(表示users表)
//这是一个UserBean<---------->users表映射 //它的一个对象<----------->users表的一条记录对应 //数据 package com.tsinghua; public class UserBean { private int userId; private String username; private String passwd; private String email; private int grade; public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPasswd() { return passwd; } public void setPasswd(String passwd) { this.passwd = passwd; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getGrade() { return grade; } public void setGrade(int grade) { this.grade = grade; } }
UserBeanCl.java(业务逻辑控制)
//这是一个处理类(处理users表)<------->操作UserBean //业务逻辑在这里 package com.tsinghua; import java.sql.*; import java.util.*; public class UserBeanCl { // 业务逻辑,有一句话:能用私有的就不要用私有 private Connection ct = null; private PreparedStatement ps = null; private ResultSet rs = null; private int pageCount = 0;// 共有几页(计算) //返回pageCount public int getPageCount(){ return this.pageCount; } // 分页显示 public ArrayList getResultByPage(int pageNow, int pageSize) { ArrayList al = new ArrayList(); try { int rowCount = 0;// 共有几条记录(查表) // 首先得到rowCount // 连接数据库 ConnDB cd = new ConnDB(); ct = cd.getConn(); ps = ct.prepareStatement("select count(*) from users"); rs = ps.executeQuery(); if (rs.next()) { rowCount = rs.getInt(1); } // 计算pageCount if (rowCount % pageSize == 0) { pageCount = rowCount / pageSize; } else { pageCount = rowCount / pageSize + 1; } ps = ct.prepareStatement("select * from users limit " + (pageNow - 1) * pageSize + "," + pageSize); // 给问号赋值 // ps.setInt(1,(pageNow-1)*pageSize); // ps.setInt(2,pageSize ); rs = ps.executeQuery(); while (rs.next()) { // 将rs中的每一条记录封装到UserBean ub,实现一号线 UserBean ub = new UserBean(); ub.setUserId(rs.getInt(1)); ub.setUsername(rs.getString(2)); ub.setPasswd(rs.getString(3)); ub.setEmail(rs.getString(4)); ub.setGrade(rs.getInt(5)); // 实现第二根线,将ub放入到ArrayList中 al.add(ub); } } catch (Exception ex) { ex.printStackTrace(); }finally{ this.close(); } return al; } // 验证用户 public boolean checkUser(String u, String p) { boolean b = false; try { // 得到连接 ConnDB cd = new ConnDB(); ct = cd.getConn(); ps = ct.prepareStatement("select passwd from users where username='" + u + "'"); // ps.setString(1,u); rs = ps.executeQuery(); System.out.println("进入验证"); if (rs.next()) { System.out.println("有结果"); String dbPasswd = rs.getString(1); if (dbPasswd.equals(p)) { b = true; } } } catch (Exception ex) { ex.printStackTrace(); } finally { this.close(); } return b; } // 关闭资源 public void close() { try { if (rs != null) { rs.close(); rs = null; } if (ps != null) { ps.close(); ps = null; } if (ct != null) { ct.close(); ct = null; } } catch (Exception ex) { ex.printStackTrace(); } } }