一个简单的servlet程序(处理用户登陆、操作数据库)

数据库用的是mysql。

最近在学servlet,顺便把代码共享下。

这个servlet程序主要功能是,通过数据库查找验证用户,以及进行简单的管理,如添加、删除。

Login.java

 1 package com.bai;

 2 

 3 import javax.servlet.http.*;

 4 import java.util.Date;

 5 import java.text.DateFormat;

 6 import java.text.SimpleDateFormat; 

 7 import java.net.*;

 8 import java.io.*;

 9 

10 public class Login extends HttpServlet{

11     

12     public void doGet(HttpServletRequest req,HttpServletResponse res){

13             

14 //--------------------------------------------------------------------------------            

15             try{            

16             String ip=req.getRemoteAddr();            

17             this.getServletContext().setAttribute("ip",ip);

18             

19             FileWriter fw=new FileWriter("d:\\ip.txt",true);

20             BufferedWriter bw=new BufferedWriter(fw);

21             //获取当前时间

22             Date dt=new Date();//如果不需要格式,可直接用dt,dt就是当前系统时间

23             DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//设置显示格式

24             String nowTime="";

25             nowTime= df.format(dt);//用DateFormat的format()方法在dt中获取并以yyyy/MM/dd HH:mm:ss格式显示

26                     

27             //在文件中写入数据

28             bw.write(""+this.getServletContext().getAttribute("ip")+"   "+nowTime+"\r\n");

29             //关闭文件流

30             bw.close();

31             }catch(Exception e){

32                 e.printStackTrace();

33             }

34 //-----------------------------------------------------------                

35         try{req.setCharacterEncoding("gb2312");

36         res.setContentType("text/html;charset=gb2312");

37             PrintWriter pw=res.getWriter();

38             pw.println("<html>");

39             pw.println("<body bgcolor=#CACCF6>");

40             pw.println("<center><img src='./imgs/imgs.jpg'/><hr>");

41             pw.println("<h1>登陆界面</h1>");

42             pw.println("<form action=logincl method=post>");  //跳转到logincl

43             pw.println("用户名:<input type=text name=username><br>");

44             pw.println("密码:<input type=password name=passwd><br>");

45             pw.println("<input type=checkbox name=keep value=2>两周内不再重新登陆<br>");

46             pw.println("<input type=submit value=login><br>");

47             pw.println("</form>");

48             pw.println("</center><img src='./imgs/logo.jpg'/><hr>");

49             pw.println("</body>");

50             pw.println("</html>");

51         }

52         catch(Exception e){

53             e.printStackTrace();

54         }

55     }

56     

57     public void doPost(HttpServletRequest req,HttpServletResponse res){

58         this.doGet(req,res);

59     }

60 }
View Code

LoginCl.java

 1 package com.bai;

 2 

 3 import javax.servlet.http.*;

 4 

 5 import java.io.*;

 6 import java.sql.*;

 7 

 8 public class LoginCl extends HttpServlet{

 9     

10     //重写init()函数

11     public void init(){

12         try{

13             //创建一个FileReader

14             FileReader fr=new FileReader("d:\\myCounter.txt");

15             BufferedReader br=new BufferedReader(fr);

16                         

17             //读取一行

18             String numVal=br.readLine();

19             br.close();

20             

21             //将times值放入到servletContext中

22             this.getServletContext().setAttribute("visitTimes",numVal);

23         }catch(Exception e){

24             e.printStackTrace();

25         }

26     }

27     

28     //重写destroy函数

29     public void destroy(){

30         try{

31         //创建一个FileWriter,内存->磁盘,写入,输出

32         FileWriter fw=new FileWriter("d:\\myCounter.txt");

33         BufferedWriter bw=new BufferedWriter(fw);

34                         

35         //在文件中写入数据

36         bw.write(""+this.getServletContext().getAttribute("visitTimes"));

37         //关闭文件流

38         bw.close();

39         }catch(Exception e){

40             e.printStackTrace();

41         }

42     }

43     public void doGet(HttpServletRequest req,HttpServletResponse res){

44         

45         Connection conn=null;

46         Statement stmt=null;

47         ResultSet rs=null;

48         UserBeanCl ubc=null;

49 //        String sql = "select username,passwd from users where username = ? and passwd = ?";

50         String sql = "select passwd from users where username = ?  limit 1";

51         try{//req.setCharacterEncoding("gb2312");

52             String user=req.getParameter("username");

53             String password=req.getParameter("passwd");

54             

55             //调用UserBeanCl

56             ubc=new UserBeanCl();

57             if(ubc.checkUser(user,password))

58             {            

59                     HttpSession hs=req.getSession(true);

60                     hs.setMaxInactiveInterval(60);

61                     hs.setAttribute("name",user);

62                     hs.setAttribute("pass",password);

63                     

64                     String keep=req.getParameter("keep");

65                     if(keep!=null){

66                     

67                     Cookie name=new Cookie("myname",user);

68                     Cookie pass=new Cookie("mypass",password);

69                     name.setMaxAge(14*24*3600);

70                     pass.setMaxAge(14*24*3600);

71                     

72                     res.addCookie(name);

73                     res.addCookie(pass);

74                     }

75                     

76                     //将servletContext中的visitTimes所对应的值+1

77                     String times=this.getServletContext().getAttribute("visitTimes").toString();

78                     //对times的值++然后写回到servletContext

79                     this.getServletContext().setAttribute("visitTimes",(Integer.parseInt(times)+1)+"");

80                     

81                     res.sendRedirect("main");

82                     //res.sendRedirect("welcome?&uname="+user+"&upass="+password);                    

83             }

84             else{

85                 res.sendRedirect("login"); //url

86             }

87             

88         }

89         catch(Exception e){

90             e.printStackTrace();

91         }finally{

92             ubc.close();

93         }

94     }

95     

96     public void doPost(HttpServletRequest req,HttpServletResponse res){

97         this.doGet(req,res);

98     }

99 }
View Code

