• Java基础12


    Java基础12

    Java基础12    1

    文件结构——(纯servlet开发网页)    1

    tomcat配置数据源    2

    ServletContext介绍    4

    开发servlet的三种方法:    5

    1.实现servlet接口(Hello.java)    5

    2. 继承GenericServlet(HelloGen.java)    6

    3. 通过继承HttpServlet(HelloHttp.java)    7

    用户管理系统model1开发    8

    用户表设计    8

    1. 登录界面(Login.java)    8

    2. 登录处理界面(LoginCl.java)    10

    3. 欢迎界面(Wel.java)    14

    servlet用户管理系统模型图    18

    Model2模式开发servlet用户管理系统    19

    WEB-INF下的配置文件(web.xml)    19

    界面层_登录界面(Login.java)    21

    界面层_验证用户(LoginCl.java)    22

    界面层_主界面(Main.java)    27

    界面层_欢迎界面(Wel.java)    29

    界面层_修改用户(Update.java)    34

    界面层_修改用户处理(UpdateCl.java)    35

    界面层_删除用户(DelUserCl.java)    37

    界面层_操作成功(Err.java)    38

    界面层_操作失败(Ok.java)    39

    model层_表示User表(UserBean.java)    41

    model层_业务逻辑(UserBeanCl.java)    42

    model层_连接数据库(ConnDB.java)    48

     

    文件结构——(纯servlet开发网页)

    tomcat配置数据源

     

    <!--将数据源的配置加入到server.xml文件中的Host树枝下-->

    <Context path="/myWebSite" docBase="D:/Workspace/servlet/myWebSite" debug="0">

    <!--name:给数据源设置名字(jndi) auth:表示该数据源是谁管理 type:类型-->

    <Resource name="luowei" auth="Container" type="javax.sql.DataSource"/>

    <ResourceParams name="shunping">

    <!--工厂设置-->

    <parameter>

    <name>factory</name>

    <value>org.apache.commons.dbcp.BasicDataSourceFactory</value>

    </parameter>

    <!--驱动设置-->

    <parameter>

    <name>driverClassName</name>

    <value>com.microsoft.jdbc.sqlserver.SQLServerDriver</value>

    </parameter>

     

    <!--设置url-->

    <parameter>

    <name>url</name>

    <value>jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=test_user</value>

    </parameter>

     

    <!--设置连接数据库的用户名-->

    <parameter>

    <name>username</name>

    <value>sa</value>

    </parameter>

     

    <!--设置连接数据库的密码-->

    <parameter>

    <name>password</name>

    <value>luowei</value>

    </parameter>

     

    <!--设置连接池中最大的激活连接数-->

    <parameter>

    <name>maxActive</name>

    <value>200</value>

    </parameter>

     

    <!--设置连接池中最大的保留(空闲)连接数-->

    <parameter>

    <name>maxIdle</name>

    <value>10</value>

    </parameter>

     

    <!--客户端在队列池中最大等待时间,按秒计算;当设置为-1时,表示一直等待-->

    <parameter>

    <name>maxIdle</name>

    <value>10</value>

    </parameter>

    </ResourceParams>

    </Context>

     

    <!--

    如果使用连接池的方式来连接数据库,那么就要这样:

    Context ctt=new javax.naming.InitalContext();

    DataSource ds=(DataSource)ctt.lookup("java:comp/env/数据源的名字");

    ct=ds.getConnection();

    -->

    ServletContext介绍

    开发servlet的三种方法:

    1.实现servlet接口(Hello.java)

    /*

    * 第一个Servlet,使用实现servlet接口的方式来开发

    *

    */

     

    package com.test1;

    import javax.servlet.*;

     

    import java.io.*;

    import javax.servlet.Servlet;

    import javax.servlet.ServletConfig;

    import javax.servlet.ServletException;

    import javax.servlet.ServletRequest;

    import javax.servlet.ServletResponse;

    import java.io.IOException;

     

    public class Hello implements Servlet {

        //该函数用于初始化该servlet(类似于类的构造函数)

        //该函数只会被调用一次(当用户第一次访问该servlet时被调用)

        public void init(ServletConfig arg0) throws ServletException {

            // TODO Auto-generated method stub

            System.out.println("init it");

        }

        

        //这个函数用于处理业务逻辑

        //程序员应当把业务逻辑代码写在这里

        //当用户每访问该servlet时,都会被调用

        //req:用于获得客户端(浏览器)的信息,res:用于向客户端(浏览器)返回信息

        public void service(ServletRequest req, ServletResponse res)

                throws ServletException, IOException {

            System.out.println("service it");//向控制台打印

            

            //从res中得到PrintWriter(向浏览器打印)

            PrintWriter pw=res.getWriter();

            pw.println("hello,world");

        }

        

        //该函数用于得到servlet配置文件

        public ServletConfig getServletConfig() {

            // TODO Auto-generated method stub

            return null;

        }

     

        public String getServletInfo() {

            // TODO Auto-generated method stub

            return null;

        }

        

        //销毁servlet实例(释放内存),以下情况该函数被调用

            //1.reload 该servlet(webApps)

            //2.关闭tomcat

            //3.关机

        public void destroy() {

            System.out.println("destroy!");

            // TODO Auto-generated method stub

            

        }

        

    }

    2. 继承GenericServlet(HelloGen.java)

    //这是第二种开发servlet的方法(继承GenericServlet开发)

     

    package com.test2;

     

    import javax.servlet.GenericServlet;

    import javax.servlet.*;

    import java.io.*;

     

    public class HelloGen extends GenericServlet

    {

        //重写service方法即可

        public void service(ServletRequest req, ServletResponse res)

        {

            //返回hello,world!generic

            try{

                PrintWriter pw=res.getWriter();

                pw.println("hello,world! generic");

            }

            catch(Exception e)

            {

                e.printStackTrace();

            }

        }

    }

    3. 通过继承HttpServlet(HelloHttp.java)

    //这是第三种开发servlet的方法(通过继承HttpServlet)

     

    package com.test3;

     

    import javax.servlet.http.*;

    import java.io.*;

     

    public class HelloHttp extends HttpServlet

    {

        //处理get请求

        //req:用于获得浏览器的信息

        //res:用于向浏览返回的信

        public void doGet(HttpServletRequest req,HttpServletResponse res)

        {

            //业务逻辑

            try{

                PrintWriter pw=res.getWriter();

                pw.println("hello,HttpServlet");

            }

            catch(Exception e)

            {

                e.printStackTrace();

            }

        }

        

        //处理post请求

        //req:用于获得浏览器的信息

        //res:用于向浏览返回的信

        public void doPost(HttpServletRequest req,HttpServletResponse res)

        {

            this.doGet(req,res);

        }

    }

    用户管理系统model1开发

    用户表设计

    --run:

    --sqlcmd -U sa -P luowei -d master

        

    create database test_user;

     

    use test_user;

     

    create table users(

    useId int primary key identity(1,1),--用户id号

    username varchar(20),

    passwd varchar(20),

    email varchar(30),

    grade int --用户的级别

    );

     

    insert into users(username,passwd,email,grade) values("admin","admin","admin@sohu.com","1");

    insert into users(username,passwd,email,grade) values("luowei","luowei","luowei@163.com","1");

    insert into users(username,passwd,email,grade) values("test1","test1","test1@sina.com","5");

    insert into users(username,passwd,email,grade) values("test2","test2","test2@sina.com","5");

     

    select * from users;

    1. 登录界面(Login.java)

    //登录界面

     

    package com.usermanage;

     

    import javax.servlet.http.*;

    import javax.servlet.*;

    import java.io.*;

     

    public class Login extends HttpServlet

    {

        //处理get请求

        //req:用于获得浏览器的信息

        //res:用于向浏览返回的信

        public void doGet(HttpServletRequest req,HttpServletResponse res)

        {

            //业务逻辑

            try{

                //解决中文乱码

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

                PrintWriter pw=res.getWriter();

                //返回登录界面

                pw.println("<html>");

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

                //得到error信息

                String info=req.getParameter("info");

                if(info!=null)

                {

                    pw.println("<h2>你的用户名或密码出错</h2>");

                }

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

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

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

                pw.println(" 密码: <input type=password name=passwd height=30 weight=220><br>");

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

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

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

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

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

                

            }

            catch(Exception e)

            {

                e.printStackTrace();

            }

        }

        

        //处理post请求

        //req:用于获得浏览器的信息(向浏览器请求信息)

        //res:用于向浏览器返回的信息(向浏览器发送信息)

        public void doPost(HttpServletRequest req,HttpServletResponse res)

        {

            this.doGet(req,res);

            

        }

    }

    2. 登录处理界面(LoginCl.java)

    //用户验证

    /**

    *同一用户的不同页面共享数据(四种方式):

    *    1.通过sendRedirect("welcome?uname=name&passwd=password),

            其中welcome表示要跳转到的页面,uname,passwd表示要传递的参数,

            当有多个参数时要用 & 符号隔开,name和password表示参数的值

        2.利用隐藏表单

            <form action=login>

            <input type=hidden name=a value=b>

            </form>

        3.通过服务器端为浏览器分配的Session空间

            1.得到session

                HttpSession hs=request.getSession(true);

            2.向session添加属性

                hs.setAttribute(String name,Object val);

            3.从session得到某个属性

                String name=hs.getAttribute(String name);

            4.从session删除某个属性

                hs.removeAttribute(String name);

        4.利用cookie

            1.在服务器端创建:Cookie c=new Cookie(String name,String val);

            2.添加到客户端:response.addCookie(c)

            3.从客户端读到服务器:requestCookies();

    */

    package com.usermanage;

     

    import javax.servlet.http.*;

    import javax.servlet.*;

    import java.io.*;

    import java.sql.*;

     

    public class LoginCl extends HttpServlet

    {

        //处理get请求

        //req:用于获得浏览器的信息

        //res:用于向浏览返回的信

        public void doGet(HttpServletRequest req,HttpServletResponse res)

        {

            Connection ct=null;

            Statement sm=null;

            ResultSet rs=null;

            //业务逻辑

            try

            {

                //接收用户用户名和密码

                String u=req.getParameter("username");

                String p=req.getParameter("passwd");

                //PrintWriter pw=res.getWriter();

                System.out.println("username="+u+" passwd="+p);

                

                //连接数据库

                // Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");

                Class.forName("org.gjt.mm.mysql.Driver").newInstance();

                

                // 得到连接

                // ct=DriverManager.getConnection(

                    // "jdbc:microsoft:sqlserver://127.0.0.1:1433;databaseName=test_user",

                    // "sa","luowei");

                ct=DriverManager.getConnection("jdbc:mysql://localhost:3306/test_user",

                    "root","root");    

                

                // 创建Statement

                sm=ct.createStatement();

                // rs=sm.executeQuery("select top 1 * from users where username='"

                // +u+"' and passwd='"+p+"'");

                rs=sm.executeQuery("select username,passwd from users where username='"

                +u+"' and passwd='"+p+"'");

                

                //验证

                if(rs.next())

                {

                    //说明用户是存在的(合法)

                    String dbPasswd=rs.getString(2);

                    if(dbPasswd.equals(p)) //这样可以消除注入漏洞

                    {

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

                        System.out.println("keep="+keep);

                        if(keep!=null)//是否选中了checkbox

                        {

                            //将用户名和密码保存在客户端

                            //创建cookie

                            Cookie name=new Cookie("myname",u);

                            Cookie pass=new Cookie("mypasswd",p);

                            //设置时间

                            name.setMaxAge(14*24*3600);

                            pass.setMaxAge(14*24*3600);

                            //回写到客户端

                            res.addCookie(name);

                            res.addCookie(pass);

                        }

                        //将验证成功的信息,写入session

                        //得到session

                        HttpSession hs=req.getSession(true);

                        

                        //修改session的存在时间(这里改成20秒)

                        hs.setMaxInactiveInterval(20);

                        

                        //向session添加属性

                        hs.setAttribute("pass","ok");

                        

                        //将用户名传到welcome页面(可以在浏览器中看到值)

                        res.sendRedirect("welcome?uname="+u+"&passwd="+p);

                    }

                }

                else

                {

                    //不合法

                    //跳转

                    res.sendRedirect("login?info=error1");//写要跳转到的servlet的url

                }

            }

            catch(Exception e)

            {

                e.printStackTrace();

            }

            finally

            {

                try

                {

                    if(null!=rs) rs.close();

                    if(null!=sm) sm.close();

                    if(null!=ct) ct.close();

                }catch(Exception e)

                {

                    e.printStackTrace();

                }

            }

    /*             //验证

                if(p.equals("123"))

                {

                    //合法

                    //将验证成功的信息,写入session

                    //得到session

                    HttpSession hs=req.getSession(true);

                    

                    //修改session的存在时间(这里改成40秒)

                    hs.setMaxInactiveInterval(40);

                    

                    //向session添加属性

                    hs.setAttribute("pass","ok");

                    

                    //将用户名传到welcome页面(可以在浏览器中看到值)

                    res.sendRedirect("welcome?uname="+u+"&passwd="+p);

                }

                else

                {

                    //不合法

                    //跳转

                    res.sendRedirect("login?info=error1");//写要跳转到的servlet的url

                }

            }

            catch(Exception e)

            {

                e.printStackTrace();

            } */

        }

        

        //处理post请求

        //req:用于获得浏览器的信息

        //res:用于向浏览返回的信

        public void doPost(HttpServletRequest req,HttpServletResponse res)

        {

            this.doGet(req,res);

            

        }

    }

    3. 欢迎界面(Wel.java)

    //欢迎界面

     

    package com.usermanage;

     

    import javax.servlet.http.*;

    import javax.servlet.*;

    import java.sql.*;

    import java.io.*;

     

    public class Wel extends HttpServlet

    {

        //处理get请求

        //req:用于获得浏览器的信息

        //res:用于向浏览返回的信

        public void doGet(HttpServletRequest req,HttpServletResponse res)

        {

            Connection ct=null;

            PreparedStatement ps=null;

            ResultSet rs=null;

            //业务逻辑

            try{

                //得到session

                HttpSession hs=req.getSession(true);

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

                

                

                if(val==null)//判断

                {

                    //如果客户端session中没有用户信息,再看有没有cookie信息

                    //客户端得到所有cookie信息

                    Cookie [] allCookies=req.getCookies();

                    int i=0;

                    String name="";

                    String passwd="";

                    //如果allCookies不为空

                    if(allCookies!=null)

                    {

                        //从中取出cookie

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

                        {

                            //依次取出

                            Cookie temp=allCookies[i];

                            if(temp.getName().equals("myname"))

                            {

                                name=temp.getValue();//得到cookie的值

                            }

                            else if(temp.getName().equals("mypasswd"))

                            {

                                passwd=temp.getValue();//得到cookie的值

                                System.out.println("passwd="+passwd);

                            }

                        }

                        //System.out.println("myname="+name+" passwd="+passwd);

                        if(!name.equals("")&&!passwd.equals(""))

                        {

                            //到logincl去验证

                            res.sendRedirect("loginCl?username="+name+"&passwd="+passwd);

                            System.out.println("myname="+name+" passwd="+passwd);

                            return;

                        }

                    }

                    

                    //非法登录,跳转到登录界面并提示出错

                    res.sendRedirect("login?info=error1");

                    return;

                }

                

                //解决中文乱码

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

                PrintWriter pw=res.getWriter();

                

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

                

                //=====================分页的功能=============================

                int pageSize=5;        //一页显示几条记录

                int pageNow=1;        //希望显示第几页

                int rowCount=0;        //共有几条记录(查表)

                int pageCount=0;    //一共有几页(计算)

                

                //动态接收pageNow

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

                if(sPageNow!=null)

                {

                    //用户不是第一次进入welcome页面

                    pageNow=Integer.parseInt(sPageNow);

                }

                

                //得到rowCount

                //加载驱动

                Class.forName("org.gjt.mm.mysql.Driver").newInstance();

                

                // 得到连接

                ct=DriverManager.getConnection("jdbc:mysql://localhost:3306/test_user",

                    "root","root");    

                

                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 "+pageSize*(pageNow-1)

                    +","+pageSize);

                //给?赋值

                //ps.setInt(1,pageSize*(pageNow-1));

                //ps.setInt(2,pageSize);

                

                rs=ps.executeQuery();

                //表头

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

                pw.println("<tr><th>id</th><th>name</th><th>passwd</th>"

                    +"<th>email</th><th>grade</th><tr>");

                while(rs.next())

                {

                    pw.println("<tr>");

                    pw.println("<td>"+rs.getInt(1)+"</td>");

                    pw.println("<td>"+rs.getString(2)+"</td>");

                    pw.println("<td>"+rs.getString(3)+"</td>");

                    pw.println("<td>"+rs.getString(4)+"</td>");

                    pw.println("<td>"+rs.getInt(5)+"</td>");

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

                }

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

                if(1!=pageNow)//上一页

                {

                    pw.println("<a href=welcome?pageNow="+(pageNow-1)+">上一页</a>");

                }

                //显示超链接(页面)

                for(int i=pageNow;i<=pageNow+pageSize&&i<=pageCount;i++)

                {

                    pw.println("<a href=welcome?pageNow="+i+">"+i+"</a>");

                }

                if(pageCount!=pageNow)//下一页

                {

                    pw.println("<a href=welcome?pageNow="+(pageNow+1)+">下一页</a>");

                }

     

                pw.println("<br><br>");

                pw.println("<a href=welcome?pageNow="+1+">第一页</a> ");

                pw.println("<a href=welcome?pageNow="+(pageCount-pageSize)+">最后页</a>");

                pw.println("<br>");

                //得到从loginCl传递的 用户名

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

                //得到从loginCl传递的 密码

                String p=req.getParameter("passwd");

     

                //在servlet中显示图片

                pw.println("<img src=imgs/1.gif><br>");

                pw.println("welcome,hello!"+u+" password="+p+"<br>");

                pw.println("<a href=login>返回重新登录</a>");

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

            }

            catch(Exception e)

            {

                e.printStackTrace();

            }

        }

        

        //处理post请求

        //req:用于获得浏览器的信息

        //res:用于向浏览返回的信

        public void doPost(HttpServletRequest req,HttpServletResponse res)

        {

            this.doGet(req,res);

            

        }

    }

    servlet用户管理系统模型图

    Model2模式开发servlet用户管理系统

    WEB-INF下的配置文件(web.xml)

    <?xml version="1.0" encoding="gb2312"?>

     

    <web-app xmlns="http://java.sun.com/xml/ns/javaee"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

    version="2.5">

     

    <display-name>Welcome to myWebSite</display-name>

    <description>

    Welcome to myWebSite

    </description>

     

    <!-- JSPC servlet mappings start -->

     

    <servlet>

    <servlet-name>Hello</servlet-name>

    <servlet-class>com.test1.Hello</servlet-class>

    </servlet>

    <servlet-mapping>

    <servlet-name>Hello</servlet-name>

    <url-pattern>/servlet/Hello</url-pattern>

    </servlet-mapping>

     

    <servlet>

    <servlet-name>hellogen</servlet-name>

    <servlet-class>com.test2.HelloGen</servlet-class>

    </servlet>

    <servlet-mapping>

    <servlet-name>hellogen</servlet-name>

    <url-pattern>/hellogen</url-pattern>

    </servlet-mapping>

     

    <servlet>

    <servlet-name>hellohttp</servlet-name>

    <servlet-class>com.test3.HelloHttp</servlet-class>

    </servlet>

    <servlet-mapping>

    <servlet-name>hellohttp</servlet-name>

    <url-pattern>/hellohttp</url-pattern>

    </servlet-mapping>

     

    <servlet>

    <servlet-name>login</servlet-name>

    <servlet-class>com.user_mng.Login</servlet-class>

    </servlet>

    <servlet-mapping>

    <servlet-name>login</servlet-name>

    <url-pattern>/login</url-pattern>

    </servlet-mapping>

     

    <servlet>

    <servlet-name>loginCl</servlet-name>

    <servlet-class>com.user_mng.LoginCl</servlet-class>

    </servlet>

    <servlet-mapping>

    <servlet-name>loginCl</servlet-name>

    <url-pattern>/loginCl</url-pattern>

    </servlet-mapping>

     

    <servlet>

    <servlet-name>main</servlet-name>

    <servlet-class>com.user_mng.Main</servlet-class>

    </servlet>

    <servlet-mapping>

    <servlet-name>main</servlet-name>

    <url-pattern>/main</url-pattern>

    </servlet-mapping>

     

    <servlet>

    <servlet-name>wel</servlet-name>

    <servlet-class>com.user_mng.Wel</servlet-class>

    </servlet>

    <servlet-mapping>

    <servlet-name>wel</servlet-name>

    <url-pattern>/welcome</url-pattern>

    </servlet-mapping>

     

    <servlet>

    <servlet-name>delUserCl</servlet-name>

    <servlet-class>com.user_mng.DelUserCl</servlet-class>

    </servlet>

    <servlet-mapping>

    <servlet-name>delUserCl</servlet-name>

    <url-pattern>/delUserCl</url-pattern>

    </servlet-mapping>

     

    <servlet>

    <servlet-name>ok</servlet-name>

    <servlet-class>com.user_mng.Ok</servlet-class>

    </servlet>

    <servlet-mapping>

    <servlet-name>ok</servlet-name>

    <url-pattern>/ok</url-pattern>

    </servlet-mapping>

     

    <servlet>

    <servlet-name>err</servlet-name>

    <servlet-class>com.user_mng.Err</servlet-class>

    </servlet>

    <servlet-mapping>

    <servlet-name>err</servlet-name>

    <url-pattern>/err</url-pattern>

    </servlet-mapping>

     

    <servlet>

    <servlet-name>update</servlet-name>

    <servlet-class>com.user_mng.Update</servlet-class>

    </servlet>

    <servlet-mapping>

    <servlet-name>update</servlet-name>

    <url-pattern>/update</url-pattern>

    </servlet-mapping>

     

    <servlet>

    <servlet-name>updateCl</servlet-name>

    <servlet-class>com.user_mng.UpdateCl</servlet-class>

    </servlet>

    <servlet-mapping>

    <servlet-name>updateCl</servlet-name>

    <url-pattern>/updateCl</url-pattern>

    </servlet-mapping>

    <!-- JSPC servlet mappings end -->

    </web-app>

    界面层_登录界面(Login.java)

    //登录界面

     

    package com.user_mng;

     

    import javax.servlet.http.*;

    import javax.servlet.*;

    import java.io.*;

     

    public class Login extends HttpServlet

    {

        //处理get请求

        //req:用于获得浏览器的信息

        //res:用于向浏览返回的信

        public void doGet(HttpServletRequest req,HttpServletResponse res)

        {

            //业务逻辑

            try{

                //解决中文乱码

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

                PrintWriter pw=res.getWriter();

                //返回登录界面

                pw.println("<html>");

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

                pw.println("<center>");

                pw.println("<img src=imgs/1.gif>");

                pw.println("<hr>");

                //得到error信息

                String info=req.getParameter("info");

                if(info!=null)

                {

                    pw.println("<h2>你的用户名或密码出错</h2>");

                }

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

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

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

                pw.println(" 密码: <input type=password name=passwd height=30 width=160><br>");

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

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

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

                pw.println("</center><hr>");

                pw.println("<img src=imgs/logo.gif>");

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

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

                

            }

            catch(Exception e)

            {

                e.printStackTrace();

            }

        }

        

        //处理post请求

        //req:用于获得浏览器的信息(向浏览器请求信息)

        //res:用于向浏览器返回的信息(向浏览器发送信息)

        public void doPost(HttpServletRequest req,HttpServletResponse res)

        {

            this.doGet(req,res);

            

        }

    }

    界面层_验证用户(LoginCl.java)

    //用户验证

    /**

    *同一用户的不同页面共享数据(四种方式):

    *    1.通过sendRedirect("welcome?uname=name&passwd=password),

            其中welcome表示要跳转到的页面,uname,passwd表示要传递的参数,

            当有多个参数时要用 & 符号隔开,name和password表示参数的值

        2.利用隐藏表单

            <form action=login>

            <input type=hidden name=a value=b>

            </form>

        3.通过服务器端为浏览器分配的Session空间

            1.得到session

                HttpSession hs=request.getSession(true);

            2.向session添加属性

                hs.setAttribute(String name,Object val);

            3.从session得到某个属性

                String name=hs.getAttribute(String name);

            4.从session删除某个属性

                hs.removeAttribute(String name);

        4.利用cookie

            1.在服务器端创建:Cookie c=new Cookie(String name,String val);

            2.添加到客户端:response.addCookie(c)

            3.从客户端读到服务器:requestCookies();

    */

    /*

    *多个用户共享同一数据:

        1.利用ServletContext,它是在服务器端分配供多个用户共享的数据区域

        2.得到ServletContext实例:this.getServletContext();

        3.可以把它想像成一张表,和session非常相似,每一行是一个属性:

            1.添加属性:setAttribute(String name,Object ob)

            2.得到值:getAttribute(String name) 返回Object

            3.删除属性:removeAttribute(String name)

        4.生命周期:从创建开始,到服务器关闭而结束

    */

    package com.user_mng;

     

    import javax.servlet.http.*;

    import javax.servlet.*;

    import java.io.*;

    import java.sql.*;

     

    public class LoginCl extends HttpServlet

    {

        //添加网页访问次数的功能

        //重写init函数(init函数会在访问这个servlet文件时,会被调用一次)

        public void init()

        {

            try{

                //这个函数只会被调用一次

                //从文件中读取次数

                FileReader fr=new FileReader("f:/myCounter.txt");

                BufferedReader br=new BufferedReader(fr);

                //读出一行数据

                String numVal=br.readLine();

                //关闭文件流

                br.close();

     

                //将numVal值放入到servletContext

                this.getServletContext().setAttribute("visitTime",numVal+"");

                System.out.println("init被调用");

            }catch(Exception e){

                e.printStackTrace();

            }

        }

        

        //重写destroy函数(destroy函数在服务器被关闭时,会自动调用)

        public void destroy()

        {

            try{

                //再将新的次数写回文件

                FileWriter fw=new FileWriter("f:/myCounter.txt");

                BufferedWriter bw=new BufferedWriter(fw);

                //写入一行数据

                bw.write(this.getServletContext().getAttribute("visitTime").toString());

                //关闭文件流

                bw.close();

                System.out.println("destroy函数被调用");

            }catch(Exception e){

                e.printStackTrace();

            }

        }

        

        //处理get请求

        //req:用于获得浏览器的信息

        //res:用于向浏览返回的信

        public void doGet(HttpServletRequest req,HttpServletResponse res)

        {

            // Connection ct=null;

            // Statement sm=null;

            // ResultSet rs=null;

     

            //业务逻辑

            try

            {

                //接收用户用户名和密码

                String u=req.getParameter("username");

                String p=req.getParameter("passwd");

                //PrintWriter pw=res.getWriter();

                System.out.println("username="+u+" passwd="+p);

                

                //调用UserBeanCl,创建一个UserBeanCl对象

                UserBeanCl ubc=new UserBeanCl();

                

                //验证,使用UserBeanCl的方法

                if(ubc.checkUser(u,p))

                {

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

                    System.out.println("keep="+keep);

                    if(keep!=null)//是否选中了checkbox

                    {

                        //将用户名和密码保存在客户端

                        //创建cookie

                        Cookie name=new Cookie("myname",u);

                        Cookie pass=new Cookie("mypasswd",p);

                        //设置时间

                        name.setMaxAge(14*24*3600);

                        pass.setMaxAge(14*24*3600);

                        //回写到客户端

                        res.addCookie(name);

                        res.addCookie(pass);

                    }

                    //将验证成功的信息,写入session

                    //得到session

                    HttpSession hs=req.getSession(true);

                    

                    //修改session的存在时间(这里改成20秒)

                    hs.setMaxInactiveInterval(20);

                    

                    //向session添加属性

                    hs.setAttribute("pass","ok");

                    hs.setAttribute("uname",u);

                    hs.setAttribute("passwd",p);

                    

                    //将servletContext中的visitTime中的值++

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

                    //对times++再重新放回servlet

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

                    

                    //将用户名传到welcome页面(可以在浏览器中看到

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

                    res.sendRedirect("main");

                }

                else

                {

                    //不合法

                    //跳转

                    res.sendRedirect("login?info=error1");//写要跳转到的servlet的url

                }

            }

            catch(Exception e)

            {

                e.printStackTrace();

            }

            

    /*             //验证

                if(p.equals("123"))

                {

                    //合法

                    //将验证成功的信息,写入session

                    //得到session

                    HttpSession hs=req.getSession(true);

                    

                    //修改session的存在时间(这里改成40秒)

                    hs.setMaxInactiveInterval(40);

                    

                    //向session添加属性

                    hs.setAttribute("pass","ok");

                    

                    //将用户名传到welcome页面(可以在浏览器中看到值)

                    res.sendRedirect("welcome?uname="+u+"&passwd="+p);

                }

                else

                {

                    //不合法

                    //跳转

                    res.sendRedirect("login?info=error1");//写要跳转到的servlet的url

                }

            }

            catch(Exception e)

            {

                e.printStackTrace();

            } */

        }

        

        //处理post请求

        //req:用于获得浏览器的信息

        //res:用于向浏览返回的信

        public void doPost(HttpServletRequest req,HttpServletResponse res)

        {

            this.doGet(req,res);

            

        }

    }

    界面层_主界面(Main.java)

    //主界面//登录界面

     

    package com.user_mng;

     

    import javax.servlet.http.*;

    import javax.servlet.*;

    import java.io.*;

     

    public class Main extends HttpServlet

    {

        //处理get请求

        //req:用于获得浏览器的信息

        //res:用于向浏览返回的信

        public void doGet(HttpServletRequest req,HttpServletResponse res)

        {

            //业务逻辑

            try{

                //解决中文乱码

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

                PrintWriter pw=res.getWriter();

                

                //返回登录界面

                pw.println("<html>");

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

                pw.println("<center>");

                pw.println("<img src=imgs/1.gif>");

                pw.println("<hr>");

                

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

                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>");

                pw.println("<img src=imgs/logo.gif>");

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

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

                

            }

            catch(Exception e)

            {

                e.printStackTrace();

            }

        }

        

        //处理post请求

        //req:用于获得浏览器的信息(向浏览器请求信息)

        //res:用于向浏览器返回的信息(向浏览器发送信息)

        public void doPost(HttpServletRequest req,HttpServletResponse res)

        {

            this.doGet(req,res);

            

        }

    }

    界面层_欢迎界面(Wel.java)

    //欢迎界面

     

    package com.user_mng;

     

    import javax.servlet.http.*;

    import javax.servlet.*;

    import java.util.*;

    import java.sql.*;

    import java.io.*;

     

    public class Wel extends HttpServlet

    {

        //处理get请求

        //req:用于获得浏览器的信息

        //res:用于向浏览返回的信

        public void doGet(HttpServletRequest req,HttpServletResponse res)

        {

            Connection ct=null;

            PreparedStatement ps=null;

            ResultSet rs=null;

            //业务逻辑

            try{

                //得到session

                HttpSession hs=req.getSession(true);

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

                //从Session中得到用户名和密码

                String u=(String)hs.getAttribute("uname");

                String p=(String)hs.getAttribute("passwd");

                

                if(val==null)//判断

                {

                    //如果客户端session中没有用户信息,再看有没有cookie信息

                    //客户端得到所有cookie信息

                    Cookie [] allCookies=req.getCookies();

                    int i=0;

                    String name="";

                    String passwd="";

                    //如果allCookies不为空

                    if(allCookies!=null)

                    {

                        //从中取出cookie

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

                        {

                            //依次取出

                            Cookie temp=allCookies[i];

                            if(temp.getName().equals("myname"))

                            {

                                name=temp.getValue();//得到cookie的值

                            }

                            else if(temp.getName().equals("mypasswd"))

                            {

                                passwd=temp.getValue();//得到cookie的值

                                System.out.println("passwd="+passwd);

                            }

                        }

                        //System.out.println("myname="+name+" passwd="+passwd);

                        if(!name.equals("")&&!passwd.equals(""))

                        {

                            //到logincl去验证

                            res.sendRedirect("loginCl?username="+name+"&passwd="+passwd);

                            System.out.println("myname="+name+" passwd="+passwd);

                            return;

                        }

                    }

                    

                    //非法登录,跳转到登录界面并提示出错

                    res.sendRedirect("login?info=error1");

                    return;

                }

                

                //解决中文乱码

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

                PrintWriter pw=res.getWriter();

                

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

                pw.println("<center>");

                pw.println("<img src=imgs/1.gif>");

                pw.println("&nbsp;&nbsp;&nbsp;&nbsp;欢迎您:"+u+"<img src=imgs/luowei.gif>");

                pw.println("<hr>");

                

                

                //=====================分页的功能=============================

                int pageSize=5;        //一页显示几条记录

                int pageNow=1;        //希望显示第几页

                //int jumpPage=0;    //跳转的页面

                

                //动态接收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("<h1>管理用户</h1><br>");

                //表头

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

                pw.println("<tr bgcolor=pink><th>用户id</th><th>用户名</th><th>密码</th>"

                    +"<th>邮箱</th><th>级别</th><th>修改用户</th><th>删除用户</th><tr>");

                

                //定义一个颜色数组

                String [] mycol={"silver","pink"};

                

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

                {

                    //取出UserBean

                    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()+

                        "&uPass="+ub.getPasswd()+"&uEmail="+ub.getMail()+"&uGrade="+ub.getGrade()+">修改用户</a></td>");

                    pw.println("<td><a href=delUserCl?userid="+ub.getUserId()+

                        " onClick=\"return window.confirm('您确认要删除该用户吗?')\">删除用户</a></td>");

                    //弹出删除确认对话框,其中\"是转义符

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

                }

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

                

                //接收jumpPae

                //jumpPage=Integer.parseInt(req.getParameter("jumpPage"));

                //pageNow=jumpPage;

                

                int pageCount=ubc.getPageCount();

                if(1!=pageNow)//上一页

                {

                    pw.println("<a href=welcome?pageNow="+(pageNow-1)+">上一页</a>");

                }

                //显示超链接(页面)

                for(int i=pageNow;i<=pageNow+pageSize&&i<=pageCount;i++)

                {

                    pw.println("<a href=welcome?pageNow="+i+">"+i+"</a>");

                }

                if(pageCount!=pageNow)//下一页

                {

                    pw.println("<a href=welcome?pageNow="+(pageNow+1)+">下一页</a>");

                }

                pw.println("<br>");

                

                //指定跳转到某页

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

                pw.println("跳转到:<input type=text name=pageNow height=30 width=50>");

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

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

                pw.println("<br>");

                pw.println("<a href=welcome?pageNow="+1+">第一页</a> ");

                pw.println("<a href=welcome?pageNow="+(pageCount-pageSize)+">最后页</a>");

                pw.println("<br>");

                

    /*             //得到从loginCl传递的 用户名

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

                //得到从loginCl传递的 密码

                String p=req.getParameter("passwd");

    */

     

                pw.println("welcome,hello! "+u+" Your password:"+p+"<br>");

                pw.println("<a href=login>返回重新登录</a>");

                pw.println("<br>该网页被访问了"+Integer.parseInt(this.getServletContext().

                    getAttribute("visitTime").toString())+"次<br>");

                pw.println("您的ip="+req.getRemoteAddr()+"<br>");

                pw.println("您的主机名为:"+req.getRemoteHost()+"<br>");

                pw.println("</center><hr>");

                pw.println("<img src=imgs/logo.gif>");

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

            }

            catch(Exception e)

            {

                e.printStackTrace();

            }finally{

                try

                {

                    if(null!=rs) {rs.close();rs=null;}

                    if(null!=ps) {ps.close();ps=null;}

                    if(null!=ct) {ct.close();ct=null;}

                }catch(Exception e)

                {

                    e.printStackTrace();

                }

            }

        }

        

        //处理post请求

        //req:用于获得浏览器的信息

        //res:用于向浏览返回的信

        public void doPost(HttpServletRequest req,HttpServletResponse res)

        {

            this.doGet(req,res);

            

        }

    }

    界面层_修改用户(Update.java)

    //修改用户界面

     

    package com.user_mng;

     

    import javax.servlet.http.*;

    import javax.servlet.*;

    import java.io.*;

     

    public class Update extends HttpServlet

    {

        //处理get请求

        //req:用于获得浏览器的信息

        //res:用于向浏览返回的信

        public void doGet(HttpServletRequest req,HttpServletResponse res)

        {

            //业务逻辑

            try{

                //解决中文乱码

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

                PrintWriter pw=res.getWriter();

                //返回登录界面

                pw.println("<html>");

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

                pw.println("<center>");

                pw.println("<img src=imgs/1.gif>");

                pw.println("<hr>");

                

                pw.println("<h1>修改用户信息</h1>");

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

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

                pw.println("<tr><td>用户id</td><td><input readonly name=uId type=text value="

                    +req.getParameter("uId")+"></td></tr>");

                pw.println("<tr><td>用户名</td><td><input readonly name=uName type=text value="

                    +req.getParameter("uName")+"></td></tr>");

                pw.println("<tr><td>密码</td><td><input name=uPass type=text value="

                    +req.getParameter("uPass")+"></td></tr>");

                pw.println("<tr><td>邮箱</td><td><input name=uEmail type=text value="

                    +req.getParameter("uEmail")+"></td></tr>");

                pw.println("<tr><td>级别</td><td><input name=uGrade type=text value="

                    +req.getParameter("uGrade")+"></td></tr>");

                //提交按钮

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

                    " onClick=\"return window.confirm('您确认要修改该用户吗?')\"></td></tr>");

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

                

                pw.println("</center><hr>");

                pw.println("<img src=imgs/logo.gif>");

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

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

                

            }

            catch(Exception e)

            {

                e.printStackTrace();

            }

        }

        

        //处理post请求

        //req:用于获得浏览器的信息(向浏览器请求信息)

        //res:用于向浏览器返回的信息(向浏览器发送信息)

        public void doPost(HttpServletRequest req,HttpServletResponse res)

        {

            this.doGet(req,res);

            

        }

    }

    界面层_修改用户处理(UpdateCl.java)

    //处理修改某个用户界面

     

    package com.user_mng;

     

    import javax.servlet.http.*;

    import javax.servlet.*;

    import java.io.*;

     

    public class UpdateCl extends HttpServlet

    {

        //处理get请求

        //req:用于获得浏览器的信息

        //res:用于向浏览返回的信

        public void doGet(HttpServletRequest req,HttpServletResponse res)

        {

            //业务逻辑

            try{

                //解决中文乱码

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

                PrintWriter pw=res.getWriter();

                

                //调用userBeanCl的删除用户的方法,完成删除任务

                UserBeanCl ubc=new UserBeanCl();

                //接收从Update.java中传递的值

                String id=req.getParameter("uId");

                String uPass=req.getParameter("uPass");

                String uEmail=req.getParameter("uEmail");

                String uGrade=req.getParameter("uGrade");

                

                if(ubc.updateUser(id,uPass,uEmail,uGrade))

                {

                    //删除成功

                    res.sendRedirect("ok");

                }else

                {

                    //删除失败

                    res.sendRedirect("err");

                }

            }

            catch(Exception e)

            {

                e.printStackTrace();

            }

        }

        

        //处理post请求

        //req:用于获得浏览器的信息(向浏览器请求信息)

        //res:用于向浏览器返回的信息(向浏览器发送信息)

        public void doPost(HttpServletRequest req,HttpServletResponse res)

        {

            this.doGet(req,res);

            

        }

    }

    界面层_删除用户(DelUserCl.java)

    //处理删除某个用户界面

     

    package com.user_mng;

     

    import javax.servlet.http.*;

    import javax.servlet.*;

    import java.io.*;

     

    public class DelUserCl extends HttpServlet

    {

        //处理get请求

        //req:用于获得浏览器的信息

        //res:用于向浏览返回的信

        public void doGet(HttpServletRequest req,HttpServletResponse res)

        {

            //业务逻辑

            try{

                //解决中文乱码

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

                PrintWriter pw=res.getWriter();

                

                //调用userBeanCl的删除用户的方法,完成删除任务

                UserBeanCl ubc=new UserBeanCl();

                //接收从Wel.java中传递的id

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

                if(ubc.delUser(id))

                {

                    //删除成功

                    res.sendRedirect("ok");

                }else

                {

                    //删除失败

                    res.sendRedirect("err");

                }

            }

            catch(Exception e)

            {

                e.printStackTrace();

            }

        }

        

        //处理post请求

        //req:用于获得浏览器的信息(向浏览器请求信息)

        //res:用于向浏览器返回的信息(向浏览器发送信息)

        public void doPost(HttpServletRequest req,HttpServletResponse res)

        {

            this.doGet(req,res);

            

        }

    }

    界面层_操作成功(Err.java)

    //操作成功界面

     

    package com.user_mng;

     

    import javax.servlet.http.*;

    import javax.servlet.*;

    import java.io.*;

     

    public class Ok extends HttpServlet

    {

        //处理get请求

        //req:用于获得浏览器的信息

        //res:用于向浏览返回的信

        public void doGet(HttpServletRequest req,HttpServletResponse res)

        {

            //业务逻辑

            try{

                //解决中文乱码

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

                PrintWriter pw=res.getWriter();

                //返回登录界面

                pw.println("<html>");

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

                pw.println("<center>");

                pw.println("<img src=imgs/1.gif>");

                pw.println("<hr>");

                pw.println("<h1>恭喜你,操作成功!</h1>");

                pw.println("<a href=main>返回主界面</a>&nbsp;"

                    +"&nbsp;&nbsp<a href=welcome>返回上一页面</a>");

                pw.println("</center><hr>");

                pw.println("<img src=imgs/logo.gif>");

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

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

                

            }

            catch(Exception e)

            {

                e.printStackTrace();

            }

        }

        

        //处理post请求

        //req:用于获得浏览器的信息(向浏览器请求信息)

        //res:用于向浏览器返回的信息(向浏览器发送信息)

        public void doPost(HttpServletRequest req,HttpServletResponse res)

        {

            this.doGet(req,res);

            

        }

    }

    界面层_操作失败(Ok.java)

    //操作失败界面

     

    package com.user_mng;

     

    import javax.servlet.http.*;

    import javax.servlet.*;

    import java.io.*;

     

    public class Err extends HttpServlet

    {

        //处理get请求

        //req:用于获得浏览器的信息

        //res:用于向浏览返回的信

        public void doGet(HttpServletRequest req,HttpServletResponse res)

        {

            //业务逻辑

            try{

                //解决中文乱码

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

                PrintWriter pw=res.getWriter();

                //返回登录界面

                pw.println("<html>");

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

                pw.println("<center>");

                pw.println("<img src=imgs/1.gif>");

                pw.println("<hr>");

                pw.println("<h1>很遗憾,操作不成功!</h1>");

                pw.println("<a href=main>返回主界面</a>&nbsp;"

                    +"&nbsp;&nbsp<a href=welcome>返回上一页面</a>");

                pw.println("</center><hr>");

                pw.println("<img src=imgs/logo.gif>");

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

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

                

            }

            catch(Exception e)

            {

                e.printStackTrace();

            }

        }

        

        //处理post请求

        //req:用于获得浏览器的信息(向浏览器请求信息)

        //res:用于向浏览器返回的信息(向浏览器发送信息)

        public void doPost(HttpServletRequest req,HttpServletResponse res)

        {

            this.doGet(req,res);

            

        }

    }

    model层_表示User表(UserBean.java)

    //这是一个UserBean <-----> users表映射

    //他的一个 对象 <-----> users表的一条记录对应

    //数据

    package com.user_mng;

     

    public class UserBean{

        private int userId;

        private String userName;

        private String passwd;

        private String mail;

        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 mail)

        {

            this.mail=mail;

        }

        public String getMail()

        {

            return this.mail;

        }

        

        public void setGrade(int grade)

        {

            this.grade=grade;

        }

        public int getGrade()

        {

            return this.grade;

        }

    }

    model层_业务逻辑(UserBeanCl.java)

    //这是一个处理类(处理users表) <----->操作UserBean

    //业务逻辑

     

    package com.user_mng;

     

    import java.sql.*;

    import java.util.*;

     

    public class UserBeanCl

    {

        //业务逻辑

        private Connection ct=null;

        private PreparedStatement ps=null;

        private ResultSet rs=null;

        

        private int rowCount=0;        //共有几条记录(查表)

        private int pageCount=0;    //一共有几页(计算)

     

        

        //public static UserBean ub=new UserBean();

    /*     public UserBeanCl(UserBean ub)

        {

            this.ub=ub;

        } */

          

        

        //验证用户

        public boolean checkUser(String u,String p)

        {

            boolean b=false;

            try{

                //得到连接

                ConnDB cd=new ConnDB();

                ct=cd.getConn();

                

                // ps=ct.prepareStatement("select userName,passwd from users where userName='"

                    // +ub.getUserName()+"' limit 1");

                ps=ct.prepareStatement("select userName,passwd from users where userName=? limit 1");

                ps.setString(1,u);

                rs=ps.executeQuery();

                

                if(rs.next())

                {

                    String dbPasswd=rs.getString(2);

                    if(dbPasswd.equals(p))

                    {

                        b=true;

                    }

                }

            }catch(Exception e){

                e.printStackTrace();

            }finally{

                this.close();

            }

            return b;

        }

        

        /*1.如果返回ResultSet,那么在使用ResultSet时是不能关闭与该ResultSet

         *    相互关联的数据库连接等资源,从而造成资源浪费。

         *2.如果返回ResultSet,只能使用rs.getInt(?),rs.getString(?)...这样的

         *    方法来得到结果,代码的可读性不好,维护不方便。

         *3.利用集合:比如ArrayList作为中转,这样,我们就可以尽快的关闭rs,数据库连接

         *    同时更能体现面向对象编程,代码可读性好。

                1.将rs中的每条记录,封装成一个UserBean对象ub;

                2.将封装后的UserBean对象ub放入到ArrayList集合中,利于管理。

        */

        //-----------------------------

        //分页显示结果

        public ArrayList getResultByPage(int pageNow,int pageSize)

        {

            ArrayList al=new ArrayList();

            try

            {

                //得到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 "+pageSize*(pageNow-1)

                    +","+pageSize);

                //给?赋值

                //ps.setInt(1,pageSize*(pageNow-1));

                //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.setMail(rs.getString(4));

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

                    

                    al.add(ub);//将ub放入到ArrayList集合中

                    

                }

            }catch(Exception e)

            {

                e.printStackTrace();

            }finally

            {

                this.close();

            }

            return al;

        }

        

        //修改用户

        public boolean updateUser(String id,String passwd,String email,String grade)

        {

            boolean b=false;

            try{

                //得到连接

                ConnDB cd=new ConnDB();

                ct=cd.getConn();

                

                String sql="update users set passwd='"+passwd+"',email='"+email+

                    "',grade='"+grade+"' where useId='"+id+"'";

                

                ps=ct.prepareStatement(sql);

                

                int num=ps.executeUpdate();

                

                if(num==1)

                {

                    //删除成功

                    b=true;

                }else

                {

                    //删除失败

                    

                }

            }catch(Exception e){

                e.printStackTrace();

            }finally{

                this.close();

            }

            return b;

        }

        

        //删除用户

        public boolean delUser(String id)

        {

            boolean b=false;

            try{

                //得到连接

                ConnDB cd=new ConnDB();

                ct=cd.getConn();

                

                String sql="delete from users where useId='"+id+"'";

                

                ps=ct.prepareStatement(sql);

                

                int num=ps.executeUpdate();

                

                if(num==1)

                {

                    //删除成功

                    b=true;

                }else

                {

                    //删除失败

                    

                }

            }catch(Exception e){

                e.printStackTrace();

            }finally{

                this.close();

            }

            return b;

        }

        

        //返回pageCount

        public int getPageCount()

        {

            return this.pageCount;

        }

        

        //关闭资源

        public void close()

        {

            try

                {

                    if(null!=rs) {rs.close();rs=null;}

                    if(null!=ps) {ps.close();ps=null;}

                    if(null!=ct) {ct.close();ct=null;}

                }catch(Exception e)

                {

                    e.printStackTrace();

                }

        }

    }

    model层_连接数据库(ConnDB.java)

    //从数据库中得到连接

     

    package com.user_mng;

     

    import java.sql.*;

     

    public class ConnDB

    {

        private Connection ct=null;

        

        public Connection getConn()

        {

            try{

                //得到rowCount

                //加载驱动

                Class.forName("org.gjt.mm.mysql.Driver").newInstance();

                // Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");

                

                // 得到连接

                // ct=DriverManager.getConnection(

                    // "jdbc:microsoft:sqlserver://127.0.0.1:1433;databaseName=test_user",

                    // "sa","luowei");

                ct=DriverManager.getConnection("jdbc:mysql://localhost:3306/test_user",

                    "root","root");    

            }catch(Exception e){

                e.printStackTrace();

            }

            return ct;

            

    /*        

            try{

                //利用数据源的方式访问数据库

                //创建一个上下文环境

                Context con=new javax.naming.InitalContext();

                //通过con得到数据源

                DataSource ds=(DataSource)con.lookup("java:comp/env/数据源的名字");

                ct=ds.getConnection();

            }catch(Eception e){

                e.printStackTrace();

            }

    */

        }

    }

  • 相关阅读:
    消息队列(一)
    Servlet3.1学习(三)
    再弄一片文章凑个4篇文章的数,主要是用于XML和 Binary序列化和反序列化的类
    Entity Framework底层操作封装(3)
    Entity Framework底层操作封装(2)
    Entity Framework底层操作封装(1)
    实现合并区间
    socket简单案例实现
    PostgreSQL11.2数据恢复记录(From Physical Files)
    Spring Data JPA 与 MyBatis 对比分析
  • 原文地址:https://www.cnblogs.com/luowei010101/p/2138366.html
Copyright © 2020-2023  润新知