JAVA 用户登录图形验证码

摘要: 由于公司需要做一个监控系统,然后需要一个简单的登录页面,所以就需要一个简单的登录并需要验证,所以就在网上查了一下简单的验证码制作,废话不多说,代码如下:

1.pom引用

		<dependency>
			<groupId>com.github.penggle</groupId>
			<artifactId>kaptcha</artifactId>
			<version>2.3.2</version>
		</dependency>

2.配置参数代码

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.Properties;


@Component  
public class KaptchaConfig {  
    @Bean(name="captchaProducer")
    public DefaultKaptcha getDefaultKaptcha(){  
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        Properties properties = new Properties();  
        properties.setProperty("kaptcha.border", "no");
        properties.setProperty("kaptcha.border.color", "105,179,90");
        properties.setProperty("kaptcha.textproducer.font.color", "black");
        properties.setProperty("kaptcha.image.width", "125");
        properties.setProperty("kaptcha.image.height", "45");
        properties.setProperty("kaptcha.textproducer.font.size", "35");
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");  
        Config config = new Config(properties);  
        defaultKaptcha.setConfig(config);  
        return defaultKaptcha;
    }

3.获取验证图片代码和登录代码,以及存储session和清除session退出代码

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

import com.unionpay.gmp.bean.UserInfo;
import com.unionpay.gmp.service.GmpLoginService;
import com.unionpay.gmp.utils.ResultUtil;
import com.unionpay.gmp.vo.response.ResponseVo;

@Controller
@RequestMapping("/user")
public class GmpLoginController {
    private static final Logger logger = LoggerFactory.getLogger(GmpLoginController.class);

    private Producer captchaProducer = null;

    @Autowired
    public void setCaptchaProducer(Producer captchaProducer) {
        this.captchaProducer = captchaProducer;
    }

    @Autowired
    private GmpLoginService gmpUserService;

    /**
     * 获取验证码图片
     * Gets captcha code.
     *
     * @param request  the request
     * @param response the response
     * @return the captcha code
     * @throws IOException the io exception
     */
    @RequestMapping("/captchaCode")
    public ModelAndView getCaptchaCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        //生成验证码文本
        String capText = captchaProducer.createText();
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);

        //利用生成的字符串构建图片
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
        return null;
    }

    /**
     * 登录接口
     */
    @RequestMapping(value = "/login")
    @ResponseBody
    public ResponseVo login(UserInfo userInfo, HttpServletRequest request) throws IOException {
        String accountName = userInfo.getAccountName();
        String password = userInfo.getPassword();
        String captcha = userInfo.getCaptcha();
        System.out.println("登录 |信息打印| 账号:"+accountName +"| 密码 :"+password);
        // 从session中获取之前保存的验证码跟前台传来的验证码进行匹配
        HttpSession session = request.getSession();
        String kaptcha = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        //System.out.println("##########################验证码打印 ::"+kaptcha);
        if (kaptcha == null) {
            return ResultUtil.error("验证码已失效");
        }
        if (!captcha.equals(kaptcha)) {
            return ResultUtil.error("验证码不正确");
        }
        // 用户信息
        UserInfo user = gmpUserService.findUserByAccountName(userInfo);
        // 账号不存在、密码错误
        if (user == null) {
            return ResultUtil.error("账号不存在");
        }
        if (!user.getPassword().equals(password)) {
            return ResultUtil.error("密码不正确");
        }
        //将用户信息存入session
        request.getSession().setAttribute("trustpointsUserInfo", user);
        return ResultUtil.success("查询成功", user);
    }

    /**
     * @param user
     * @param request
     * @param response
     * @desc: 修改密码
     */
    @RequestMapping(value = "/updateUserInfo")
    @ResponseBody
    public ResponseVo updateUserInfo(UserInfo user, HttpServletRequest request, HttpServletResponse response) {
        try {
            logger.info("密码修改 | 开始 | 接收到用户修改请求 ");
            if (verifyAdmin(request)) {
                //1. 判断完正在登录中以后即开始修改密码
                //2. 调用修改密码接口
                //3. 判断是否修改成功
                long updateFlag = gmpUserService.updateUserInfo(user);
                if (updateFlag == 1) {
                    logger.info("密码修改 | 成功 | 请重新登录! ");
                    return ResultUtil.success("修改成功", "请重新登录");
                } else {
                    return ResultUtil.error("修改失败");
                }
//           HttpSession session = request.getSession();
            } else {
                logger.warn("密码修改 | 失败 | 用户未登录或登录已超时! ");
                return ResultUtil.error("当前未登录");
            }
        } catch (Exception e) {
            logger.warn("密码修改 | 失败 | 用户未登录或登录已超时! " + e);
            return ResultUtil.error("修改失败");
        }

    }

    /**
     * @param user
     * @param request
     * @param response
     * @return 退出登录, 返回到登录页面
     */
    @RequestMapping(value = "/logout")
    @ResponseBody
    public ResponseVo logout(UserInfo user, HttpServletRequest request, HttpServletResponse response) {
        try {
            logger.info("退出登录 | 开始 | 接收到用户退出请求 ");
            if (verifyAdmin(request)) {
                HttpSession session = request.getSession();
                session.setAttribute("trustpointsUserInfo", null);
            }
        } catch (Exception e) {
            logger.info("退出登录 | 错误 | 请重试! "+e);
        }
        logger.info("退出登录 | 成功 | 成功退出用户 ");
        return ResultUtil.success("退出成功", "成功退出用户!");
    }

    /**
     * @desc: 判断session是否过期
     * @version: @1.0
     */
    private boolean verifyAdmin(HttpServletRequest request) {
        HttpSession session = request.getSession();
        UserInfo user = (UserInfo) session.getAttribute("trustpointsUserInfo");
        if (user == null) {
            String msg = "*当前未登录";
            request.setAttribute("msg", msg);

            return false;
        }
        String accountName = user.getAccountName();
        if (accountName == null || accountName.equals("")) {
            String msg = "*用户状态异常";
            request.setAttribute("msg", msg);
            return false;
        }
        return true;
    }

4. 上面的代码已经完整的(不带权限)将一个简单的登录实现出来,供大家参考! 还有就是网上很多例子,你给代码了,然后你不给引用的import ,真的挺烦的. 

注意:配置文件和controller是分开的!

5.效果图 

 

相关推荐
©️2020 CSDN 皮肤主题: 精致技术 设计师:CSDN官方博客 返回首页