MainFrame.java

 1 package com.bai;

 2 

 3 import javax.servlet.http.*;

 4 

 5 import java.io.*;

 6 

 7 public class MainFrame extends HttpServlet{

 8     public void doGet(HttpServletRequest req,HttpServletResponse res){

 9         try{req.setCharacterEncoding("gb2312");

10         res.setContentType("text/html;charset=gb2312");

11             PrintWriter pw=res.getWriter();

12             pw.println("<html>");

13             pw.println("<body bgcolor=#CACCF6>");

14             pw.println("<center><img src='./imgs/imgs.jpg'/><hr>");

15             pw.println("<h1>主界面</h1>");

16             pw.println("<a href=welcome>管理用户</a>");

17             pw.println("<a href=adduser>添加用户</a>");

18             pw.println("<a href=check>查询用户</a>");

19             pw.println("<a href=login>安全退出</a>");

20             pw.println("</center><img src='./imgs/logo.jpg'/><hr>");

21             pw.println("</body>");

22             pw.println("</html>");

23         }

24         catch(Exception e){

25             e.printStackTrace();

26         }

27     }

28     

29     public void doPost(HttpServletRequest req,HttpServletResponse res){

30         this.doGet(req,res);

31     }

32 }
View Code

 

Welcome.java

  1 package com.bai;

  2 

  3 import javax.servlet.http.*;

  4 

  5 import java.io.*;

  6 import java.sql.*;

  7 import java.util.ArrayList;

  8 

  9 public class Welcome extends HttpServlet{

 10     public void doGet(HttpServletRequest req,HttpServletResponse res){

 11         Connection conn=null;

 12         Statement stmt=null;

 13         ResultSet rs=null;

 14         String u=null;

 15         String p=null;

 16         

 17         res.setContentType("text/html;charset=gb2312");

 18         HttpSession hs=req.getSession();

 19         String val=(String)hs.getAttribute("pass");

 20         

 21         Cookie []allCookies=req.getCookies();        

 22         if(val==null){

 23             try{

 24                 for(int i=0;i<allCookies.length;i++){

 25                 

 26                 if(allCookies[i].getName().equals("myname"))

 27                     u=allCookies[i].getValue();

 28                 

 29                 else if(allCookies[i].getName().equals("mypass"))

 30                     p=allCookies[i].getValue();

 31                 }

 32                 if(u!=null&&p!=null){

 33 //                    hs.setAttribute("pass",p);

 34 //                    res.sendRedirect("welcome?&uname="+u+"&upass="+p);

 35                     res.sendRedirect("logincl?username="+u+"&passwd="+p);

 36                     return ;

 37                 }

 38                 

 39                     res.sendRedirect("login");

 40                     return ;

 41             }catch(Exception e){

 42                 e.printStackTrace();

 43             }

 44             

 45         }    

 46             

 47         u=req.getParameter("uname");

 48         p=req.getParameter("upass");

 49         

 50         try{//req.setCharacterEncoding("gb2312");

 51         

 52         int pageSize=5;//每一页显示记录数

 53         int pageNow=1; //当前页

 54         

 55         //动态接收pageNow

 56         String sPageNow=req.getParameter("pageNow");

 57         if(sPageNow!=null){

 58                 pageNow=Integer.parseInt(sPageNow);

 59         }

 60         

 61         //调用UserBeanCl

 62         UserBeanCl ubc=new UserBeanCl();

 63         ArrayList al=ubc.getResultByPage(pageNow,pageSize);

 64         

 65         PrintWriter pw=res.getWriter();

 66     

 67         pw.println("<body><center>");

 68         pw.println("<body bgcolor=#CACCF6>");

 69         pw.println("<img src='./imgs/imgs.jpg'/>");

 70         pw.println("<h1>管理用户</h1>");

 71         pw.println("<table border=1>");//带边框的表格

 72         pw.println("<tr><th>id</th><th>name</th><th>password</th><th>email</th><th>grade</th><th>修改用户</th><th>删除用户</th></tr>");//表头

 73         for(int i=0;i<al.size();i++){

 74             UserBean ub=(UserBean)al.get(i);

 75             pw.println("<tr>");

 76             pw.println("<td>"+ub.getUserId()+"</td>");

 77             pw.println("<td>"+ub.getUserName()+"</td>");

 78             pw.println("<td>"+ub.getPasswd()+"</td>");

 79             pw.println("<td>"+ub.getEmail()+"</td>");

 80             pw.println("<td>"+ub.getGrade()+"</td>");

 81             pw.println("<td><a href=update?uId="+ub.getUserId()+"&uName="+ub.getUserName()+"&uPass="+ub.getPasswd()+"&uMail="+ub.getEmail()+"&uGrade="+ub.getGrade()+">修改用户</a></td>");

 82             pw.println("<td><a href=delete?userid="+ub.getUserId()+" onclick=\"return window.confirm('你确认要删除该用户吗?')\">删除用户</a></td>");

 83             pw.println("</tr>");

 84         }

 85         pw.println("</table>");    

 86 //        res.setContentType("text/html;charset=gb2312");

 87         int pageCount=ubc.getPageCount();

 88         if(pageNow!=1)

 89             pw.println("<a href=welcome?pageNow="+(pageNow-1)+"&uname="+u+"&upass="+p+">"+"last"+"</a>");

 90         

 91         for(int i=pageNow;i<=pageNow+4;i++){

 92             pw.println("<a href=welcome?pageNow="+i+"&uname="+u+"&upass="+p+">"+i+"</a>");

 93         }

 94         if(pageNow!=pageCount)

 95             pw.println("<a href=welcome?pageNow="+(pageNow+1)+"&uname="+u+"&upass="+p+">"+"next"+"</a>");

 96         

 97         //跳转功能

 98         pw.println("<form action=welcome method=post>");

 99         pw.println("Go to<input type=text name=pageNow>page<br>");

100         pw.println("<input type=submit value=Go><br>");

101             

102 //        pw.println("<img src='./imgs/imgs.jpg'/>");

103 //        pw.println("welcome! "+u+"&pass="+p);

104         pw.println("该网页被访问了"+this.getServletContext().getAttribute("visitTimes").toString()+"次");

105         pw.println("你的IP:"+req.getRemoteAddr()+"<br>");

106         pw.println("你的机器名="+req.getRemoteHost()+"<br>");

107         pw.println("</center><img src='./imgs/logo.jpg'/><hr>");

108         pw.println("</body>");

109         }

110         catch(Exception e){

111             e.printStackTrace();

112         }finally{

113             

114         }

115     }

116     public void doPost(HttpServletRequest req,HttpServletResponse res){

117         this.doGet(req,res);

118     }

119 }
View Code

 

 UserBeanCl.java

  1 //处理users表的类,操作userbean

  2 //业务逻辑

  3 package com.bai;

  4 import java.sql.*;

  5 import java.util.ArrayList;

  6 public class UserBeanCl{

  7     //业务逻辑

  8     private Connection conn=null;

  9     private PreparedStatement ps=null;

 10     private ResultSet rs=null;

 11     private int rowCount=0;//共有几条记录

 12     private int pageCount=0;//共有几页

 13     

 14     //查询用户

 15     public ArrayList Check(String querytype,String username){

 16         ArrayList al=new ArrayList();

 17         try{

 18             //得到连接

 19             ConnDB cd=new ConnDB();

 20             conn=cd.getConn();

 21             Statement stmt = conn.createStatement();

 22             if(querytype.equals("fuzzy")){ //模糊查询

 23                 //模糊查询算法

 24                 char arr[]=username.toCharArray();

 25                 String sql="select * from users where ";

 26                 for(int i=0;i<username.length();i++){

 27                     if(i==0)

 28                         sql=sql.concat("upper(username) like '%"+arr[i]+"%' ");

 29                     else sql=sql.concat("and upper(username) like '%"+arr[i]+"%' ");

 30                 }

 31                 System.out.println(sql);

 32                 rs=stmt.executeQuery(sql);

 33                 

 34             }

 35             if(querytype.equals("precise")){  //精确查询        

 36                 ps=conn.prepareStatement("select * from users where username=?");                        

 37                 ps.setString(1,username);

 38                 rs=ps.executeQuery();

 39                 System.out.println(ps);

 40                 //String sql1=("select * from users where username=");

 41                 //sql1=sql1.concat(username);

 42                 //System.out.println(sql1);

 43                 //rs=stmt.executeQuery(sql1);

 44             }

 45             while(rs.next()){

 46                 //将rs中每条记录封装到userbean中

 47                 UserBean ub=new UserBean();

 48                 ub.setUserId(rs.getInt(1));

 49                 ub.setUserName(rs.getString(2));

 50                 ub.setPasswd(rs.getString(3));

 51                 ub.setEmail(rs.getString(4));

 52                 ub.setGrade(rs.getInt(5));

 53                 

 54                 //将ub放入到ArrayList中

 55                 al.add(ub);

 56             }

 57         }catch(Exception e){

 58             e.printStackTrace();

 59         }finally{

 60             this.close();

 61         }

 62             return al;

 63     }

 64     

 65     //添加用户

 66     public boolean AddUser(String id,String username,String email,String passwd,String grade){

 67         try{

 68             //得到连接

 69             ConnDB cd=new ConnDB();

 70             conn=cd.getConn();

 71             

 72             ps=conn.prepareStatement("insert into users(userId,username,passwd,email,grade) values(?,?,?,?,?)");

 73             ps.setString(1,id);

 74             ps.setString(2,username);

 75             ps.setString(3,email);

 76             ps.setString(4,passwd);

 77             ps.setString(5,grade);

 78 

 79             int num=ps.executeUpdate();

 80             if(num==1){

 81                 return true;

 82             }

 83             

 84         }catch(Exception e){

 85             e.printStackTrace();

 86         }finally{

 87             this.close();

 88         }

 89         return false;

 90     }

 91     

 92     //修改用户

 93     public boolean UpdateUser(String id,String email,String passwd,String grade){

 94         try{

 95             //得到连接

 96             ConnDB cd=new ConnDB();

 97             conn=cd.getConn();

 98             

 99             ps=conn.prepareStatement("update users set email=?,passwd=?,grade=? where userId=?");

100             ps.setString(1,email);

101             ps.setString(2,passwd);

102             ps.setString(3,grade);

103             ps.setString(4,id);

104             int num=ps.executeUpdate();

105             if(num==1){

106                 return true;

107             }

108             

109         }catch(Exception e){

110             e.printStackTrace();

111         }finally{

112             this.close();

113         }

114         return false;

115     }

116     

117     //删除用户

118     public boolean deleteUser(String id){

119         try{

120             //得到连接

121             ConnDB cd=new ConnDB();

122             conn=cd.getConn();

123             

124             ps=conn.prepareStatement("delete from users where userId=?");

125             ps.setString(1,id);

126             int num=ps.executeUpdate();

127             if(num==1){

128                 return true;

129             }

130             

131         }catch(Exception e){

132             e.printStackTrace();

133         }finally{

134             this.close();

135         }

136         return false;

137     }

138     

139     //返回pageCount

140     public int getPageCount(){

141         return this.pageCount;

142     }

143     //分页显示

144     public ArrayList getResultByPage(int pageNow,int pageSize){

145         

146         ArrayList al=new ArrayList();

147         try{

148         

149         ConnDB cd=new ConnDB();

150         conn=cd.getConn();

151         ps=conn.prepareStatement("select count(*) from users");

152         rs=ps.executeQuery();

153         //得到行数

154         if(rs.next()){

155             rowCount = rs.getInt(1);

156         }

157         //计算页数

158         if(rowCount%pageSize==0){

159             pageCount=rowCount/pageSize;

160         }else{

161             pageCount=rowCount/pageSize+1;

162         }

163         String sql="select * from users where userId not in(select * from(select userId from users limit ?)a) limit ?";

164         PreparedStatement pstmt = conn.prepareStatement(sql);

165         pstmt.setInt(2,pageSize);

166         pstmt.setInt(1,pageSize*(pageNow-1));

167         rs=pstmt.executeQuery();

168         

169         while(rs.next()){

170             //将rs中每条记录封装到userbean中

171             UserBean ub=new UserBean();

172             ub.setUserId(rs.getInt(1));

173             ub.setUserName(rs.getString(2));

174             ub.setPasswd(rs.getString(3));

175             ub.setEmail(rs.getString(4));

176             ub.setGrade(rs.getInt(5));

177             

178             //奖ub放入到ArrayList中

179             al.add(ub);

180         }

181         }catch(Exception e){

182             e.printStackTrace();

183         }finally{

184             this.close();

185         }

186         return al;

187     }

188     

189     //验证用户

190     public boolean checkUser(String u,String p){

191         boolean b=false;

192         try{

193             //得到连接

194             ConnDB cd=new ConnDB();

195             conn=cd.getConn();

196             

197             ps=conn.prepareStatement("select passwd from users where username = ?  limit 1");

198             ps.setString(1,u);

199             rs=ps.executeQuery();

200             

201             if(rs.next()){            

202                 String dbPasswd=rs.getString(1);

203                 if(dbPasswd.equals(p)) {

204                     b=true;

205                 }

206             }            

207         }catch(Exception e){

208             e.printStackTrace();

209         }finally{

210             this.close();

211         }

212         return b;

213     }

214     

215     //关闭数据库连接

216     public  void close(){

217         try{

218             if(rs!=null){

219                 rs.close();

220                 rs=null;

221             }

222             if(ps!=null){

223                 ps.close();

224                 ps=null;

225             }

226             if(conn!=null){

227                 conn.close();

228                 conn=null;

229             }

230         }catch(Exception e){

231             e.printStackTrace();

232         }

233     }

234 }
View Code

 

