登录案例version1 基本登录+验证码

package com.frxx.web.servlet; import com.frxx.domain.User;
import com.frxx.service.impl.UserServiceImpl; 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("/login")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8");
//校验验证码
String checkcode = request.getParameter("checkcode");
HttpSession session = request.getSession();
String checkcodeSession = (String) session.getAttribute("checkcode");
//验证码为一次性
session.removeAttribute("checkcode");
if(checkcodeSession == null || !checkcodeSession.equalsIgnoreCase(checkcode)){
//验证码错误,直接跳回登录页
request.getRequestDispatcher("frxx_login.html").forward(request, response);
} //1.获取用户名密码
String username = request.getParameter("username");
String password = request.getParameter("password"); //2.封装User对象,登录参数username password
User loginCondition = new User();
loginCondition.setUname(username);
loginCondition.setPassword(password); //3.Service,调用login方法
UserServiceImpl userService = new UserServiceImpl();
User user = userService.login(loginCondition); //4.判断是否为null
if(user != null){
//登录成功,将用户存入Session域中,跳转到首页
request.getSession().setAttribute("user", user);
response.sendRedirect(request.getContextPath() + "/index.jsp");
}else{
//登录失败,返回登录页面
response.sendRedirect(request.getContextPath() + "/frxx_login.html");
}
} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
LoginServlet
package com.frxx.web.servlet; import com.frxx.utils.GraphicHelper; 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("/checkCode")
public class CheckCodeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String checkcode = GraphicHelper.create(80, 40, "jpg", response.getOutputStream());
request.getSession().setAttribute("checkcode", checkcode);
} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
CheckCodeServlet
package com.frxx.utils; import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties; public class JdbcUtils {
private static DataSource ds; static{
/*
使用德鲁伊连接池
*/
InputStream is = null;
try {
//加载配置
Properties druidProperties = new Properties();
//获取配置文件流对象
is = JdbcUtils.class.getClassLoader().getResourceAsStream("druid.properties");
druidProperties.load(is); //创建德鲁伊连接池
ds = DruidDataSourceFactory.createDataSource(druidProperties);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally{
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} //获取数据源
public static DataSource getDataSource(){
return ds;
} //获取连接
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
}
JdbcUtils
package com.frxx.utils; import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random; public final class GraphicHelper { /**
* 以字符串形式返回生成的验证码,同时输出一个图片
*
* @param width
* 图片的宽度
* @param height
* 图片的高度
* @param imgType
* 图片的类型
* @param output
* 图片的输出流(图片将输出到这个流中)
* @return 返回所生成的验证码(字符串)
*/
public static String create(final int width, final int height,
final String imgType, OutputStream output) {
StringBuffer sb = new StringBuffer();
Random random = new Random(); BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics graphic = image.getGraphics();
graphic.setColor(Color.getColor("F8F8F8"));
graphic.fillRect(0, 0, width, height); Color[] colors = new Color[] { Color.BLUE, Color.GRAY, Color.GREEN,
Color.RED, Color.BLACK, Color.ORANGE, Color.magenta,Color.darkGray,Color.pink };
// 在 "画板"上生成干扰线条 ( 40 是线条个数)
for (int i = 0; i < 40; i++) {
graphic.setColor(colors[random.nextInt(colors.length)]);
final int x = random.nextInt(width);
final int y = random.nextInt(height);
final int w = random.nextInt(20);
final int h = random.nextInt(20);
final int signA = random.nextBoolean() ? 1 : -1;
final int signB = random.nextBoolean() ? 1 : -1;
graphic.drawLine(x, y, x + w * signA, y + h * signB);
}
// 在 "画板"上绘制字母
graphic.setFont(new Font("Comic Sans MS", Font.BOLD, 30));
for (int i = 0; i < 4; i++) {
final int temp = random.nextInt(26) + 97;
String s = String.valueOf((char) temp);
sb.append(s);
graphic.setColor(colors[random.nextInt(colors.length)]);
graphic.drawString(s, i * (width / 4), height - (height / 3));
}
graphic.dispose();
try {
ImageIO.write(image, imgType, output);
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}
GraphicHelper
package com.frxx.service;
import com.frxx.domain.User;
public interface UserService {
/**
* 用户登录
* @param userLoginCondition 用户名和密码
* @return
*/
User login(User userLoginCondition);
}
UserService
package com.frxx.service.impl; import com.frxx.dao.impl.UserDaoImpl;
import com.frxx.domain.User;
import com.frxx.service.UserService; public class UserServiceImpl implements UserService {
@Override
public User login(User loginCondition) {
UserDaoImpl userDao = new UserDaoImpl();
return userDao.login(loginCondition);
}
}
UserServiceImpl
package com.frxx.dao;
import com.frxx.domain.User;
public interface UserDao {
/**
* 用户登录
* @param loginCondition 条件是用户名和密码
* @return
*/
User login(User loginCondition);
}
UserDao
package com.frxx.dao.impl; import com.frxx.dao.UserDao;
import com.frxx.domain.User;
import com.frxx.utils.JdbcUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate; public class UserDaoImpl implements UserDao {
JdbcTemplate jdbcTemplate = new JdbcTemplate(JdbcUtils.getDataSource()); @Override
public User login(User loginCondition) {
//写语句
String sql = "select uid, uname, password, gender, phone, email, birthday from tb_user where uname=? and password=?";
//查询对象
User user = null;
try{
user = jdbcTemplate.queryForObject(sql,
new BeanPropertyRowMapper<User>(User.class),
loginCondition.getUname(), loginCondition.getPassword());
}catch (DataAccessException e){
// e.printStackTrace();//记录到日志文件中
}
return user;
}
}
UserDaoImpl
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>fupin</title>
<style>
/*使用原子类*/
.marginAuto{
margin: auto;
}
.wr1{
width: 1200px;
}
</style>
<style>
body{
margin: 0;
}
.loginHeader{
font-size: 40px;
color: #1bae9b;
padding: 30px 0px;
font-family: 华文行楷;
}
/*.logo-img-wr{*/
/*width: 1200px;*/
/*margin: 30px auto 30px;*/
/*}*/
.main-content{
background-color: #ccc;
height: 600px;
}
.login-form-wr{
box-sizing: border-box;
border: 1px solid black;
width: 300px;
/*text-align: center;*/
padding: 0px 30px 0px;
float: right;
margin-top: 100px;
margin-right: 100px;
}
.login-form-wr h1{
text-align: center;
font-size: 20px;
}
.login-form-wr .form-row{
width: 100%;
height: 35px;
margin-bottom: 10px;
font-size: 16px;
}
.normal-input{
box-sizing: border-box;
width: 100%;
height: 100%;
padding: 5px;
}
.login-form-wr .form-row input{
font-size: 14px;
}
.checkcode-input{
box-sizing: border-box;
width: 60%;
/*width: auto;*/
height: 100%;
vertical-align: middle;
margin-right: 5px;
/*padding: 5px;*/
}
.checkcode{
box-sizing: border-box;
width: 35%;
/*width: 80px;*/
height: 100%;
vertical-align: middle;
}
#remember-pwd{
position: relative;
top: -1px;
border: 1px solid black;
width: 20px;
height: 20px;
vertical-align: middle;
}
#submit-btn{
width: 100%;
height: 40px;
margin-bottom: 30px;
}
</style>
<script>
window.onload = function () {
/*
验证码点击切换:
1.绑定点击事件
2.点击时,修改图片的src属性,需要添加时间戳
原因:如果src的值2次是相同的,浏览器会在缓存中取,而不是发送请求。
*/
document.getElementById("checkCodeImg").onclick = function(){
document.getElementById("checkCodeImg").src = "/frxx/checkCode?time=" + new Date().getTime();
}
}
</script>
</head>
<body>
<!--logo-->
<div class="wr1 marginAuto loginHeader">
凡人修仙
</div>
<!--<div class="logo-img-wr">-->
<!--<img src="img/logo_dang_login.png" alt="">-->
<!--</div>-->
<!--背景和登录框-->
<div class="main-content">
<div class="login-form-wr">
<h1>用户登录</h1>
<form action="/frxx/login" method="post">
<div class="form-row">
<input class="normal-input" type="text" name="username" placeholder="请输入您的用户名">
</div>
<div class="form-row">
<input class="normal-input" type="password" name="password" placeholder="请输入您的密码">
</div>
<div class="form-row">
<input class="checkcode-input" type="text" name="checkcode" placeholder="请输入验证码">
<img id="checkCodeImg" class="checkcode" src="/frxx/checkCode" alt="">
</div>
<div class="form-row">
<input id="remember-pwd" type="checkbox" name="remember_pwd">
<label for="remember-pwd">记住我,以后自动登录</label>
</div>
<div>
<input id="submit-btn" type="submit" value="登录">
</div>
</form>
</div>
</div>
</body>
</html>
frxx_login.html
<%--
Created by IntelliJ IDEA.
User: jie
Date: 2019/5/8
Time: 15:21
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
<style>
.float-left{
float: right;
}
.mr-30{
margin-right: 30px;
}
</style>
</head>
<body>
<nav>
<div class="float-left mr-30">
<c:if test="${user == null}">
您好,请<a href="/frxx/frxx_login.html">登录</a>|<a href="/frxx/frxx_register.html">注册</a>
</c:if>
<c:if test="${user != null}">
${user.uname}<a href="#">退出</a>
</c:if>
</div>
</nav> </body>
</html>
index.jsp
登录案例version1 基本登录+验证码的更多相关文章
- Java 之 Session 包含验证码登录案例
需求: 1. 访问带有验证码的登录页面login.jsp 2. 用户输入用户名,密码以及验证码. 如果用户名和密码输入有误,跳转登录页面,提示:用户名或密码错误 如果验证码输入有误,跳转登录页面, ...
- Django(十六)基于模板的登录案例:登录装饰器、csrf攻击方式及防护、ajax的Post 的csrf开启写法、生成验证码、加验证码登录、反向解析+传参
一.csrf攻击 1.1 csrf攻击(跨站请求伪造) [csrf攻击即]:通过第3方网站,伪造请求(前提条件是你已经登录正常网站,并保存了session或cookie登录信息且没有退出),第三方网站 ...
- jsp之jstl(展示所有商品、重写登录案例)
jsp之jstl jstl: jsp标准的标签库语言,apache的,是用来替代java脚本 使用步骤: 1.导入jar包 (jstl.jar和standard.jar) 2.在页面上导入标签库 &l ...
- curl 模拟登录微信公众平台带验证码
这段时间一直写个项目, 从切图到前端到后台都要搞定,真tm累. 今天下午手残,不停用错误的密码去模拟登录微信公众平台,结果后来出现验证码,瞬间悲剧(菜鸟从来没搞过带验证码的). 研究了一下,发现其实很 ...
- Android first---文件读取(登录案例编写为主)
以android登录案例来介绍文件的读取与androidAPI给予的方法 第一步:绘制界面 绘制方法:在线性布局下面设置相对布局 代码部分: <LinearLayout xmlns:androi ...
- ADO.NET学习系列(三)----做一个登录案例
总体思路.根据用户输入的用户名和密码,来判断,和数据库里面存的是不是一样,如果一样就表明登录成功,否则就登录失败. 方案一: 1.select* from 表名 where username=&quo ...
- 基于Struts2框架实现登录案例 之 使用Struts2标签库简化表单+继承ActionSupport完成输入交验
一,使用Struts2标签库简化表单 在文章[基于Struts2框架实现登录案例]的基础上,通过使用Struts标签库可以简化登录页面login2.jsp <%@ page language=& ...
- 简单登录案例(SharedPreferences存储账户信息)&联网请求图片并下载到SD卡(文件外部存储)
新人刚学习Android两周,写一个随笔算是对两周学习成果的巩固,不足之处欢迎各位建议和完善. 这次写的是一个简单登录案例,大概功能如下: 注册的账户信息用SharedPreferences存储: 登 ...
- Android(java)学习笔记213:开源框架post和get方式提交数据(qq登录案例)
1.前面提到Http的get/post方式 . HttpClient方式,实际工作的时候不常用到,因为这些方式编写代码是很麻烦的 2.Android应用会经常使用http协议进行传输,网上会有很完善 ...
随机推荐
- camera报错经典问题
--- 33u>: error: undefined reference to 'NSFeature::RAWSensorInfo<22133u>::impGetDefaultDat ...
- Composer基础应用1
先唠叨唠叨一些琐碎的事.本人最早从事.Net开发,后来处于好奇慢慢转到了php,因为.net从一早就使用了命名空间(反正从我使用就存在这玩意了),所以在转php时很自然的就使用了命名空间,但是在使用过 ...
- ES搜索排序,文档相关度评分介绍——TF-IDF—term frequency, inverse document frequency, and field-length norm—are calculated and stored at index time.
Theory Behind Relevance Scoring Lucene (and thus Elasticsearch) uses the Boolean model to find match ...
- HDU 6170 Two strings (dp)
/** * 题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6170 * 字符串match, '.'代表匹配任意一个字符,"*" 代表 ...
- hdu-2874 Connections between cities(lca+tarjan+并查集)
题目链接: Connections between cities Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/327 ...
- linux命令学习笔记(24):Linux文件类型与扩展名
Linux文件类型和Linux文件的文件名所代表的意义是两个不同的概念.我们通过一般应用程序 而创建的比如file.txt.file.tar.gz ,这些文件虽然要用不同的程序来打开,但放在Linux ...
- POJ3237 Tree(树剖+线段树+lazy标记)
You are given a tree with N nodes. The tree’s nodes are numbered 1 through N and its edges are numbe ...
- 结合Mysql和kettle邮件发送日常报表_20161001
十一假期 参加婚礼 稍晚点发博 整体流程步骤是: 写SQL-导出到excel设定excel模板调整格式-设置kettle转换--设置kettle邮件作业--完成 第一.写SQL 保持最近12个周的数据 ...
- POJ 3258 最小值最大化 二分搜索
题意:牛要到河对岸,在与河岸垂直的一条线上,河中有N块石头,给定河岸宽度L,以及每一块石头离牛所在河岸的距离, 现在去掉M块石头,要求去掉M块石头后,剩下的石头之间以及石头与河岸的最小距离的最大值. ...
- C# FileStream Write追加写入文本
该例子为追加 C盘中的 file1.txt 的文本内容 完整代码如下: 引入命名空间: [csharp] view plain copy print? using System.IO; 完整代码: [ ...