栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

会话跟踪技术(Cookie&Session)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

会话跟踪技术(Cookie&Session)

会话跟踪技术
  • 会话:用户打开浏览器,访问web服务器的资源,会话建立,直到有一方断开连接,会话结束。在一次会话中可以包含多次请求和响应

  • 会话跟踪:一种维护浏览器状态的方法,服务器需要识别多次请求是否来自于同一浏览器,以便在同一次会话的多次请求间共享数据

  • HTTP协议是无状态的,每次浏览器向服务器请求时,服务器都会将该请求视为新的请求,因此我们需要会话跟踪技术来实现会话内数据共享

  • 实现方式:

    1. 客户端会话跟踪技术:Cookie
    2. 服务端会话跟踪技术:Session
Cookie基本使用
  • Cookie:客户端会话技术,将数据保存到客户端,以后每次请求都携带Cookie数据进行访问

  • Cookie基本使用

    • 发生Cookie

      1. 创建Cookie对象,设置数据

        Cookie cookie = new Cookie("key","value");
        
      2. 发送Cookie到客户端:使用response对象

        response.addCookie(cookie);
        
    • 使用Cookie

      1. 获取客户端携带的所有Cookie,使用request对象

        Cookie[] cookies = request.getCookies();
        
      2. 遍历数组,获取每一个Cookie对象: for

        for (Cookie cookie : cookie) {
            String name = cookie.getName();
            if("username".equals(name)) {
                String value = cookie.getValue();
                System.out.println(name+":"+value);
                
                break;
            }
        }
        
      3. 使用Cookie对象方法获取数据

        cookie.getName();
        cookie.getValue();
        
Cookie原理
  • Cookie的实现是基于HTTP协议的
    • 响应头: set-cookie
    • 请求头: cookie
Cookie使用细节
  • Cookie存活时间
    • 默认情况下,Cookie存储在浏览器内存中,当浏览器关闭,内存释放,则Cookie被销毁
    • setMaxAge(int seconds):设置Cookie存活时间
      1. 正数:将Cookie写入浏览器所在电脑的硬盘,持久化存储。到时间自动删除
      2. 负数:默认值,Cookie在当前浏览器内存中,当浏览器关闭,则Cookie被销毁
      3. 零:删除对应Cookie
  • Cookie存储中文
    • Cookie不能直接存储中文
    • 如需要存储,则需要进行转码:URL编码
Session基本使用
  • 服务端会话跟踪技术:将数据保存到服务端

  • JavaEE提供 HttpSession接口,来实现一次会话的多次请求间数据共享功能

  • 使用:

    1. 获取Session对象

      HttpSession session = request.getSession();
      
    2. Session对象功能:

    • void setAttribute(String name, Object o):存储数据到session域中
    • Object getAttribute(String name):根据key,获取值
    • void removeAttribute(String name):根据key,删除该键值对
Session原理
  • Session是基于Cookie实现的

服务器自动创建一个Cookie:JSessionId=xxx

Session使用细节
  • Session钝化、活化:

    服务器重启后,Session中的数据是否还在?

    • 钝化:在服务器正常关闭后,Tomcat会自动将Session数据写入硬盘的文件中(tomcat存储为SESSIONS.ser)
    • 活化:再次启动服务器后,从文件中加载数据到Session中(SESSIONS.ser会被删除)
  • Seesion销毁:

    • 默认情况下,无操作,30分钟自动销毁

    • 也可在web.xml中配置

      
      	30
      
      
    • 手动销毁:调用Session对象的invalidate()方法

小结
  • Cookie和Session都是来完成一次会话内多次请求间数据共享的
  • 区别:
    • 存储位置:Cookie是将数据存储在客户端,Session将数据存储在服务端
    • 安全性:Cookie不安全,Session安全
    • 数据大小:Cookie最大3KB,Session无大小限制
    • 存储时间:Cookie可以长期存储,Session默认30分钟
    • 服务器性能:Cookie不占服务器资源,Session 占用服务器资源
案例 登录注册案例

需求说明:

  1. 完成用户登录功能,如果用户勾选“记住用户”,则下次访问登录页面
    自动填充用户名密码
  2. 完成注册功能,并实现验证码功能
用户登录