ConnDB.java   //获取数据库连接

 1 //g从数据库得到连接

 2 

 3 package com.bai;

 4 import java.sql.*;

 5 

 6 public class ConnDB{

 7     private Connection conn=null;

 8     public Connection getConn(){

 9         try{

10             //加载驱动

11             Class.forName("com.mysql.jdbc.Driver");

12             //得到连接

13             conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/sqdb","root","root");

14         }catch(Exception e){

15             e.printStackTrace();

16         }

17         return conn;

18     }

19 }
View Code

UserBean.java

 1 package com.bai;

 2 

 3 public class UserBean{

 4     private int userId;

 5     private String userName;

 6     private String passwd;

 7     private String email;

 8     private int grade;

 9     

10     public  void setUserId(int userId){

11         this.userId=userId;

12     }

13     public int getUserId(){

14         return (this.userId);

15     }

16 

17     

18     public void setEmail(String email) {

19         this.email = email; 

20     }

21 

22     public String getEmail() {

23         return (this.email); 

24     }

25 

26     

27     public void setUserName(String userName) {

28         this.userName = userName; 

29     }

30 

31     public void setPasswd(String passwd) {

32         this.passwd = passwd; 

33     }

34 

35     public void setGrade(int grade) {

36         this.grade = grade; 

37     }

38 

39     public String getUserName() {

40         return (this.userName); 

41     }

42 

43     public String getPasswd() {

44         return (this.passwd); 

45     }

46 

47     public int getGrade() {

48         return (this.grade); 

49     }

50 }
View Code

 Update.java

 1 package com.bai;

 2 

 3 import javax.servlet.http.*;

 4 

 5 import java.io.*;

 6 

 7 public class Update extends HttpServlet{

 8     

 9     public void doGet(HttpServletRequest req,HttpServletResponse res){

10             

11         

12         try{req.setCharacterEncoding("gb2312");

13         res.setContentType("text/html;charset=gb2312");

14             PrintWriter pw=res.getWriter();

15             pw.println("<html>");

16             pw.println("<body bgcolor=#CACCF6>");

17             pw.println("<center><img src='./imgs/imgs.jpg'/><hr>");

18             

19             pw.println("<h1>修改用户界面</h1>");

20             pw.println("<form action=updatecl>");

21             pw.println("<table border=1>");

22             

23             pw.println("<tr><td>id</td><td><input readonly name=userid type=text value="+req.getParameter("uId")+"></td></tr>");

24             pw.println("<tr><td>name</td><td><input readonly type=text value="+req.getParameter("uName")+"></td></tr>");

25             pw.println("<tr><td>passwd</td><td><input type=text name=newPass value="+req.getParameter("uPass")+"></td></tr>");

26             pw.println("<tr><td>email</td><td><input type=text name=newEmail value="+req.getParameter("uMail")+"></td></tr>");

27             pw.println("<tr><td>grade</td><td><input type=text name=newGrade value="+req.getParameter("uGrade")+"></td></tr>");

28             pw.println("<tr><td colspan=2><input type=submit value=修改用户></td></tr>");

29             pw.println("</table></form>");

30             

31             pw.println("</center><img src='./imgs/logo.jpg'/><hr>");

32             pw.println("</body>");

33             pw.println("</html>");

34         }

35         catch(Exception e){

36             e.printStackTrace();

37         }

38     }

39     

40     public void doPost(HttpServletRequest req,HttpServletResponse res){

41         this.doGet(req,res);

42     }

43 }
View Code

