Servlet—简单的管理系统
网站的框架
网站的框架采用MV模式,即Model(模型)、View(视图)。框架将界面层和模型层进行分离,结构更清晰,更加方便管理代码。
其中上图框架中的修改和删除功能完成而添加查询模块没有编写
实现的系统页面样式如下:
下面贴出网站详细的代码:
1.Login.java
/** *登录界面*/ package com.xidian; import javax.servlet.http.*; import java.io.*; public class Login extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res){ try{ //中文乱码 res.setContentType("text/html;charset=gbk"); PrintWriter pw=res.getWriter(); //返回登录界面 pw.println("<html>"); pw.println("<body bgcolor=#CDD4FF >"); pw.println("<center><img src=images/1.jpg width=120px height=150px><hr>"); //得到error信息 String info=req.getParameter("info"); if(info!=null){ pw.println("<h4>请正确登录!</h4>"); } pw.println("<h3>登录界面<h3>"); pw.println("<form action=logincl method=post>"); pw.println("用户名:<input type=text name=username><br>"); pw.println("密码:<input type=password name=password><br>"); pw.println("<input type=checkbox name=keep value=2>保存Cookie<br>"); pw.println("<input type=submit name=login value=login><br>"); pw.println("</form>"); pw.println("</center><hr><img src=images/3.jpg width=120px height=150px>"); pw.println("<body>"); pw.println("<html>"); } catch(Exception ex){ ex.printStackTrace(); }
} public void doPost(HttpServletRequest req,HttpServletResponse res){ this.doGet(req,res); } }
2.LoginCl.java
1 //处理界面 2 package com.xidian; 3 import javax.servlet.http.*; 4 import java.io.*; 5 import java.sql.*; 6 7 public class Logincl extends HttpServlet { 8 9 //重写init函数,init只会在启动tomcat调用servlet时被执行 10 public void init(){ 11 12 try { 13 //只会被调用一次 14 System.out.println ("init被调用"); 15 16 //添加网页访问次数的功能 17 //创建一个FileReader 18 FileReader f=new FileReader("e://myDocument.txt"); 19 BufferedReader br=new BufferedReader(f); 20 //读出一行数据 21 String numVal=br.readLine(); 22 //一定要关闭文件流 23 br.close(); 24 int times=Integer.parseInt(numVal); 25 //将times值放入到servletcontext 26 this.getServletContext().setAttribute("visitTimes",times+""); 27 28 } 29 catch (Exception ex) { 30 } 31 } 32 33 //重写destroy函数,destroy函数在tomcat关闭的时候被调用,要用shutdown.bat关,不能直接叉掉tomcat窗口 34 public void destroy(){ 35 try { 36 System.out.println ("destroy被调用"); 37 38 //再将新的次数写回去 39 FileWriter fw=new FileWriter("e://myDocument.txt"); 40 BufferedWriter bw=new BufferedWriter(fw); 41 bw.write(this.getServletContext().getAttribute("visitTimes").toString()); 42 bw.close(); 43 } 44 catch (Exception ex) { 45 } 46 } 47 48 public void doGet(HttpServletRequest req,HttpServletResponse res){ 49 Connection ct=null; 50 PreparedStatement sm=null; 51 ResultSet rs=null; 52 try{ 53 //接收用户名和密码 54 String u=req.getParameter("username"); 55 String p=req.getParameter("password"); 56 //调用UserBeanCl 57 UserBeanCl ubc=new UserBeanCl(); 58 //使用UserBean方法 59 if(ubc.checkUser(u,p)){ 60 //用户合法 61 62 //设置Cookie值 63 String keep=req.getParameter("keep"); 64 if(keep!=null){ 65 //将用户名和密码保存在客户端(cookie) 66 //创建Cookie 67 Cookie name=new Cookie ("myname",u); 68 Cookie pass=new Cookie("mypasswd",p); 69 //设置时间 70 name.setMaxAge(14*24*3600); 71 pass.setMaxAge(14*24*3600); 72 //回写到客户端 73 res.addCookie(name); 74 res.addCookie(pass); 75 } 76 77 //设置Session值 78 HttpSession hs=req.getSession(true); 79 //1.修改session的存在时间 80 //hs.setMaxInactiveInterval(0); 81 //2.向session添加属性 82 hs.setAttribute("uname",u+""); 83 84 //每登录一次在Session空间中添加计数器 85 String times=this.getServletContext().getAttribute("visitTimes").toString(); 86 this.getServletContext().setAttribute("visitTimes",(Integer.parseInt(times)+1)+""); 87 88 //跳转到Main页面 89 res.sendRedirect("Main"); 90 91 } else{ 92 //说明用户不存在 93 res.sendRedirect("login");//要到的servlet的那个url 94 } 95 } 96 catch(Exception ex){ 97 98 ex.printStackTrace(); 99 }finally{ 100 try { 101 if(rs!=null){ 102 rs.close(); 103 } 104 if(sm!=null){ 105 sm.close(); 106 } 107 if(ct!=null){ 108 ct.close(); 109 } 110 } 111 catch (Exception ex) { 112 ex.printStackTrace(); 113 } 114 } 115 } 116 117 public void doPost(HttpServletRequest req,HttpServletResponse res){ 118 this.doGet(req,res); 119 } 120 121 }
3.Main.java
/** *登录界面 * @version 1.00 2016/7/14 */ package com.xidian; import javax.servlet.http.*; import java.io.*; public class Main extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res){ try{ //中文乱码处理 res.setContentType("text/html;charset=gbk"); PrintWriter pw=res.getWriter(); //返回登录界面 pw.println("<html>"); pw.println("<body bgcolor=#CDD4FF >"); pw.println("<center><img src=images/1.jpg width=120px height=150px><hr>"); pw.println("<h1>主界面</h1>"); pw.println("<a href=Welcome>管理用户</a><br>"); pw.println("<a href=???>添加用户</a><br>"); pw.println("<a href=???>查找用户</a><br>"); pw.println("<a href=???>安全退出</a><br>"); pw.println("</center><hr><img src=images/3.jpg width=120px height=150px>"); pw.println("<body>"); pw.println("<html>"); } catch(Exception ex){ ex.printStackTrace(); } } public void doPost(HttpServletRequest req,HttpServletResponse res){ this.doGet(req,res); } }
4.Welcome.java
//欢迎界面 package com.xidian; import javax.servlet.http.*; import java.io.*; import java.sql.*; import java.util.*; public class Welcome extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res){ Connection ct=null; PreparedStatement ps=null; ResultSet rs=null; try { //得到session HttpSession hs=req.getSession(true); String myName=(String)hs.getAttribute("uname"); String name=""; String passwd=""; //判断非法登录 if(myName==null){ //如果session中没有用户信息,再看看有没有cookie // 从客户端得到所有cookie信息 Cookie [] allCookies=req.getCookies(); //如果allCookie不为空 if(allCookies!=null){ //从中取出cookie for(int i=0;i<allCookies.length;i++){ //依次取出 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去验证 res.sendRedirect("logincl?username="+name+"&password="+passwd); return; } } } //得到从logincl传递的用户名 String u=req.getParameter("uname"); //得到logincl传递的密码 String p=req.getParameter("upass"); //解决中文乱码问题 res.setCharacterEncoding("gbk"); PrintWriter pw=res.getWriter(); pw.println("<html>"); // pw.println("Welcome "+u+" upass="+p); pw.println("<body bgcolor=#CDD4FF >"); pw.println("欢迎您:"+myName+"<img src=images/1.gif width=50px height=30px><center><img src=images/1.jpg width=120px height=150px><hr>"); pw.println("<h1>管理用户</h1>"); pw.println("<br><a href=login>返回重新登录</a>"); //===========分页的功能======================== int pageSize=5;//一页显示几条记录 int pageNow=1; //希望显示第几页 //动态接收pageNow String sPageNow=req.getParameter("pageNow"); if(sPageNow!=null){ //用户不是第一次进入Welcome页面 pageNow=Integer.parseInt(sPageNow); } //调用UserBeanCl UserBeanCl ubc=new UserBeanCl(); ArrayList al=ubc.getResultByPage(pageNow,pageSize); pw.println("<table border=1>"); pw.println("<tr bgcolor=pink><th>id</th><th>name</th><th>passwd</th><th>email</th><th>grade</th><th>修改用户</th><th>删除用户</th></tr>"); //定义一个颜色数组 String [] mycol={"silver","pink"}; for(int i=0;i<al.size();i++){ UserBean ub=(UserBean)al.get(i); pw.println("<tr bgcolor="+mycol[i%2]+">"); pw.println("<td>"+ub.getUserId()+"</td>"); pw.println("<td>"+ub.getUserName()+"</td>"); pw.println("<td>"+ub.getPasswd()+"</td>"); pw.println("<td>"+ub.getMail()+"</td>"); pw.println("<td>"+ub.getGrade()+"</td>"); pw.println("<td><a href=Update?uId="+ub.getUserId()+"&uName="+ub.getUserName()+"&uPasswd="+ub.getPasswd()+"&uEmail="+ub.getMail()+"&uGrade="+ub.getGrade()+">修改用户</td>"); pw.println("<td><a href=DelUserCl?userid="+ub.getUserId()+" onclick=\"return window.confirm('你确定要删除用户吗?')\">删除用户</td>"); pw.println("</tr>"); } pw.println("</table>"); //显示上页 if(pageNow!=1) pw.println("<a href=Welcome?pageNow="+(pageNow-1)+">"+"上一页"+"</a>"); //显示超链接 for(int i=pageNow;i<=pageNow+4;i++){ pw.println("<a href=Welcome?pageNow="+i+">"+i+"</a>"); } //显示下页 int pageCount=ubc.getPageCount(); if(pageNow!=pageCount) pw.println("<a href=Welcome?pageNow="+(pageNow+1)+">"+"下一页"+"</a>"); pw.println("该网页被访问了"+this.getServletContext().getAttribute("visitTimes").toString()+"次"+"<br>"); //指定跳转到某夜 //这里实际是一个表单 //你需要考虑的问题:输入的页数过大?,输入的不是数字? pw.println("<form action=Welcome>"); pw.println("<input type=text name=pageNow> "); pw.println("<input type=submit name=go> "); pw.println("</form>"); pw.println("您的ip="+req.getRemoteAddr()+"<br>"); pw.println("您的机器名="+req.getRemoteHost()+"<br>"); pw.println("</center><hr><img src=images/3.jpg width=200px height=80px>"); pw.println("</html>"); } catch(Exception ex){ ex.printStackTrace(); } } public void doPost(HttpServletRequest req,HttpServletResponse res){ this.doGet(req,res); } }
5.DelUserCl.java.
/** 处理删除某个用户 */ package com.xidian; import javax.servlet.http.*; import java.io.*; public class DelUserCl extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res){ try{ //中文乱码 res.setContentType("text/html;charset=gbk"); //调用userBeanCl的删除用户的方法,完成删除 UserBeanCl ubc=new UserBeanCl(); //接收从Welcome.java中传递的id String id=req.getParameter("userid"); if(ubc.delUser(id)){ //删除成功 res.sendRedirect("Ok"); }else{ //删除失败 res.sendRedirect("Err"); } } catch(Exception ex){ ex.printStackTrace(); } } public void doPost(HttpServletRequest req,HttpServletResponse res){ this.doGet(req,res); } }
6.Update.java
/** * @(#)Login.java * *修改用户界面 * @author * @version 1.00 2016/7/14 */ package com.xidian; import javax.servlet.http.*; import java.io.*; public class Update extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res){ try{ //中文乱码 res.setContentType("text/html;charset=gbk"); PrintWriter pw=res.getWriter(); //返回登录界面 pw.println("<html>"); pw.println("<body bgcolor=#CDD4FF >"); pw.println("<center><img src=images/1.jpg width=120px height=150px><hr>"); pw.println("<h1>修改用户界面</h1>"); pw.println("<form action=UpdateCl>"); pw.println("<table border=1>"); pw.println("<tr><td>id</td><td><input readonly type=text name=uId value="+req.getParameter("uId")+"></td></tr>"); pw.println("<tr><td>name</td><td><input readonly type=text value="+req.getParameter("uName")+"></td></tr>"); pw.println("<tr><td>passwd</td><td><input type=text name=newPasswd value="+req.getParameter("uPasswd")+"></td></tr>"); pw.println("<tr><td>email</td><td><input type=text name=newEmail value="+req.getParameter("uEmail")+"></td></tr>"); pw.println("<tr><td>grade</td><td><input type=text name=newGrade value="+req.getParameter("uGrade")+"></td></tr>"); pw.println("<tr><td colspan=2><input type=submit value=修改用户></td></tr>"); pw.println("</table></form>"); pw.println("</center><hr><img src=images/3.jpg width=120px height=150px>"); pw.println("<body>"); pw.println("<html>"); } catch(Exception ex){ ex.printStackTrace(); } } public void doPost(HttpServletRequest req,HttpServletResponse res){ this.doGet(req,res); } }
7.UpdateCl.java
/** 处理修改某个用户 */ package com.xidian; import javax.servlet.http.*; import java.io.*; public class UpdateCl extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res){ try{ //中文乱码 res.setContentType("text/html;charset=gbk"); UserBeanCl ubc=new UserBeanCl(); if(ubc.updateUser(req.getParameter("uId"),req.getParameter("newEmail"),req.getParameter("newPasswd"),req.getParameter("newGrade"))){ //删除成功 res.sendRedirect("Ok"); }else{ //删除失败 res.sendRedirect("Err"); } } catch(Exception ex){ ex.printStackTrace(); } } public void doPost(HttpServletRequest req,HttpServletResponse res){ this.doGet(req,res); } }
8. Ok.java
/** 操作成功界面 */ package com.xidian; import javax.servlet.http.*; import java.io.*; public class Ok extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res){ try{ //中文乱码 res.setContentType("text/html;charset=gbk"); PrintWriter pw=res.getWriter(); //返回登录界面 pw.println("<html>"); pw.println("<body bgcolor=#CDD4FF >"); pw.println("<center><img src=images/1.jpg width=120px height=150px><hr>"); pw.println("<h1>恭喜你,操作成功!</h1>"); pw.println("<a href=Main>返回主界面</a> <a href=Welcome>返回管理用户</a>"); pw.println("</center><hr><img src=images/3.jpg width=120px height=150px>"); pw.println("<body>"); pw.println("<html>"); } catch(Exception ex){ ex.printStackTrace(); } } public void doPost(HttpServletRequest req,HttpServletResponse res){ this.doGet(req,res); } }
9.Err.java
/** 操作失败界面 */ package com.xidian; import javax.servlet.http.*; import java.io.*; public class Err extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res){ try{ //中文乱码 res.setContentType("text/html;charset=gbk"); PrintWriter pw=res.getWriter(); //返回登录界面 pw.println("<html>"); pw.println("<body bgcolor=#CDD4FF >"); pw.println("<center><img src=images/1.jpg width=120px height=150px><hr>"); pw.println("<h1>很遗憾,操作失败!</h1>"); pw.println("</center><hr><img src=images/3.jpg width=120px height=150px>"); pw.println("<body>"); pw.println("<html>"); } catch(Exception ex){ ex.printStackTrace(); } } public void doPost(HttpServletRequest req,HttpServletResponse res){ this.doGet(req,res); } }
10.ConnDB.java
//从数据库中得到连接 package com.xidian; import java.sql.*; import javax.sql.*; import javax.naming.*; public class ConnDB{ private Connection ct=null; public Connection getConn(){ /*try { //连接数据库 Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); //得到连接 ct=DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=test","sa","dba"); } catch (Exception ex) { ex.printStackTrace(); } */ try { //创建一个上下文环境 Context ctt=new javax.naming.InitialContext(); //通过con得到数据源 DataSource ds=(DataSource)ctt.lookup("java:comp/env/mydb"); ct=ds.getConnection(); System.out.println("使用连接池的方式"); } catch (Exception ex) { ex.printStackTrace(); } return ct; } }
11.UserBean.java
//这是一个UserBean<----->users表映射 //它的一个对象<----->users表的一条记录对应 //数据 package com.xidian; public class UserBean{ private int userId; private String userName; private String passwd; private String email; private int grade; public void setUserId(int userId){ this.userId=userId; } public int getUserId(){ return this.userId; } public void setUserName(String userName){ this.userName=userName; } public String getUserName(){ return this.userName; } public void setPasswd(String passwd){ this.passwd=passwd; } public String getPasswd(){ return this.passwd; } public void setMail(String email){ this.email=email; } public String getMail(){ return this.email; } public void setGrade(int grade){ this.grade=grade; } public int getGrade(){ return this.grade; } }
12.UserBeanCl.java
1 //这是一个处理类(处理users表)操作UserBean 2 //业务逻辑 3 4 package com.xidian; 5 import java.sql.*; 6 import java.util.*; 7 8 public class UserBeanCl { 9 10 private Connection ct=null; 11 private PreparedStatement ps=null; 12 private ResultSet rs=null; 13 private int pageCount=0; //共有几页(计算) 14 15 //修改用户 16 public boolean updateUser(String id,String email,String passwd,String grade){ 17 boolean b=false; 18 try{ 19 ConnDB cd=new ConnDB(); 20 ct=cd.getConn(); 21 String sql="update users set passwd='"+passwd+"',email='"+email+"',grade='"+grade+"' where userId='"+id+"'"; 22 ps=ct.prepareStatement(sql); 23 int num=ps.executeUpdate(); 24 if(num==1){ 25 //修改成功! 26 b=true; 27 }else{ 28 //修改失败! 29 30 } 31 } 32 catch(Exception ex){ 33 ex.printStackTrace(); 34 }finally{ 35 this.close(); 36 37 } 38 return b; 39 } 40 41 42 43 44 //删除用户 45 public boolean delUser(String id){ 46 boolean b=false; 47 try{ 48 ConnDB cd=new ConnDB(); 49 ct=cd.getConn(); 50 String sql="delete from users where userId='"+id+"'"; 51 ps=ct.prepareStatement(sql); 52 int num=ps.executeUpdate(); 53 if(num==1){ 54 //删除成功! 55 b=true; 56 }else{ 57 //删除失败! 58 59 } 60 } 61 catch(Exception ex){ 62 ex.printStackTrace(); 63 }finally{ 64 this.close(); 65 66 } 67 return b; 68 } 69 70 71 72 //返回pageCount 73 public int getPageCount(){ 74 return this.pageCount; 75 } 76 77 78 79 80 //分页显示 81 public ArrayList getResultByPage(int pageNow,int pageSize){ 82 ArrayList al=new ArrayList(); 83 84 try{ 85 int rowCount=0; //共有几条记录(查表) 86 87 //得到rowCount 88 ConnDB cd=new ConnDB(); 89 ct=cd.getConn(); 90 ps=ct.prepareStatement("select count(*) from users"); 91 rs=ps.executeQuery(); 92 if(rs.next()){ 93 rowCount=rs.getInt(1); 94 } 95 //计算pageCount 96 if(rowCount%pageSize==0){ 97 pageCount=rowCount/pageSize; 98 }else{ 99 pageCount=rowCount/pageSize+1; 100 } 101 ps=ct.prepareStatement("select top "+pageSize+" * from users where userId not in (select top "+pageSize*(pageNow-1)+" userId from users)"); 102 //给?号赋值 103 // ps.setInt(1,pageSize); 104 // ps.setInt(2,pageSize*(pageNow-1)); 105 106 rs=ps.executeQuery(); 107 while(rs.next()){ 108 //将rs中的每条记录封装到UserBean ub 109 UserBean ub=new UserBean(); 110 ub.setUserId(rs.getInt(1)); 111 ub.setUserName(rs.getString(2)); 112 ub.setPasswd(rs.getString(3)); 113 ub.setMail(rs.getString(4)); 114 ub.setGrade(rs.getInt(5)); 115 //将ub放入到集合ArrayList中 116 al.add(ub); 117 118 } 119 120 } 121 catch(Exception ex){ 122 ex.printStackTrace(); 123 }finally{ 124 this.close(); 125 } 126 127 return al; 128 129 } 130 131 132 //验证用户 133 134 public boolean checkUser(String u,String p){ 135 136 boolean b=false; 137 try{ 138 ConnDB cd=new ConnDB(); 139 ct=cd.getConn(); 140 ps=ct.prepareStatement("select top 1 passwd from users where username= '"+u+"'and passwd='"+p+"'"); 141 rs=ps.executeQuery(); 142 if(rs.next()){ 143 String dbPasswd=rs.getString(1); 144 if(dbPasswd.equals(p)){ 145 b=true; 146 } 147 } 148 } 149 catch(Exception ex){ 150 ex.printStackTrace(); 151 }finally{ 152 this.close(); 153 } 154 155 return b; 156 } 157 158 //关闭资源 159 public void close(){ 160 161 try { 162 if(rs!=null){ 163 rs.close(); 164 } 165 if(ps!=null){ 166 ps.close(); 167 } 168 if(ct!=null){ 169 ct.close(); 170 } 171 172 } 173 catch (Exception ex) { 174 ex.printStackTrace(); 175 } 176 } 177 178 179 }