记住用户
  • 如果用户勾选“记住用户”,则下次访问登陆页面自动填充用户名密

  • 如何自动填充用户名和密码?

    1. 将用户名和密码写入Cookie中,并且持久化存储Cookie,下次访问浏览器会自动携带Cookie

    2. 在页面获取Cookie数据后,设置到用户名和密码框中

      ${cookie.key.value} //key指存储在cookie中的键名称
      
  • 何时写Cookie?

    1. 登录成功
    2. 用户勾选记住用户复选框
注册案例
  • 注册功能:保存用户信息到数据库

  • 验证码功能:

    • 展示验证码:展示验证码图片,并可以点击切换

    • 校验验证码:验证码填写不正确,则注册失败

验证码
  • 验证码就是使用Java代码生成的一张图片验证码
  • 作用:防止机器自动注册,攻击服务器
生成验证码
  • 使用验证码生成工具类创建验证码,并传入img标签的sec中
校验验证码
  • 判断程序生成的验证码和用户输入的验证码是否一样,如果不一样,则阻止注册
  • 验证码图片访问和提交注册表单是两次请求,所以要将程序生成的验证码存入Session中

案例具体代码 目录结构

具体代码
//BrandMapper接口
package com.jihua.mapper;

import com.jihua.pojo.Brand;
import org.apache.ibatis.annotations.*;

import java.util.List;


public interface BrandMapper {
    
    @Select("select * from tb_brand")
    @ResultMap("brandResultMap")
    List selectAll();


    @Insert("insert into tb_brand values(null,#{brandName},#{companyName},#{ordered},#{description},#{status})")
    void add(Brand brand);

    
    @Select("select * from tb_brand where id = #{id}")
    @ResultMap("brandResultMap")
    Brand selectById(int id);


    
    @Update("update tb_brand set brand_name=#{brandName},company_name=#{companyName},ordered=#{ordered},description=#{description},status=#{status} where id =#{id}")
    void update(Brand brand);

    
    @Delete("delete from tb_brand where id = ${id}")
    void deleteById(int id);
}
//UserMapper接口
package com.jihua.mapper;

import com.jihua.pojo.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

public interface UserMapper {
    
    @Select("select * from tb_user where username = #{username} and password = #{password}")
    User select(@Param("username") String username, @Param("password") String password);

    
    @Select("select * from tb_user where username=#{username}")
    User selectByUsername(String username);

    
    @Insert("insert into tb_user values(null, #{username}, #{password})")
    void add(User user);
}
//Brand对象
package com.jihua.pojo;

public class Brand {
    //id 主键
    private Integer id;
    //品牌名称
    private String brandName;
    //企业名称
    private String companyName;
    //排序字段
    private Integer ordered;
    //描述信息
    private String description;


    //状态 0:禁用 1:启用
    private Integer status;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getBrandName() {
        return brandName;
    }

    public void setBrandName(String brandName) {
        this.brandName = brandName;
    }

    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    public Integer getOrdered() {
        return ordered;
    }