UpdateCl.java

 1 package com.bai;

 2 

 3 import javax.servlet.http.*;

 4 

 5 import java.io.*;

 6 

 7 public class UpdateCl extends HttpServlet{

 8     public void doGet(HttpServletRequest req,HttpServletResponse res){

 9         try{

10             res.setContentType("text/html;charset=gbk");

11             

12             UserBeanCl ubc=new UserBeanCl();

13 

14             if(ubc.UpdateUser(req.getParameter("userid"),req.getParameter("newEmail"),req.getParameter("newPass"),req.getParameter("newGrade"))){

15                 //删除成功

16                 res.sendRedirect("ok");

17             }else{

18                 //删除失败

19                 res.sendRedirect("err");

20             }

21         }

22         catch(Exception e){

23             e.printStackTrace();

24         }

25     }

26     

27     public void doPost(HttpServletRequest req,HttpServletResponse res){

28         this.doGet(req,res);

29     }

30 }
View Code

 

AddUser.java

 1 package com.bai;

 2 

 3 import javax.servlet.http.*;

 4 

 5 import java.io.*;

 6 

 7 public class AddUser extends HttpServlet{

 8     

 9     public void doGet(HttpServletRequest req,HttpServletResponse res){

10             

11         

12         try{req.setCharacterEncoding("gb2312");

13         res.setContentType("text/html;charset=gb2312");

14             PrintWriter pw=res.getWriter();

15             pw.println("<html>");

16             pw.println("<body bgcolor=#CACCF6>");

17             pw.println("<center><img src='./imgs/imgs.jpg'/><hr>");

18             

19             pw.println("<h1>添加用户界面</h1>");

20             pw.println("<form action=addusercl method=post>");

21             

22             pw.println("用户id:<input type=text name=userid><br>");

23             pw.println("用户名:<input type=text name=username><br>");

24             pw.println("密  码:<input type=password name=passwd><br>");

25             pw.println("邮  箱:<input type=text name=email><br>");

26             pw.println("等  级:<input type=text name=grade><br>");

27             

28             pw.println("<input type=submit value=添加><br>");

29             pw.println("</form>");

30             

31             pw.println("</center><img src='./imgs/logo.jpg'/><hr>");

32             pw.println("</body>");

33             pw.println("</html>");

34         }

35         catch(Exception e){

36             e.printStackTrace();

37         }

38     }

39     

40     public void doPost(HttpServletRequest req,HttpServletResponse res){

41         this.doGet(req,res);

42     }

43 }
View Code

