Servlet课程0426(十二)Servlet MV模式下用户登录及查看用户表中所有用户

Welcome.java

//登录界面
package com.tsinghua;

import javax.servlet.http.*;
import java.io.*;
import  java.sql.*;
import java.util.*;

public class Welcome extends HttpServlet{
    public void doGet(HttpServletRequest req, HttpServletResponse res)
    {

        //业务逻辑
        Connection ct = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try{

        //从Session中得到用户名
        HttpSession hs = req.getSession(true);
        String myName = (String)hs.getAttribute("uname");
        String name="";
        String passwd="";
        if(myName == null)
        {
                //如果session中没有用户信息,在看看有没有cookie信息
                        //客户端得到所有cookie信息
        Cookie[] allCookies = req.getCookies();
        int i = 0;
        //如果allCookie不为空
        if(allCookies != null)
        {
            //从中取出cookie
            for (i = 0; i<allCookies.length; i++)
            {
                //依次取出
                Cookie temp = allCookies[i];

                if(temp.getName().equals("myname"))
                {
                    //得到cookie的值
                    name = temp.getValue();
                }
                else if(temp.getName().equals("mypasswd"))
                {
                    passwd = temp.getValue();
                }
            }
            System.out.println("myname="+name+" passwd="+passwd);
            if(!name.equals("") && passwd.equals(""))
            {
                //loginCl去验证
                res.sendRedirect("loginCl?username="+name+"&userpwd="+passwd);
                return;
            }
        }

                //返回登录界面
                res.sendRedirect("login?info=error1");
                return;

        }
        //解决中文乱码
        res.setCharacterEncoding("gbk");
        PrintWriter pw = res.getWriter();
        pw.println("<html>");
        pw.println("<body><center>");
        //在Servlet中显示图片
        pw.println("<img src='./imgs/1.GIF' /><br/>");

        pw.println("wel,hello");
        pw.println("你的用户名是,"+myName);
        pw.println("<br><a href=login>返回重新登录</a>");

        //==========================分页的功能=====================
        int pageSize = 3;//一页显示几条记录
        int pageNow = 1;//希望显示第几页

        //动态的接收pageNow
        String sPageNow = req.getParameter("pageNow");
        //用户第一次进入welcome页面,此时spageNow为null,所以不需要去改动pageNow,因为pageNow此时的值默认为1
        if(sPageNow != null)
        {
            pageNow = Integer.parseInt(sPageNow);
        }

        //调用UserBeanCl
        UserBeanCl ubc = new UserBeanCl();
        ArrayList al = ubc.getResultByPage(pageNow,pageSize);

        pw.println("<table border=1>");
        pw.println("<tr><th>id</th><th>name</th><th>password</th><th>email</th><th>grade</th></tr>");
        System.out.println("al.size = "+al.size());

        for (int i = 0; i < al.size(); i++)
        {
            System.out.println("i = "+i);
            
            UserBean ub = (UserBean) al.get(i);

            pw.println("<tr>");
            pw.println("<td>"+ub.getUserId()+"</td>");
            pw.println("<td>"+ub.getUserName()+"</td>");
            pw.println("<td>"+ub.getPasswd()+"</td>");
            pw.println("<td>"+ub.getMail()+"</td>");
            pw.println("<td>"+ub.getGrade()+"</td>");
            pw.println("</tr>");

        }

        pw.println("</table>");
        //显示超链接
        pw.println("<a href=wel?pageNow="+1+">首页</a>");
        if(pageNow != 1)
        {
            pw.println("<a href=wel?pageNow="+(pageNow-1)+">上一页</a>");
        }

        for(int i = pageNow; i <= pageNow+4; i++)
        {
            pw.println("<a href=wel?pageNow="+i+">"+i+"</a>");
        }
        int pageCount = ubc.getPageCount();
        if(pageNow != pageCount)
        {
            pw.println("<a href=wel?pageNow="+(pageNow+1)+">下一页</a>");
        }

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

        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }

    }

     //处理get请求
     //req用于获得客户端(浏览器)的信息
     //res用于向 客户端(浏览器)返回信息
    public void doPost(HttpServletRequest req, HttpServletResponse res)
    {

        this.doGet(req,res);

    }


}

UserBeanCl.java

//这是一个处理类(处理users表)<---->操作userBean
//业务逻辑部分
package com.tsinghua;

import java.sql.*;
import java.util.*;


public class UserBeanCl{
        //业务逻辑
        private    Connection ct = null;
        private    PreparedStatement ps = null;
        private    ResultSet rs = null;
        private int pageCount = 0;//共有几页(计算出来的)

        //返回pageCount
        public int getPageCount()
        {
            return this.pageCount;
        }

