当前位置:文档之家› jsp编写登录界面

jsp编写登录界面

/blog/20091213/77.html按以下要求建立用户帐号信息表:用户ID:字符型,最大长度20用户姓名:字符型,最大长度20用户密码:字符型,最大长度20编写用户登陆页面。

当用户输入正确的用户ID及密码后迁移到“登录成功”提示页面。

否则用户重新进行登录。

11111 张三11111122222 李四22222233333 张五333333编写这个project时主要遇到了一个jsp页面的url传值问题,其次就是一些逻辑处理的问题url传参的String n = request.getParameter(“wrongid”);if(n == “wrongid1″)判断不了。

请教了某个高手后才知道java的字符串是不能这样判断的,要用n.equals()方法。

java中字符串的存储方法不一样,不是基本数据类型。

至此三个实验全部完成了,发现java还是挺有意思的,我很想学java啊……..可惜最近忙的要死,都抽不出时间看书。

我这人最大的杯具就是对什么都感兴趣,什么都懂一点,但是什么都不精通……..附上核心代码和工程压缩包下载:index.jsp<form id="form" action="login.jsp" method="post"><label>用户ID:<input id="username" name="username" size="15" type="text" /></label><label>密码:<input id="password" name="password" size="15" type="password" /></label><label><input type="submit" value="登陆" /></label></form>login.jspString userid = request.getParameter("username");String password = request.getParameter("password");if( userid ==""|| userid ==null|| userid.length()&gt;20|| password =="" || password ==null|| password.length()&gt;20){try{response.sendRedirect("wrong.jsp?wrongid=1");}catch(Exception e ){}}else{Connection conn =null;Statement stmt =null;ResultSet rs =null;try{Class.forName("com.mysql.jdbc.Driver").newInstance();conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/member?user=root&amp ;password=root&amp;useUnicode=true&amp;characterEncoding=utf-8");stmt = conn.createStatement();String sql="SELECT name FROM member where id="+userid+" and pw="+password;if(stmt.execute(sql)){rs = stmt.getResultSet();while(rs.next()){out.println("登陆成功!");out.println("欢迎您:"+rs.getString("name"));}}conn.close();}catch(SQLException ex){response.sendRedirect("wrong.jsp?wrongid=2");}catch(InstantiationException e){response.sendRedirect("wrong.jsp?wrongid=2");}catch(IllegalAccessException e){response.sendRedirect("wrong.jsp?wrongid=2");}catch(ClassNotFoundException e){response.sendRedirect("wrong.jsp?wrongid=2");}finally{if(rs !=null){try{rs.close();}catch(SQLException sqlEx){}// ignorers =null;}if(stmt !=null){try{stmt.close();}catch(SQLException sqlEx){}// ignorestmt =null;}}}wrong.jspString n = request.getParameter("wrongid");if(n.equals("1")){out.println("1.您没输入ID或密码。

2.ID和密码不能超过20字符");out.println("<a href="¥">点此重新登陆</a>");}else if(n.equals("2")){out.println("Sorry,登陆失败。

");out.println("您输入的用户ID或密码不对哦。

");out.println("<a href="¥">点此重新登陆</a>");}else{out.println("你又在干坏事拉!");}工程压缩包下载:http://cid-87b2103a38e6466e.skydrive.li声明:作者原创,版权所有。

未经授权,不得转载在jsp中用bean和servlet联合实现用户注册、登录作者:imagebear版权:imagebear本例需要的软件和运行环境:1、Windows2000 Server操作系统2、jdk1.43、JCreator2.5(java源码编辑调试器,吐血推荐!)4、Macromedia JRun MX5、Macromedia Dreamweaver MX(非必需)6、MySQL数据库(最好安装MySQL Control Center)一、数据库设计用MySQL Control Center打开MySQL数据库,新建数据库shopping,在其下新建表tbl_user,其中各字段设置如下:二、编写连接数据库bean:DBConn.java//DBConn.java//include required classesimport java.sql.*;//========================================== // Define Class DBConn//========================================== public class DBConn{public String sql_driver = "org.gjt.mm.mysql.Driver";public String sql_url = "jdbc:mysql://localhost:3306";public String sql_DBName = "shopping";public String user = "sa";public String pwd = "";Connection conn = null;Statement stmt = null;ResultSet rs = null;public boolean setDriver(String drv){this.sql_driver = drv;return true;}public String getDriver(){return this.sql_driver;}public boolean setUrl(String url){this.sql_url = url;return true;}public boolean setDBName(String dbname){this.sql_DBName = dbname;return true;}public String getDBName(){return this.sql_DBName;}public boolean setUser(String user){er = user;return true;}public String getUser(){return er;}public boolean setPwd(String pwd){this.pwd = pwd;return true;}public String getPwd(){return this.pwd;}public DBConn(){try{Class.forName(sql_driver);//加载数据库驱动程序this.conn = DriverManager.getConnection(sql_url + "/" + sql_DBName + "?user=" + user + "&password=" + pwd + "&useUnicode=true&characterEncoding=gb2312");this.stmt = this.conn.createStatement();}catch(Exception e){System.out.println(e.toString());}}//执行查询操作public ResultSet executeQuery(String strSql) {try{this.rs = stmt.executeQuery(strSql);return this.rs;}catch(SQLException e){System.out.println(e.toString());return null;}catch(NullPointerException e){System.out.println(e.toString());return null;}}//执行数据的插入、删除、修改操作 public boolean execute(String strSql){try{if(this.stmt.executeUpdate(strSql) == 0)return false;elsereturn true;}catch(SQLException e){System.out.println(e.toString());return false;}catch(NullPointerException e){System.out.println(e.toString());return false;}}//结果集指针跳转到某一行public boolean rs_absolute(int row){try{this.rs.absolute(row);return true;}catch(SQLException e){ System.out.println(e.toString()); return false;}}public void rs_afterLast(){try{this.rs.afterLast();}catch(SQLException e){ System.out.println(e.toString()); }}public void rs_beforeFirst(){try{this.rs.beforeFirst();}catch(SQLException e){ System.out.print(e.toString()); }}public void rs_close(){try{this.rs.close();}catch(SQLException e){ System.out.print(e.toString()); }}public void rs_deleteRow(){try{this.rs.deleteRow();}catch(SQLException e){System.out.print(e.toString());}}public boolean rs_first(){try{this.rs.first();return true;}catch(SQLException e){System.out.print(e.toString());return false;}}public String rs_getString(String column){try{return this.rs.getString(column);}catch(SQLException e){System.out.println(e.toString());return null;}}//此方法用于获取大段文本,//将其中的回车换行替换为<br>//输出到html页面public String rs_getHtmlString(String column) {try{String str1 = this.rs.getString(column);String str2 = "¥r¥n";String str3 = "<br>";return this.replaceAll(str1,str2,str3);}catch(SQLException e){System.out.println(e.toString());return null;}}//把str1字符串中的str2字符串替换为str3字符串private static String replaceAll(String str1,String str2,String str3){StringBuffer strBuf = new StringBuffer(str1);int index=0;while(str1.indexOf(str2,index)!=-1){index=str1.indexOf(str2,index);strBuf.replace(str1.indexOf(str2,index),str1.indexOf(str2,index)+str2.length(),str3); index=index+str3.length();str1=strBuf.toString();}return strBuf.toString();}public int rs_getInt(String column){try{return this.rs.getInt(column);}catch(SQLException e){System.out.println(e.toString());return -1;}}public int rs_getInt(int column){try{return this.rs.getInt(column);}catch(SQLException e){ System.out.println(e.toString()); return -1;}}public boolean rs_next(){try{return this.rs.next();}catch(SQLException e){ System.out.println(e.toString()); return false;}}//判断结果集中是否有数据 public boolean hasData(){try{boolean has_Data = this.rs.first(); this.rs.beforeFirst();return has_Data;}catch(SQLException e){ System.out.println(e.toString()); return false;}}public boolean rs_last(){try{return st();}catch(SQLException e){ System.out.println(e.toString());return false;}}public boolean rs_previous(){try{return this.rs.previous();}catch(Exception e){System.out.println(e.toString());return false;}}//main方法,调试用public static void main(String args[]){try{DBConn myconn = new DBConn();//myconn.setDBName("shopping");//myconn.DBConn();//myconn.execute("Insert Into tbl_test(id,name) values(10,shandaer)");//myconn.execute("Update tbl_test set name=yyyyyyyyyyyy where id=10");//myconn.execute("Delete from tbl_test where id=1");ResultSet rs = myconn.executeQuery("select * from tbl_user order by id desc limit 1"); //boolean hasData = myconn.hasData();//System.out.println("has data:" + hasData);//rs.first();while (myconn.rs.next()){int id = myconn.rs_getInt("id") + 1;System.out.print(id);System.out.println(myconn.rs_getInt("id") + myconn.rs_getString("name"));//System.out.println(¥n + myconn.rs_getHtmlString("name"));//System.out.println(myconn.rs.getString("name") + myconn.rs_getInt(1));}}catch(Exception e){System.err.println(e.toString());}}}声明:因为使用的是MySQL数据库,所以需要MySQL数据库的驱动下载后请将org包放至DBConn.java所在目录下以确保该bean能正常运行三、编写用户注册的bean:reg.java//reg.java//import required classesimport java.sql.*;public class reg{public int newID = 0;public boolean result = false;public boolean reg(String username,String password,String confirm,String email) {try{if(!this.checkUser(username))return false;if(!this.checkPwd(password))return false;if(!this.verifyPwd(password,confirm))return false;if(!this.checkEmail(email))return false;if(!erNotExit(username))return false;this.getNewID();this.result = this.register(username,password,confirm,email); return this.result;}catch(Exception e){System.out.println(e.toString());return false;}}//End boolean regpublic boolean checkUser(String user){try{if(user.indexOf("")!=-1){System.out.println("姓名中含有非法字符!");return false;}elsereturn true;}catch(Exception e){System.out.println(e.toString());return false;}}public boolean checkPwd(String pwd){try{if(pwd.indexOf("")!=-1){System.out.println("密码中含有非法字符!");return false;}elsereturn true;}catch(Exception e){System.out.println(e.toString());return false;}}public boolean verifyPwd(String pwd,String confirm) {try{if(!pwd.equals(confirm)){System.out.println("两次输入的密码不一致!");return false;}elsereturn true;}catch(Exception e){System.out.println(e.toString());return false;}}public boolean checkEmail(String email){try{if(email.indexOf("")!=-1){System.out.println("E-mail中含有非法字符!");return false;}elsereturn true;}catch(Exception e){System.out.println(e.toString());return false;}}public boolean userNotExit(String user){try{DBConn userDBConn = new DBConn();userDBConn.executeQuery("select * from tbl_user where name=" + user + ""); if(userDBConn.rs_next()){System.out.println("用户名已存在,请选择其它的用户名!");return false;}elsereturn true;}catch(Exception e){System.out.println(e.toString());return false;}}public int getNewID(){try{DBConn newIDDBConn = new DBConn();newIDDBConn.executeQuery("select * from tbl_user order by id desc limit 1"); if(newIDDBConn.rs_next()){this.newID = newIDDBConn.rs_getInt("id") + 1;System.out.println(this.newID);}else{this.newID = 1;}return this.newID;}catch(Exception e){System.out.println(e.toString());return -1;}}public int getID(){return this.newID;}public boolean register(String username,String password,String confirm,String email){try{DBConn regDBConn = new DBConn();String strSQL = "insert into tbl_user(id,name,pwd,email) values(" + this.newID +"," + username + "," + password + "," + email + ")";regDBConn.execute(strSQL);return true;}catch(Exception e){System.out.println(e.toString());return false;}}public static void main(String args[]){try{reg newreg = new reg();System.out.println(newreg.reg("sssssssss","ssssss","ssssss","imagebear@"));DBConn myconn = new DBConn();myconn.executeQuery("select * from tbl_user");while(myconn.rs_next()){System.out.println(myconn.rs_getInt("id") + " " + myconn.rs_getString("name") + " " + myconn.rs_getString("pwd") + " " + myconn.rs_getString("email"));}System.out.println(newreg.getID());}catch(Exception e){System.err.println(e.toString());}}};说明:1、该bean文件应和上文所述DBConn.class文件放于同一目录下2、本例主要研究注册的过程,其中的Email检测等方法并不完善,若要应用请自行设计方法四、编写用户登陆的Servlet:login.java//login.java//import required classesimport java.io.*;import javax.servlet.*;import javax.servlet.http.*;import java.sql.*;//class loginpublic class login extends HttpServlet{public void doGet(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException{String username = req.getParameter("username");String password = req.getParameter("password");if(this.checklogin(username,password)){Cookie mylogin = new Cookie("username",username);mylogin.setVersion(1);mylogin.setPath("/");mylogin.setComment("Your login username");res.addCookie(mylogin);}//Cookie[] myCookies = req.getCookies();//String nameValue = this.getCookieValue(myCookies,"username","not found"); //PrintWriter out = res.getWriter();//out.println("username" + ":" + nameValue);//out.println("Test Cookie Success!");res.sendRedirect("/index.jsp");}public void doPost(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException{doGet(req,res);}public static String getCookieValue(Cookie[] cookies,String cookieName,String defaultValue){for(int i=0;i<cookies.length;i++) {Cookie cookie = cookies[i];if (cookieName.equals(cookie.getName()))return(cookie.getValue());}return(defaultValue);}public boolean checklogin(String username,String password){try{DBConn loginConn = new DBConn();loginConn.executeQuery("select * from tbl_user where name=" + username + ""); if(loginConn.rs_next()){System.out.println("Connection created!");if(loginConn.rs_getString("pwd").trim().equals(password)){System.out.println(loginConn.rs_getString("name"));return true;}else{return false;}}System.out.println("Test Login Success!");return false;}catch(Exception e){System.out.println(e.toString());return false;}}public static void main(String args[]){login mylogin = new login();System.out.println(mylogin.checklogin("shandong","shandong"));}}说明:1、默认的jdk1.4中并没有servlet包,请至sun公司网页下载servlet.jar,放至jdk目录下的jre¥lib¥目录下,并在JCreator中设置jdk处添加servlet.jar包2、本Servlet用于检验用户名和密码,若正确则将用户名写入Cookie,完成后将当前页重定向到index.jsp页五、编写检测用户是否已经登陆的bean:checkLogin.java//checkLogin.java//import required classesimport java.io.*;import javax.servlet.*;import javax.servlet.http.*;//class checkLoginpublic class checkLogin{public String username = "";public boolean check(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException{String cookieName = "username";Cookie[] myCookies = req.getCookies();ername = this.getCookieValue(myCookies,cookieName,"not found"); PrintWriter out = res.getWriter();if(ername != null){//out.println("早上好," + ername + "!");return true;}else{out.println("登陆失败!");return false;}}public String getUserName(){return ername;}public static String getCookieValue(Cookie[] cookies,String cookieName,String defaultValue){for(int i=0;i<cookies.length;i++) {Cookie cookie = cookies[i];if (cookieName.equals(cookie.getName()))return(cookie.getValue());}return(defaultValue);}}说明:此bean检测cookie中的username,若不为空则说明已登录,反之说明没有登录。

相关主题