AddUserCl.java

 1 package com.bai;

 2 

 3 import javax.servlet.http.*;

 4 

 5 import java.io.*;

 6 

 7 public class AddUserCl extends HttpServlet{

 8     public void doGet(HttpServletRequest req,HttpServletResponse res){

 9         try{

10             res.setContentType("text/html;charset=gbk");

11             

12             UserBeanCl ubc=new UserBeanCl();

13 

14             if(ubc.AddUser(req.getParameter("userid"),req.getParameter("username"),req.getParameter("email"),req.getParameter("passwd"),req.getParameter("grade"))){

15                 //删除成功

16                 res.sendRedirect("ok");

17             }else{

18                 //删除失败

19                 res.sendRedirect("err");

20             }

21         }

22         catch(Exception e){

23             e.printStackTrace();

24         }

25     }

26     

27     public void doPost(HttpServletRequest req,HttpServletResponse res){

28         this.doGet(req,res);

29     }

30 }
View Code

DeleteUser.java

 1 package com.bai;

 2 

 3 import javax.servlet.http.*;

 4 

 5 import java.io.*;

 6 

 7 public class DeleteUser extends HttpServlet{

 8     public void doGet(HttpServletRequest req,HttpServletResponse res){

 9         try{

10             res.setContentType("text/html;charset=gbk");

11             

12             //调用userBean的删除用户的方法,完成删除

13             UserBeanCl ubc=new UserBeanCl();

14             //接收从welcome.java中传递的id

15             String id=req.getParameter("userid");

16             System.out.println("id="+id);

17             if(ubc.deleteUser(id)){

18                 //删除成功

19                 res.sendRedirect("ok");

20             }else{

21                 //删除失败

22                 res.sendRedirect("err");

23             }

24         }

25         catch(Exception e){

26             e.printStackTrace();

27         }

28     }

29     

30     public void doPost(HttpServletRequest req,HttpServletResponse res){

31         this.doGet(req,res);

32     }

33 }
View Code