    public void setOrdered(Integer ordered) {
        this.ordered = ordered;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public Brand() {
    }

    public Brand(Integer id, String brandName, String companyName, String description) {
        this.id = id;
        this.brandName = brandName;
        this.companyName = companyName;
        this.description = description;
    }

    public Brand(Integer id, String brandName, String companyName, Integer ordered, String description, Integer status) {
        this.id = id;
        this.brandName = brandName;
        this.companyName = companyName;
        this.ordered = ordered;
        this.description = description;
        this.status = status;
    }

    @Override
    public String toString() {
        return "Brand{" +
                "id=" + id +
                ", brandName='" + brandName + ''' +
                ", companyName='" + companyName + ''' +
                ", ordered=" + ordered +
                ", description='" + description + ''' +
                ", status=" + status +
                '}';
    }
}
//User对象
package com.jihua.pojo;

public class User {
    private Integer id;
    private String username;


    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }


    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }


    @Override
    public String toString() {
        return "User{" + "id=" + id + ", name='" + username + ''' + ", password='" + password + ''' + '}';
    }
}
//BrandService类
package com.jihua.service;

import com.jihua.mapper.BrandMapper;
import com.jihua.pojo.Brand;
import com.jihua.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class BrandService {
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();

    
    public List selectAll() {
        //调用BrandMapper.selectAll()

        //2. 获取sqlSession
        SqlSession sqlSession = factory.openSession();
        //3. 获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //4. 调用方法
        List brands = mapper.selectAll();
        //释放资源
        sqlSession.close();
        return brands;
    }

    
    public void add(Brand brand) {
        //2. 获取sqlSession
        SqlSession sqlSession = factory.openSession();
        //3. 获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //4. 调用方法
        mapper.add(brand);
        //提交事务
        sqlSession.commit();
        //释放资源
        sqlSession.close();
    }


    
    public Brand selectByID(int id) {

        //2. 获取sqlSession
        SqlSession sqlSession = factory.openSession();
        //3. 获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //4. 调用方法
        Brand brand = mapper.selectById(id);
        //释放资源
        sqlSession.close();
        return brand;
    }



    
    public void update(Brand brand) {
        //2. 获取sqlSession
        SqlSession sqlSession = factory.openSession();
        //3. 获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //4. 调用方法
        mapper.update(brand);
        //提交事务
        sqlSession.commit();
        //释放资源
        sqlSession.close();
    }


    
    public void deleteById(int id) {
        //2. 获取sqlSession
        SqlSession sqlSession = factory.openSession();
        //3. 获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //4. 调用方法
        mapper.deleteById(id);
        //提交事务
        sqlSession.commit();
        //释放资源
        sqlSession.close();
    }

}
//UserService类
package com.jihua.service;

import com.jihua.mapper.UserMapper;
import com.jihua.pojo.User;
import com.jihua.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;


public class UserService {

    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();

    
    public User login(String username, String password) {
        //2. 获取sqlSession
        SqlSession sqlSession = factory.openSession();
        //3. 获取UserMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //4. 调用方法
        User user = mapper.select(username, password);
        //释放资源
        sqlSession.close();
        return user;

    }

    
    public boolean register(User user) {
        //2. 获取sqlSession
        SqlSession sqlSession = factory.openSession();
        //3. 获取UserMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //4. 判断用户名是否存在
        User u = mapper.selectByUsername(user.getUsername());
        if (u == null) {
            //用户名不存在
            //添加用户
            mapper.add(user);
            //提交事务
            sqlSession.commit();
        }
        //释放资源
        sqlSession.close();
        return u == null;
    }

}
//CheckCodeUtil验证码工具类
package com.jihua.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Random;


public class CheckCodeUtil {

    //使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符
    public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
    private static Random random = new Random();


    
    public static String generateVerifyCode(int verifySize){
        return generateVerifyCode(verifySize, VERIFY_CODES);
    }
    
    public static String generateVerifyCode(int verifySize, String sources){
        if(sources == null || sources.length() == 0){
            sources = VERIFY_CODES;
        }
        int codesLen = sources.length();
        Random rand = new Random(System.currentTimeMillis());
        StringBuilder verifyCode = new StringBuilder(verifySize);
        for(int i = 0; i < verifySize; i++){
            verifyCode.append(sources.charAt(rand.nextInt(codesLen-1)));
        }
        return verifyCode.toString();
    }

    
    public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException{
        String verifyCode = generateVerifyCode(verifySize);
        outputImage(w, h, outputFile, verifyCode);
        return verifyCode;
    }

    
    public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException{
        String verifyCode = generateVerifyCode(verifySize);
        outputImage(w, h, os, verifyCode);
        return verifyCode;
    }

    
    public static void outputImage(int w, int h, File outputFile, String code) throws IOException{
        if(outputFile == null){
            return;
        }
        File dir = outputFile.getParentFile();
        if(!dir.exists()){
            dir.mkdirs();
        }
        try{
            outputFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(outputFile);
            outputImage(w, h, fos, code);
            fos.close();
        } catch(IOException e){
            throw e;
        }
    }

    
    public static void outputImage(int w, int h, OutputStream os, String code) throws IOException{
        int verifySize = code.length();
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Random rand = new Random();
        Graphics2D g2 = image.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
        Color[] colors = new Color[5];
        Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN,
                Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
                Color.PINK, Color.YELLOW };
        float[] fractions = new float[colors.length];
        for(int i = 0; i < colors.length; i++){
            colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
            fractions[i] = rand.nextFloat();
        }
        Arrays.sort(fractions);

        g2.setColor(Color.GRAY);// 设置边框色
        g2.fillRect(0, 0, w, h);

        Color c = getRandColor(200, 250);
        g2.setColor(c);// 设置背景色
        g2.fillRect(0, 2, w, h-4);

        //绘制干扰线
        Random random = new Random();
        g2.setColor(getRandColor(160, 200));// 设置线条的颜色
        for (int i = 0; i < 20; i++) {
            int x = random.nextInt(w - 1);
            int y = random.nextInt(h - 1);
            int xl = random.nextInt(6) + 1;
            int yl = random.nextInt(12) + 1;
            g2.drawLine(x, y, x + xl + 40, y + yl + 20);
        }

        // 添加噪点
        float yawpRate = 0.05f;// 噪声率
        int area = (int) (yawpRate * w * h);
        for (int i = 0; i < area; i++) {
            int x = random.nextInt(w);
            int y = random.nextInt(h);
            int rgb = getRandomIntColor();
            image.setRGB(x, y, rgb);
        }

        shear(g2, w, h, c);// 使图片扭曲

        g2.setColor(getRandColor(100, 160));
        int fontSize = h-4;
        Font font = new Font("Algerian", Font.ITALIC, fontSize);
        g2.setFont(font);
        char[] chars = code.toCharArray();
        for(int i = 0; i < verifySize; i++){
            AffineTransform affine = new AffineTransform();
            affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize/2, h/2);
            g2.setTransform(affine);
            g2.drawChars(chars, i, 1, ((w-10) / verifySize) * i + 5, h/2 + fontSize/2 - 10);
        }

        g2.dispose();
        ImageIO.write(image, "jpg", os);
    }

    private static Color getRandColor(int fc, int bc) {
        if (fc > 255)
            fc = 255;
        if (bc > 255)
            bc = 255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }

    private static int getRandomIntColor() {
        int[] rgb = getRandomRgb();
        int color = 0;
        for (int c : rgb) {
            color = color << 8;
            color = color | c;
        }
        return color;
    }

    private static int[] getRandomRgb() {
        int[] rgb = new int[3];
        for (int i = 0; i < 3; i++) {
            rgb[i] = random.nextInt(255);
        }
        return rgb;
    }

    private static void shear(Graphics g, int w1, int h1, Color color) {
        shearX(g, w1, h1, color);
        shearY(g, w1, h1, color);
    }

    private static void shearX(Graphics g, int w1, int h1, Color color) {

        int period = random.nextInt(2);

        boolean borderGap = true;
        int frames = 1;
        int phase = random.nextInt(2);

        for (int i = 0; i < h1; i++) {
            double d = (double) (period >> 1)
                    * Math.sin((double) i / (double) period
                    + (6.2831853071795862D * (double) phase)
                    / (double) frames);
            g.copyArea(0, i, w1, 1, (int) d, 0);
            if (borderGap) {
                g.setColor(color);
                g.drawLine((int) d, i, 0, i);
                g.drawLine((int) d + w1, i, w1, i);
            }
        }

    }

    private static void shearY(Graphics g, int w1, int h1, Color color) {

        int period = random.nextInt(40) + 10; // 50;

        boolean borderGap = true;
        int frames = 20;
        int phase = 7;
        for (int i = 0; i < w1; i++) {
            double d = (double) (period >> 1)
                    * Math.sin((double) i / (double) period
                    + (6.2831853071795862D * (double) phase)
                    / (double) frames);
            g.copyArea(i, 0, 1, h1, 0, (int) d);
            if (borderGap) {
                g.setColor(color);
                g.drawLine(i, (int) d, i, 0);
                g.drawLine(i, (int) d + h1, i, h1);
            }

        }

    }
}
//SqlSessionFactoryUtils工具类
package com.jihua.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class SqlSessionFactoryUtils {
    private static SqlSessionFactory sqlSessionFactory;

    static {
//静态代码块会随着类的加截而自动执行,且只执行一次
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }
}
//AddServlet类
package com.jihua.web;

import com.jihua.pojo.Brand;
import com.jihua.service.BrandService;

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

@WebServlet("/addServlet")
public class AddServlet extends HttpServlet {
    private BrandService service = new BrandService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //处理POST请求乱码问题
        request.setCharacterEncoding("UTF-8");

        //1.接收表单提交的数据,封装为一个Brand对象
        String brandName = request.getParameter("brandName");
        String companyName = request.getParameter("companyName");
        String ordered = request.getParameter("ordered");
        String description = request.getParameter("description");
        String status = request.getParameter("status");

        //封装为一个Brand对象
        Brand brand = new Brand();
        brand.setBrandName(brandName);
        brand.setCompanyName(companyName);
        brand.setOrdered(Integer.parseInt(ordered));
        brand.setDescription(description);
        brand.setStatus(Integer.parseInt(status));

        //2. 调用service 完成添加
        service.add(brand);

        //3. 转发到查询所有Servlet
        request.getRequestDispatcher("/selectAllServlet").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
//CheckCodeServlet类
package com.jihua.web;

import com.jihua.util.CheckCodeUtil;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //生成验证码
        ServletOutputStream os = response.getOutputStream();
        String checkCode = CheckCodeUtil.outputVerifyImage(150, 50, os, 4);
        //存入session
        HttpSession session = request.getSession();
        session.setAttribute("checkCodeGen",checkCode);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
//DeleteByIdServlet类
package com.jihua.web;

import com.jihua.pojo.Brand;
import com.jihua.service.BrandService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/deleteByIdServlet")
public class DeleteByIdServlet extends HttpServlet {
    private BrandService service = new BrandService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //处理POST请求乱码问题
        request.setCharacterEncoding("UTF-8");

        //1.接收id
        String id = request.getParameter("id");

        //2. 调用service 完成删除
        service.deleteById(Integer.parseInt(id));

        //3. 转发到查询所有Servlet
        request.getRequestDispatcher("/selectAllServlet").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
//LoginServlet类
package com.jihua.web;

import com.jihua.pojo.User;
import com.jihua.service.UserService;

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

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    private UserService service = new UserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 获取用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //获取复选框(remember)数据,1表示勾选
        String remember = request.getParameter("remember");
        //2. 调用service查询
        User user = service.login(username, password);
        //3. 判断
        if (user != null) {
            //登录成功
            //判断用户是否勾选记住我
            if ("1".equals(remember)){
                //勾选了,发送Cookie

                //1. 创建Cookie对象
                Cookie c_username = new Cookie("username",username);
                Cookie c_password = new Cookie("password", password);
                //设置Cookie存活时间
                c_username.setMaxAge(60*60*24*7);
                c_password.setMaxAge(60*60*24*7);
                //2. 发送Cookie
                response.addCookie(c_username);
                response.addCookie(c_password);

            }
            //将登录成功后的user对象,存储到session
            HttpSession session = request.getSession();
            session.setAttribute("user",user);
            //跳转到查询所有SelectAllServlet
            String contextPath = request.getContextPath();
            response.sendRedirect(contextPath + "/selectAllServlet");
        } else {
            //登录失败
            //将错误信息保存到request
            request.setAttribute("login_msg","用户名或密码错误");
            //跳转到login.jsp
            request.getRequestDispatcher("login.jsp").forward(request,response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
//RegisterServlet类
package com.jihua.web;

import com.jihua.pojo.User;
import com.jihua.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    private UserService service = new UserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 获取用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //封装为User对象
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        //获取用户输入的验证码
        String checkCode = request.getParameter("checkCode");
        //从session中获取程序生成的验证码
        HttpSession session = request.getSession();
        String checkCodeGen = (String) session.getAttribute("checkCodeGen");
        //比对(忽略大小写)
        if (!checkCodeGen.equalsIgnoreCase(checkCode)) {
            //不允许注册
            request.setAttribute("register_msg", "验证码错误");
            request.getRequestDispatcher("register.jsp").forward(request, response);
            return;
        }
        //2. 调用service注册
        boolean flag = service.register(user);
        //3. 判断注册成功与否
        if (flag) {
            //注册成功,跳转到登录页面
            request.setAttribute("register_msg", "注册成功,请登录");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        } else {
            //注册失败,跳转到注册页面
            request.setAttribute("register_msg", "用户名已存在");
            request.getRequestDispatcher("register.jsp").forward(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
//SelectAllServlet类
package com.jihua.web;

import com.jihua.pojo.Brand;
import com.jihua.service.BrandService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/selectAllServlet")
public class SelectAllServlet extends HttpServlet {
    private BrandService service = new BrandService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 调用BrandService完成查询
        List brands = service.selectAll();

        //2. 存入request域中
        request.setAttribute("brands", brands);

        //3. 转发到brand.jsp
        request.getRequestDispatcher("/brand.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
//SelectByIdServlet类
package com.jihua.web;

import com.jihua.pojo.Brand;
import com.jihua.service.BrandService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet("/selectByIdServlet")
public class SelectByIdServlet extends HttpServlet {
    private BrandService service = new BrandService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 接收id
        String id = request.getParameter("id");
        //2. 调用service
        Brand brand = service.selectByID(Integer.parseInt(id));
        //3. 存储到request域中
        request.setAttribute("brand",brand);
        //4. 转发到update.jsp
        request.getRequestDispatcher("/update.jsp").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }
}
//UpdateServlet类
package com.jihua.web;

import com.jihua.pojo.Brand;
import com.jihua.service.BrandService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/updateServlet")
public class UpdateServlet extends HttpServlet {
    private BrandService service = new BrandService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //处理POST请求乱码问题
        request.setCharacterEncoding("UTF-8");

        //1.接收表单提交的数据,封装为一个Brand对象
        String id = request.getParameter("id");
        String brandName = request.getParameter("brandName");
        String companyName = request.getParameter("companyName");
        String ordered = request.getParameter("ordered");
        String description = request.getParameter("description");
        String status = request.getParameter("status");

        //封装为一个Brand对象
        Brand brand = new Brand();
        brand.setId(Integer.parseInt(id));
        brand.setBrandName(brandName);
        brand.setCompanyName(companyName);
        brand.setOrdered(Integer.parseInt(ordered));
        brand.setDescription(description);
        brand.setStatus(Integer.parseInt(status));

        //2. 调用service 完成修改
        service.update(brand);

        //3. 转发到查询所有Servlet
        request.getRequestDispatcher("/selectAllServlet").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
//BrandMapper.xml



    
        
        

    

//UserMapper.xml





//mybatis-config.xml



    
    
        
    

    
        
            
            
                
                
                
                
                
            
        
    
    
        
        
    

//addBrand.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page isELIgnored="false" %>


    添加品牌


添加品牌
品牌名称︰
企业名称:
排序︰
描述信息︰
状态∶ 禁用 启用
brand.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page isELIgnored="false" %>


    Title


${user.username},欢迎您

序号 品牌名称 企业名称 排序 品牌介绍 状态 操作
${status.count} ${brand.brandName} ${brand.companyName} ${brand.ordered} ${brand.description} 启用 禁用 修改 删除
//login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>




    
    login



欢迎,请登录 ${login_msg} ${register_msg}

用户名:

密   码:

记住:

没有账号?注册
//register.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>




    
    欢迎注册
    


欢迎注册
已有账号?登录

用户名:

${register_msg}

密   码:

<%-- 密码格式有误
--%>

验证码: 看不清?

//update.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page isELIgnored="false" %>


    修改品牌


修改品牌
<%--隐藏域,提交id--%> 品牌名称︰
企业名称:
排序︰
描述信息︰
状态∶ 禁用 启用
禁用 启用
//pom.xml


    4.0.0

    org.example
    brand_demo
    1.0-SNAPSHOT

    war

    
        1.8
        1.8
    

    
        
        
            org.mybatis
            mybatis
            3.5.5
        

        
        
            mysql
            mysql-connector-java
            5.1.34
        

        
        
            javax.servlet
            javax.servlet-api
            3.1.0
            provided
        

        
        
            javax.servlet.jsp
            jsp-api
            2.2
            provided
        

        
        
            jstl
            jstl
            1.2
        
        
            taglibs
            standard
            1.1.2
        

    
    
        
            
                org.apache.tomcat.maven
                tomcat7-maven-plugin
                2.2
            


            
            
                org.apache.tomcat.maven
                tomcat7-maven-plugin
                2.2
                
                    
                    8080
                
            
        
    

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/932750.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号