孟繁森

登录案例session与Cookie的简单使用
java编辑器eclipse 服务器环境:tomcat HTML编辑器:Hbuilder 数据库管理系统:sqly...
扫描右侧二维码阅读全文
30
2019/07

登录案例session与Cookie的简单使用

开发工具:

java编辑器eclipse
服务器环境:tomcat
HTML编辑器:Hbuilder
数据库管理系统:sqlyog
数据库:mysql
项目架构:

1.servlet 类
2.service类
3.dao类
4.entity类
5.utils类
需要依赖的文件:

mysql驱动包、dbutils驱动包、c3p0驱动包、mchange驱动包
配置文件:c3p0.properties
创建数据库,创建表:

sql.png
搭建页面:

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<!--引入bootstrap核心的css文件-->
<link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
<!--因为bootstrap核心的js问价依赖于jquery,所以应该有限导入jquery文件-->
<script type="text/javascript" src="js/jquery-3.1.1.js"></script>
<!--引入bootstrap核心的js文件-->
<script type="text/javascript" src="js/bootstrap.js"></script>
<style>
    div{
        width:350px;
        margin:auto;
    }
    .container {
      margin-top: 120px;
      padding-bottom: 20px;
    }
    .mylogin {
      width: 350px;
      padding: 20px;
      padding-top: 5px;
      margin: 0 auto;
      border: 1px solid #eee;
      background-color: #fafad2;
    }
    h3 {
      margin-bottom: 20px;
    }

  </style>
</head>
<body>
<%
    //获取cookie
    Cookie[] cookies = request.getCookies();
    if(cookies !=null && cookies.length != 0){
        for(Cookie c:cookies){
            //如何获取cookies的名称getName以及值getValue();
            if("username".equals(c.getName())){
                pageContext.setAttribute("username", c.getValue());
            }
            if("pwd".equals(c.getName())){
                pageContext.setAttribute("pwd", c.getValue());
            }
        }
    }
%>
<div style="float:left;">
<span style="color:red;">${msg }</span>
</div>
<div>
 <form action="user" class="post">
    <h3 class="text-center">用户登录</h3>
    <div class="form-group">
      <div class="input-group">
        <div class="input-group-addon">
          <span>姓名:</span>
        </div>
        <input type="text" value="${username }" name="username" class="form-control" required>
      </div>
    </div>
    <div class="form-group">
       <div class="input-group">
        <div class="input-group-addon">
          <span>密码:</span>
        </div>
        <input type="password" value="${pwd }" name="pwd" class="form-control" required>
       </div>
    </div>
         <input type="submit" class="btn btn-primary form-control">
    </form>
  </div>
</body>
</html>

main.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <!--要转么创建一个页面来判断时候登录  -->
    <jsp:include page="check.jsp"></jsp:include>
    <h1>欢迎来到本系统</h1>
    欢迎您,${user.username }
</body>
</html>

check.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page import="com.offcn.entity.User"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
    /*
        通过存储在session中的关键字user的获取数据
    */
    User user = (User)session.getAttribute("user");
    if(user == null){
        request.setAttribute("msg", "请您先登录");
    
%>
    <jsp:forward page="login.jsp"></jsp:forward>
<%
    }
%>
</body>
</html>

Class页面:

com.offcn.entity包下的User.java类

package com.offcn.entity;

public class User {
    private int uid;
    private String username;
    private String pwd;
    public int getUid() {
        return uid;
    }
    public void setUid(int uid) {
        this.uid = uid;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPwd() {
        return pwd;
    }
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
    public User(int uid, String username, String pwd) {
        super();
        this.uid = uid;
        this.username = username;
        this.pwd = pwd;
    }
    public User(String username, String pwd) {
        super();
        this.username = username;
        this.pwd = pwd;
    }
    public User() {
        // TODO Auto-generated constructor stub
    }
}

com.offcn.servlet包下的UserServlet.java类

package com.offcn.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.offcn.entity.User;
import com.offcn.service.UserService;
@WebServlet("/user")
public class UserServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取登录数据
        String username = request.getParameter("username");
        String pwd = request.getParameter("pwd");
        //创建user类进行传输
        User user = new User(username,pwd);
        HttpSession session = request.getSession();
        boolean isSuccess = new UserService().login(user,session);
        if(isSuccess) {
            //获取cookie的值
            //获取用户名
            Cookie cookie1 = new Cookie("username", username);
            //获取密码
            Cookie cookie2 = new Cookie("pwd", pwd);
            //设置cookie的存活时间默认,默认生命周期是浏览器会话结束,单位是秒
            cookie1.setMaxAge(60*60*2);
            cookie2.setMaxAge(2*60*60);
            //将cookies响应给浏览器
            response.addCookie(cookie1);
            response.addCookie(cookie2);
            //跳转页面
            request.setAttribute("user", user);
            request.getRequestDispatcher("main.jsp").forward(request, response);
        }else {
            request.setAttribute("msg", "用户名或者密码输入错误");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }
}

com.offcn.service包下的UserService.java类

package com.offcn.service;

import javax.servlet.http.HttpSession;

import com.offcn.dao.UserDao;
import com.offcn.entity.User;

public class UserService {

    public boolean login(User user, HttpSession session) {
        User u = new UserDao().login(user);
        if(u != null) {
            //将登陆状态也就是user对象存储在session中
            session.setAttribute("user", u);
                return true;
        }
        return false;
    }

}

com.offcn.dao包下的UserDao.java类

package com.offcn.dao;

import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.offcn.entity.User;

public class UserDao {

    public User login(User user) {
        QueryRunner qRunner = new QueryRunner(new ComboPooledDataSource());
        User u = null;
        try {
        u = qRunner.query("select * from user where username=? and pwd=?",
                    new BeanHandler<User>(User.class),user.getUsername(),user.getPwd());
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return u;
    }

}

com.offcn.utils包下的DateTest.java类

package com.offcn.utils;

import java.util.Date;

public class DateTest {
    public static void main(String[] args) {
        Date date = new Date();
        System.out.println(date);
        java.sql.Date date2 = new java.sql.Date(System.currentTimeMillis());
        System.out.println(date2);
    }
}

c3p0.properties配置文件:

c3p0.driverClass=com.mysql.jdbc.Driver
c3p0.jdbcUrl=jdbc:mysql://localhost:3306/user
c3p0.user=root
c3p0.password=root

这里附上源码+所用jar包:

此处内容需要评论回复后(审核通过)方可阅读。

此处内容需要评论回复后(审核通过)方可阅读。

Last modification:September 19th, 2019 at 12:10 am
如果觉得我的文章对你有用,请随意赞赏

One comment

Leave a Comment