DeleteError.java

 1 //删除失败

 2 

 3 package com.bai;

 4 

 5 import javax.servlet.http.*;

 6 

 7 import java.io.*;

 8 

 9 public class DeleteError extends HttpServlet{

10     public void doGet(HttpServletRequest req,HttpServletResponse res){

11         try{

12             res.setContentType("text/html;charset=gbk");

13             PrintWriter pw=res.getWriter();

14             pw.println("<html>");

15             pw.println("<body bgcolor=#CACCF6>");

16             pw.println("<center><img src='./imgs/imgs.jpg'/><hr>");

17             

18             pw.println("<h1>操作失败!</h1>");

19             pw.println("</center><img src='./imgs/logo.jpg'/><hr>");

20             pw.println("</body>");

21             pw.println("</html>");

22         }

23         catch(Exception e){

24             e.printStackTrace();

25         }

26     }

27     

28     public void doPost(HttpServletRequest req,HttpServletResponse res){

29         this.doGet(req,res);

30     }

31 }
View Code

Ok.java

 1 //删除成功界面

 2 package com.bai;

 3 

 4 import javax.servlet.http.*;

 5 

 6 import java.io.*;

 7 

 8 public class Ok extends HttpServlet{

 9     public void doGet(HttpServletRequest req,HttpServletResponse res){

10         try{

11             res.setContentType("text/html;charset=gbk");

12             PrintWriter pw=res.getWriter();

13             pw.println("<html>");

14             pw.println("<body bgcolor=#CACCF6>");

15             pw.println("<center><img src='./imgs/imgs.jpg'/><hr>");

16             

17             pw.println("<h1>操作成功!</h1>");

18             pw.println("<a href=main>返回主界面</a>&nbsp;&nbsp;&nbsp;<a href=welcome>继续删除用户</a>");

19             pw.println("</center><img src='./imgs/logo.jpg'/><hr>");

20             pw.println("</body>");

21             pw.println("</html>");

22         }

23         catch(Exception e){

24             e.printStackTrace();

25         }

26     }

27     

28     public void doPost(HttpServletRequest req,HttpServletResponse res){

29         this.doGet(req,res);

30     }

31 }
View Code