        //分页显示
        public ArrayList getResultByPage(int pageNow ,int pageSize){

            ArrayList al = new ArrayList();
            try{

            int rowCount = 0;//共有几条记录(查表)
            //1加载驱动
            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 top "+pageSize+" * from users where userId not in (select top "+(pageSize*(pageNow-1))+" userId from users)");
            //执行查询
            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));

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

            }catch(Exception ex){
                ex.printStackTrace();
            }finally{
                this.close();
            }
            return al;
        }

        //验证用户
        public boolean checkUser(String u, String p){
            boolean b = false;
            try{
                //得到连接
                ConnDB cd = new ConnDB();
                ct = cd.getConn();

                ps = ct.prepareStatement("select top 1 passwd from users where username=?");
                ps.setString(1,u);
                rs = ps.executeQuery();
                if(rs.next()){
                    String dbPasswd = rs.getString(1);
                    if(dbPasswd.equals(p)){
                        b = true;
                    }
                }


            }catch(Exception ex){
                ex.printStackTrace();
            }finally{
                this.close();
            }
            return b;

        }

        //关闭资源
        public void close()
        {
            try{
                if(rs != null){
                    rs.close();
                    rs = null;
                }
                if(ps != null){
                    ps.close();
                    ps = null;
                }
                if(ct != null){
                    ct.close();
                    ct = null;
                }
            }catch(Exception ex){
                ex.printStackTrace();
            }
        }


}

UserBean.java

//这是一个UserBean <---->user表映射
//它的一个对象<---->users表的一条记录对应
//本身代表的就是数据
package com.tsinghua;

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;
    }



}

ConnDB.java

//从数据库中得到连接
package com.tsinghua;

import java.sql.*;

public class ConnDB{

    private Connection ct = null;

    public Connection getConn()
    {
        try{
            //1.加载 驱动
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            //2.返回连接
            ct = DriverManager.getConnection("jdbc:sqlserver://127.0.0.1:1433;databaseName=spdb","sa","123456");

        }catch(Exception ex){
            ex.printStackTrace();
        }
        return ct;
    }
}

LoginCl.java

//登录界面
package com.tsinghua;

import javax.servlet.http.*;
import java.io.*;
import java.sql.*;

public class LoginCl extends HttpServlet{
    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("userpwd");

            //调用UserBeanCl 1.创建一个对象
            UserBeanCl ubc = new UserBeanCl();

            //2.使用UserBeanCl处理的方法
            if(ubc.checkUser(u,p))
            {


                    //将用户名和密码保存在客户端
                    //创建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,得到session那张表
                HttpSession hs = req.getSession(true);
                //默认30分钟,为了展示效果下面修改销毁时间
                //该方法是按照秒来算的
                hs.setMaxInactiveInterval(30);

                //写入属性
                hs.setAttribute("uname",u);

                //跳转到welcome
                res.sendRedirect("wel?uname="+u);


            }else{
                //说明用户名不存在
                //不合法
                //写你要到的Servlet的那个URL
                res.sendRedirect("login");

            }


        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }finally{

            try{
                    if(rs != null)
                        rs.close();
                    if(sm != null)
                        sm.close();
                    if(ct != null)
                        ct.close();


                }catch(Exception ex){
                    ex.printStackTrace();
                }

        }

    }

     //处理get请求
     //req用于获得客户端(浏览器)的信息
     //res用于向 客户端(浏览器)返回信息
    public void doPost(HttpServletRequest req, HttpServletResponse res)
    {

        this.doGet(req,res);

    }


}

Login.java

//登录界面
package com.tsinghua;

import javax.servlet.http.*;
import java.io.*;

public class Login extends HttpServlet{
    public void doGet(HttpServletRequest req, HttpServletResponse res)
    {

            //业务逻辑
        try{
            //中文乱码
            //浏览器默认ISO-8859
            res.setContentType("text/html;charset=gbk");

            PrintWriter pw = res.getWriter();

            //返回登录界面
            pw.println("<html>");
            pw.println("<body>");
            //得到error信息
            String info = req.getParameter("info");
            if(info != null)
            {
                pw.println("<h1>你的用户名或是密码错误!</h1>");
            }
            pw.println("<h1>登录界面</h1>");
            pw.println("<form action='loginCl' method=post>");
            pw.println("用户名<input type='text' name='username'/><br/>");
            pw.println("<br/>密&nbsp码<input type='password' name='userpwd'/><br/>");
            pw.println("<br/><input type=checkbox name=keep value=2/>两周内不用再登录<br/>");
            pw.println("<br/><input type='submit' value='loing' /><br/>");
            pw.println("</form>");
            pw.println("</body>");
            pw.println("</html>");


        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }

    }

     //处理get请求
     //req用于获得客户端(浏览器)的信息
     //res用于向 客户端(浏览器)返回信息
    public void doPost(HttpServletRequest req, HttpServletResponse res)
    {

        this.doGet(req,res);

    }


}

 

posted on 2016-04-27 12:55  让编程成为一种习惯  阅读(290)  评论(0编辑  收藏  举报