登录案例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协议进行传输,网上会有很完善 ...
随机推荐
- BZOJ 1650 [Usaco2006 Dec]River Hopscotch 跳石子:二分
题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=1650 题意: 数轴上有n个石子,第i个石头的坐标为Di,现在要从0跳到L,每次条都从一个石 ...
- laravel基础课程---8、laravel响应和视图(响应是什么)
laravel基础课程---8.laravel响应和视图(响应是什么) 一.总结 一句话总结: 就是向请求返回的响应数据(一般为html(视图),当然也可以是变量值):所有的路由及控制器必须返回某个类 ...
- html5--1.5 文本元素
html5--1.5 文本元素 学习要点: 掌握常用的文本元素 文本元素,就是讲一段文本设置成相匹配的结构和含义 1.b元素: 我的作用就是 加粗文字: 2.br元素: 我的作用就是强制换行: 3.i ...
- xpath normalize-sapce 函数的Java实现
normalize-space函数实现的功能是:删除字符串前后空格,中间的空格有多个只保留一个. 1. 用Java正则表达式 public static String normalizeSpace(S ...
- star score
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http ...
- 数据结构与算法(2)----->字符串
1. 字符串的一些特点 1.1 广泛性 (1)字符串可以看作是字符类型的数组----->所以可能会涉及排序+查找; (2)很多问题都可以转化为字符串类型的方法去解决; 需要注意的是:用java ...
- Mesos以及Marathon安装总结
安装了将近一周的环境了,终于把Mesos以及Marathon给安装上了,我指的离线安装. 策略1: 严格的按照官网的流程: http://mesos.apache.org/gettingstarted ...
- 洛谷 P3804 [模板] 后缀自动机
题目:https://www.luogu.org/problemnew/show/P3804 模仿了一篇题解,感觉很好写啊. 代码如下: #include<cstdio> #include ...
- .NETFramework-Web.Services:WebMethodAttribute
ylbtech-.NETFramework-Web.Services:WebMethodAttribute 1.程序集 System.Web.Services, Version=4.0.0.0, Cu ...
- web.xml中:<context-param>与<init-param>的区别与作用及获取方法
<context-param>的作用: web.xml的配置中<context-param>配置作用1. 启动一个WEB项目的时候,容器(如:Tomcat)会去读它的配置文件w ...