新增的查询功能

CheckUser.java

 1 package com.bai;

 2 

 3 import javax.servlet.http.*;

 4 

 5 import java.io.*;

 6 

 7 public class CheckUser extends HttpServlet{

 8     

 9     public void doGet(HttpServletRequest req,HttpServletResponse res){

10             

11         

12         try{req.setCharacterEncoding("gb2312");

13         res.setContentType("text/html;charset=gb2312");

14             PrintWriter pw=res.getWriter();

15             pw.println("<html>");

16             pw.println("<body bgcolor=#CACCF6>");

17             pw.println("<center><img src='./imgs/imgs.jpg'/><hr>");

18             pw.println("<h1>查询用户</h1>");

19             

20             pw.println("<form action=checkop method=post>");

21             pw.println("请输入用户名:<input type=text name=username>");

22             pw.println("<input type=submit value=查询><br>");

23             pw.println("<input type=radio checked=checked name=querytype value=fuzzy>模糊查询<br>");

24             pw.println("<input type=radio name=querytype value=precise>精确查询<br>");

25             pw.println("</form>");

26             

27             pw.println("</center><img src='./imgs/logo.jpg'/><hr>");

28             pw.println("</body>");

29             pw.println("</html>");

30         }

31         catch(Exception e){

32             e.printStackTrace();

33         }

34     }

35     

36     public void doPost(HttpServletRequest req,HttpServletResponse res){

37         this.doGet(req,res);

38     }

39 }
View Code

