案例需求:
1. 访问带有验证码的登录页面login.jsp
2. 用户输入用户名,密码以及验证码
1. 如果用户名和密码输入有误,跳转登录页面,提示:用户名或者密码错误
2. 如果验证码输入有误,跳转登录页面,提示:验证码错误
3. 如果全部输入正确,则跳转到主页success.jsp,显示:用户名,欢迎您
分析:
1. login.jsp界面,form表单,提交方式为post,表单包括:用户名、密码、验证码输入框,name属性值分别为:username、password、checkcode_String,一个输出验证码图片,id为:checkCode,一个登录提交按钮
2. 生成验证码的Servlet,名字为CheckCodeServlet,将生成的验证码字符串封装为session,名字为checkCode_session,request.getSession().setAttribute("checkCode_session",checkCode_session),在login.jsp界面的img标签src属性指向CheckCodeServlet的虚拟路径
3. 连接MySQL数据库,用druid和JDBCTemplate,写JDBCUtils工具类,通过类加载器将配置文件加载进内存,写静态方法getDataSource()获取DataSource对象,还有静态方法getConnection(),获取Connection对象
private static DataSource ds;
Properties pro =new Properties();
InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid1.properties");
pro.load(is);
ds= DruidDataSourceFactory.createDataSource(pro);
public static DataSource getDataSourse(){ return ds;}
public static Connection getConnection() throws SQLException {return ds.getConnection();}
4. 写一个User类(javabean),用于存储从login.jsp页面获取到的提交表单数据,private String username,private String password,private String checkCode,生成setter,getter,toString方法
5. 写一个UserDao用于在数据库中寻找所传参数是否存在,首先获取JDBCTemplate对象,private JdbcTemplate jdbcTemplate=new JdbcTemplate(JDBCUtils.getDataSourse()),定义一个login(User user)方法,在方法内部先写sql语句,最后调用jdbcTemplate.queryForObject(String sql,new BeanPropertyRowMapper<Object>(Object.class),参数1,参数2...)方法,注意catch一个异常DataAccessException,否则如果查不到数据就出现异常,浏览器会报500错误码,方法体如下
public User login(User loginuser){
try {
//1.编写sql
String sql = "select * from user where username=? and password=?";
//2.调用query方法
User user = jdbcTemplate.queryForObject(sql,
new BeanPropertyRowMapper<User>(User.class),
loginuser.getUsername(), loginuser.getPassword());
return user;
}catch (DataAccessException e) {
e.printStackTrace();
return null;
}
}
6. 处理注册逻辑的Servlet,LoginServlet,首先设置request的编码格式为utf-8,防止中文乱码,然后从login.jsp中获取提交表单的数据,封装为Map集合,Map<String, String[]> parameterMap = request.getParameterMap(),创建一个User对象,用于将获取到的数据封装到这个对象,接着调用BeanUtils的populate方法封装,BeanUtils.populate(user,parameterMap),此时数据已经被封装到user里面,首先应该判断用户输入的验证码是否正确,先获取用户在页面输入的验证码,返回给checkcode_string字符串,再获取生成的验证码,返回给checkCode_session,判断if1(checkCode_session!=null && checkCode_session.equalsIgnoreCase(checkcode_string)),如果满足,说明验证码正确,然后创建UserDao对象,调用其login()方法,将这里的user传进去,返回一个login对象,if2 (login!=null),说明登录成功,获取该对象的username,设置session,名为user,值为username,重定向到success.jsp,在success.jsp页面里面输出xxx欢迎您回来,else2,登录失败,设置session,名为login,值为 "用户名或密码错误" ,转发给login.jsp,如果else1,那么验证码错误,设置session,名为cc_session,值为 "验证码错误" ,转发给login.jsp
7. 在login.jsp页面,末尾处加一段脚本代码,通过css选择器控制div颜色
<div><%=request.getSession().getAttribute("login") == null ? "":request.getSession().getAttribute("login")%></div>
<div><%=request.getSession().getAttribute("cc_session") == null ? "":request.getSession().getAttribute("cc_session")%></div>
8. 在success.jsp页面加入下面一段脚本
<h1><%=request.getSession().getAttribute("user")%>欢迎您回来</h1>
9. 至此本案例结束,项目名称idea下的, 11_登录案例_加入验证码
代码
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>login</title>
<script>
window.onload=function () {
//1. 获取图片对象
document.getElementById("checkCode").onclick=function () {//加时间戳
this.src="/day17/checkCodeServlet?"+new Date().getTime();
}
}
</script>
<style>
table input{
box-sizing: border-box;
vertical-align: center;
padding-left: 4px;
}
div{
color: red;
}
</style>
</head>
<body>
<form action="/day17/loginServlet" method="post">
<table>
<tr>
<td>用户名</td>
<td><input type="text" placeholder="请输入用户名" name="username"></td>
</tr>
<tr>
<td>密码</td>
<td><input type="password" placeholder="请输入密码" name="password"></td>
</tr>
<tr>
<td>验证码</td>
<td><input type="text" placeholder="请输入验证码" name="checkcode_String"></td>
</tr>
<tr>
<td colspan="2"><img src="/day17/checkCodeServlet" id="checkCode"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="登录"></td>
</tr>
</table>
</form>
<div><%=request.getSession().getAttribute("login") == null ? "":request.getSession().getAttribute("login")%></div>
<div><%=request.getSession().getAttribute("cc_session") == null ? "":request.getSession().getAttribute("cc_session")%></div>
</body>
</html>
CheckCodeServlet
package zr.web.servlet;
import javax.imageio.ImageIO;
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.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int width=100;
int height=50;
//1. 创建一个对象,在内存中代表这个验证码图片
BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//2. 美化这个图片
//2.1 填充背景色
Graphics graphics = image.getGraphics();// 画笔对象
graphics.setColor(Color.white);
graphics.fillRect(0,0,width,height);
//2.2 画边框
graphics.setColor(Color.blue);
graphics.drawRect(0,0,width-1,height-1);
//2.3 生成随机字符
String str="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
//生成随机脚标
Random ran=new Random();
StringBuilder sb =new StringBuilder();
for (int i = 1; i <=4 ; i++) {
int index = ran.nextInt(str.length());
//获取字符
char ch=str.charAt(index);//随机字符
sb.append(ch);
//2.4写验证码
graphics.drawString(ch+"",width/5*i,height/2);
}
String checkCode_session =sb.toString();
//将生成的验证码存入session
request.getSession().setAttribute("checkCode_session",checkCode_session);
//2.5画干扰线
graphics.setColor(Color.gray);
for (int i = 1; i <=10 ; i++) {
//随机生成坐标点
int x1 = ran.nextInt(width);
int y1 = ran.nextInt(height);
int x2 = ran.nextInt(width);
int y2 = ran.nextInt(height);
graphics.drawLine(x1,y1,x2,y2);
}
//3. 将图片输出到页面展示
ImageIO.write(image,"jpg",response.getOutputStream());
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
JDBCUtils
package zr.web.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{
try {
Properties pro =new Properties();
InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid1.properties");
pro.load(is);
ds= DruidDataSourceFactory.createDataSource(pro);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static DataSource getDataSourse(){
return ds;
}
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
}
User
package zr.web.domain;
public class User {
private String username;
private String password;
private String checkCode;
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setCheckCode(String checkCode) {
this.checkCode = checkCode;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getCheckCode() {
return checkCode;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", checkCode='" + checkCode + '\'' +
'}';
}
}
UserDao
package zr.web.dao;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import zr.web.domain.User;
import zr.web.utils.JDBCUtils;
public class UserDao {
//声明JDBCTemplate来共用
private JdbcTemplate jdbcTemplate=new JdbcTemplate(JDBCUtils.getDataSourse());
public User login(User loginuser){
try {
//1.编写sql
String sql = "select * from user where username=? and password=?";
//2.调用query方法
User user = jdbcTemplate.queryForObject(sql,
new BeanPropertyRowMapper<User>(User.class),
loginuser.getUsername(), loginuser.getPassword());
return user;
}catch (DataAccessException e) {
e.printStackTrace();
return null;
}
}
}
LoginServlet
package zr.web.servlet;
import org.apache.commons.beanutils.BeanUtils;
import zr.web.dao.UserDao;
import zr.web.domain.User;
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;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 设置request的编码
request.setCharacterEncoding("utf-8");
//获取所有请求参数
Map<String, String[]> parameterMap = request.getParameterMap();
//创建一个User对象,用于封装数据
User user=new User();
//使用BeanUtils封装
try {
BeanUtils.populate(user,parameterMap);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
String checkcode_string = request.getParameter("checkcode_String");
HttpSession session = request.getSession();
String checkCode_session = (String) session.getAttribute("checkCode_session");
session.removeAttribute("checkCode_session");
if(checkCode_session!=null && checkCode_session.equalsIgnoreCase(checkcode_string)){
UserDao dao=new UserDao();
User login = dao.login(user);
if (login!=null){
//登陆成功
String username = user.getUsername();
session.setAttribute("user",username);
//重定向到success.jsp
response.sendRedirect(request.getContextPath()+"/success.jsp");
}else{
//登录失败
session.setAttribute("login","用户名或密码错误");
//转发到login.jsp页面
request.getRequestDispatcher("/login.jsp").forward(request,response);
}
}else{
//验证码错误
session.setAttribute("cc_session","验证码错误");
//转发到login.jsp页面
request.getRequestDispatcher("/login.jsp").forward(request,response);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>success</title>
</head>
<body>
<h1><%=request.getSession().getAttribute("user")%>欢迎您回来</h1>
</body>
</html>