CheckUserOperation.java

 1 package com.bai;

 2 

 3 import javax.servlet.http.*;

 4 import java.util.ArrayList;

 5 import java.io.*;

 6 

 7 public class CheckUserOperation extends HttpServlet{

 8     public void doGet(HttpServletRequest req,HttpServletResponse res){

 9         try{

10             res.setContentType("text/html;charset=gbk");

11             UserBeanCl ubc=new UserBeanCl();

12             

13             HttpSession hs=req.getSession(true);

14             

15             ArrayList al=new ArrayList();

16             al=null;

17             al=ubc.Check(req.getParameter("querytype"),req.getParameter("username"));

18             if(al.size()!=0){

19                 //查询到结果

20                 res.sendRedirect("checkresult?state="+"true");

21                 hs.setAttribute("result",al);

22             }else{

23                 //没查询到结果

24                 System.out.println("no result");

25                 

26                 res.sendRedirect("checkresult?state="+"false");

27             }

28         }

29         catch(Exception e){

30             e.printStackTrace();

31         }

32     }

33     

34     public void doPost(HttpServletRequest req,HttpServletResponse res){

35         this.doGet(req,res);

36     }

37 }
View Code

CheckResult.java

 1 package com.bai;

 2 

 3 import javax.servlet.http.*;

 4 import java.util.ArrayList;

 5 import java.io.*;

 6 

 7 public class CheckResult extends HttpServlet{

 8     

 9     public void doGet(HttpServletRequest req,HttpServletResponse res){

10             

11         ArrayList al=new ArrayList();

12         HttpSession hs=req.getSession();

13         

14         try{req.setCharacterEncoding("gb2312");

15             res.setContentType("text/html;charset=gb2312");

16             PrintWriter pw=res.getWriter();

17             pw.println("<html>");

18             pw.println("<body bgcolor=#CACCF6>");

19             pw.println("<center><img src='./imgs/imgs.jpg'/><hr>");

20             pw.println("<h1>查询用户</h1>");

21             

22             pw.println("<form action=checkop method=post>");

23             pw.println("请输入用户名:<input type=text name=username>");

24             pw.println("<input type=submit value=查询><br>");

25             pw.println("<input type=radio checked=checked name=querytype value=fuzzy>模糊查询<br>");

26             pw.println("<input type=radio name=querytype value=precise>精确查询<br>");

27             pw.println("</form>");

28             

29             //如果查询到,则列出结果

30             if(req.getParameter("state").equals("true")){

31                 al=(ArrayList)hs.getAttribute("result");

32                     pw.println("<table border=1>");//带边框的表格

33                     pw.println("<tr><th>id</th><th>name</th><th>password</th><th>email</th><th>grade</th></tr>");//表头

34                     for(int i=0;i<al.size();i++){

35                         UserBean ub=(UserBean)al.get(i);

36                         pw.println("<tr>");

37                         pw.println("<td>"+ub.getUserId()+"</td>");

38                         pw.println("<td>"+ub.getUserName()+"</td>");

39                         pw.println("<td>"+ub.getPasswd()+"</td>");

40                         pw.println("<td>"+ub.getEmail()+"</td>");

41                         pw.println("<td>"+ub.getGrade()+"</td>");

42                         pw.println("</tr>");

43                     }

44                     pw.println("</table>");    

45             }else{

46                 pw.println("找不到此用户");

47             }

48             pw.println("</center><img src='./imgs/logo.jpg'/><hr>");

49             pw.println("</body>");

50             pw.println("</html>");

51         }

52         catch(Exception e){

53             e.printStackTrace();

54         }

55     }

56     

57     public void doPost(HttpServletRequest req,HttpServletResponse res){

58         this.doGet(req,res);

59     }

60 }
View Code

 

你可能感兴趣的:(servlet)