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

 1 package com.frxx.web.servlet;
 2 
 3 import com.frxx.domain.User;
 4 import com.frxx.service.impl.UserServiceImpl;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.annotation.WebServlet;
 8 import javax.servlet.http.HttpServlet;
 9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11 import javax.servlet.http.HttpSession;
12 import java.io.IOException;
13 
14 @WebServlet("/login")
15 public class LoginServlet extends HttpServlet {
16     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
17 
18         request.setCharacterEncoding("UTF-8");
19         //校验验证码
20         String checkcode = request.getParameter("checkcode");
21         HttpSession session = request.getSession();
22         String checkcodeSession = (String) session.getAttribute("checkcode");
23         //验证码为一次性
24         session.removeAttribute("checkcode");
25         if(checkcodeSession == null || !checkcodeSession.equalsIgnoreCase(checkcode)){
26             //验证码错误,直接跳回登录页
27             request.getRequestDispatcher("frxx_login.html").forward(request, response);
28         }
29 
30         //1.获取用户名密码
31         String username = request.getParameter("username");
32         String password = request.getParameter("password");
33 
34         //2.封装User对象,登录参数username  password
35         User loginCondition = new User();
36         loginCondition.setUname(username);
37         loginCondition.setPassword(password);
38 
39         //3.Service,调用login方法
40         UserServiceImpl userService = new UserServiceImpl();
41         User user = userService.login(loginCondition);
42 
43         //4.判断是否为null
44         if(user != null){
45             //登录成功,将用户存入Session域中,跳转到首页
46             request.getSession().setAttribute("user", user);
47             response.sendRedirect(request.getContextPath() + "/index.jsp");
48         }else{
49             //登录失败,返回登录页面
50             response.sendRedirect(request.getContextPath() + "/frxx_login.html");
51         }
52     }
53 
54     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
55         doPost(request, response);
56     }
57 }
LoginServlet
 1 package com.frxx.web.servlet;
 2 
 3 import com.frxx.utils.GraphicHelper;
 4 
 5 import javax.servlet.ServletException;
 6 import javax.servlet.annotation.WebServlet;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 import java.io.IOException;
11 
12 @WebServlet("/checkCode")
13 public class CheckCodeServlet extends HttpServlet {
14     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
15         String checkcode = GraphicHelper.create(80, 40, "jpg", response.getOutputStream());
16         request.getSession().setAttribute("checkcode", checkcode);
17     }
18 
19     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
20         doPost(request, response);
21     }
22 }
CheckCodeServlet
 1 package com.frxx.utils;
 2 
 3 import com.alibaba.druid.pool.DruidDataSourceFactory;
 4 
 5 import javax.sql.DataSource;
 6 import java.io.IOException;
 7 import java.io.InputStream;
 8 import java.sql.Connection;
 9 import java.sql.SQLException;
10 import java.util.Properties;
11 
12 public class JdbcUtils {
13     private static DataSource ds;
14 
15     static{
16         /*
17             使用德鲁伊连接池
18          */
19         InputStream is = null;
20         try {
21             //加载配置
22             Properties druidProperties = new Properties();
23             //获取配置文件流对象
24             is = JdbcUtils.class.getClassLoader().getResourceAsStream("druid.properties");
25             druidProperties.load(is);
26 
27             //创建德鲁伊连接池
28             ds = DruidDataSourceFactory.createDataSource(druidProperties);
29         } catch (IOException e) {
30             e.printStackTrace();
31         } catch (Exception e) {
32             e.printStackTrace();
33         } finally{
34             if(is != null){
35                 try {
36                     is.close();
37                 } catch (IOException e) {
38                     e.printStackTrace();
39                 }
40             }
41         }
42     }
43 
44     //获取数据源
45     public static DataSource getDataSource(){
46         return ds;
47     }
48 
49     //获取连接
50     public static Connection getConnection() throws SQLException {
51         return ds.getConnection();
52     }
53 }
JdbcUtils
 1 package com.frxx.utils;
 2 
 3 import javax.imageio.ImageIO;
 4 import java.awt.*;
 5 import java.awt.image.BufferedImage;
 6 import java.io.IOException;
 7 import java.io.OutputStream;
 8 import java.util.Random;
 9 
10 public final class GraphicHelper {
11 
12     /**
13      * 以字符串形式返回生成的验证码,同时输出一个图片
14      *
15      * @param width
16      *            图片的宽度
17      * @param height
18      *            图片的高度
19      * @param imgType
20      *            图片的类型
21      * @param output
22      *            图片的输出流(图片将输出到这个流中)
23      * @return 返回所生成的验证码(字符串)
24      */
25     public static String create(final int width, final int height,
26                                 final String imgType, OutputStream output) {
27         StringBuffer sb = new StringBuffer();
28         Random random = new Random();
29 
30         BufferedImage image = new BufferedImage(width, height,
31                 BufferedImage.TYPE_INT_RGB);
32         Graphics graphic = image.getGraphics();
33         graphic.setColor(Color.getColor("F8F8F8"));
34         graphic.fillRect(0, 0, width, height);
35 
36         Color[] colors = new Color[] { Color.BLUE, Color.GRAY, Color.GREEN,
37                 Color.RED, Color.BLACK, Color.ORANGE, Color.magenta,Color.darkGray,Color.pink };
38         // 在 "画板"上生成干扰线条 ( 40 是线条个数)
39         for (int i = 0; i < 40; i++) {
40             graphic.setColor(colors[random.nextInt(colors.length)]);
41             final int x = random.nextInt(width);
42             final int y = random.nextInt(height);
43             final int w = random.nextInt(20);
44             final int h = random.nextInt(20);
45             final int signA = random.nextBoolean() ? 1 : -1;
46             final int signB = random.nextBoolean() ? 1 : -1;
47             graphic.drawLine(x, y, x + w * signA, y + h * signB);
48         }
49         // 在 "画板"上绘制字母
50         graphic.setFont(new Font("Comic Sans MS", Font.BOLD, 30));
51         for (int i = 0; i < 4; i++) {
52             final int temp = random.nextInt(26) + 97;
53             String s = String.valueOf((char) temp);
54             sb.append(s);
55             graphic.setColor(colors[random.nextInt(colors.length)]);
56             graphic.drawString(s, i * (width / 4), height - (height / 3));
57         }
58         graphic.dispose();
59         try {
60             ImageIO.write(image, imgType, output);
61         } catch (IOException e) {
62             e.printStackTrace();
63         }
64         return sb.toString();
65     }
66 }
GraphicHelper
 1 package com.frxx.service;
 2 
 3 import com.frxx.domain.User;
 4 
 5 public interface UserService {
 6 
 7     /**
 8      * 用户登录
 9      * @param userLoginCondition 用户名和密码
10      * @return
11      */
12     User login(User userLoginCondition);
13 }
UserService
 1 package com.frxx.service.impl;
 2 
 3 import com.frxx.dao.impl.UserDaoImpl;
 4 import com.frxx.domain.User;
 5 import com.frxx.service.UserService;
 6 
 7 public class UserServiceImpl implements UserService {
 8     @Override
 9     public User login(User loginCondition) {
10         UserDaoImpl userDao = new UserDaoImpl();
11         return userDao.login(loginCondition);
12     }
13 }
UserServiceImpl
 1 package com.frxx.dao;
 2 
 3 import com.frxx.domain.User;
 4 
 5 public interface UserDao {
 6     /**
 7      * 用户登录
 8      * @param loginCondition 条件是用户名和密码
 9      * @return
10      */
11     User login(User loginCondition);
12 }
UserDao
 1 package com.frxx.dao.impl;
 2 
 3 import com.frxx.dao.UserDao;
 4 import com.frxx.domain.User;
 5 import com.frxx.utils.JdbcUtils;
 6 import org.springframework.dao.DataAccessException;
 7 import org.springframework.jdbc.core.BeanPropertyRowMapper;
 8 import org.springframework.jdbc.core.JdbcTemplate;
 9 
10 public class UserDaoImpl implements UserDao {
11     JdbcTemplate jdbcTemplate = new JdbcTemplate(JdbcUtils.getDataSource());
12 
13     @Override
14     public User login(User loginCondition) {
15         //写语句
16         String sql = "select uid, uname, password, gender, phone, email, birthday from tb_user where uname=? and password=?";
17         //查询对象
18         User user = null;
19         try{
20             user = jdbcTemplate.queryForObject(sql,
21                     new BeanPropertyRowMapper<User>(User.class),
22                     loginCondition.getUname(), loginCondition.getPassword());
23         }catch (DataAccessException e){
24 //            e.printStackTrace();//记录到日志文件中
25         }
26         return user;
27     }
28 }
UserDaoImpl
  1 <!DOCTYPE html>
  2 <html lang="en">
  3 <head>
  4     <meta charset="UTF-8">
  5     <title>fupin</title>
  6     <style>
  7         /*使用原子类*/
  8         .marginAuto{
  9             margin: auto;
 10         }
 11         .wr1{
 12             width: 1200px;
 13         }
 14     </style>
 15     <style>
 16         body{
 17             margin: 0;
 18         }
 19         .loginHeader{
 20             font-size: 40px;
 21             color: #1bae9b;
 22             padding: 30px 0px;
 23             font-family: 华文行楷;
 24         }
 25         /*.logo-img-wr{*/
 26             /*width: 1200px;*/
 27             /*margin: 30px auto 30px;*/
 28         /*}*/
 29         .main-content{
 30             background-color: #ccc;
 31             height: 600px;
 32         }
 33         .login-form-wr{
 34             box-sizing: border-box;
 35             border: 1px solid black;
 36             width: 300px;
 37             /*text-align: center;*/
 38             padding: 0px 30px 0px;
 39             float: right;
 40             margin-top: 100px;
 41             margin-right: 100px;
 42         }
 43         .login-form-wr h1{
 44             text-align: center;
 45             font-size: 20px;
 46         }
 47         .login-form-wr .form-row{
 48             width: 100%;
 49             height: 35px;
 50             margin-bottom: 10px;
 51             font-size: 16px;
 52         }
 53         .normal-input{
 54             box-sizing: border-box;
 55             width: 100%;
 56             height: 100%;
 57             padding: 5px;
 58         }
 59         .login-form-wr .form-row input{
 60             font-size: 14px;
 61         }
 62         .checkcode-input{
 63             box-sizing: border-box;
 64             width: 60%;
 65             /*width: auto;*/
 66             height: 100%;
 67             vertical-align: middle;
 68             margin-right: 5px;
 69             /*padding: 5px;*/
 70         }
 71         .checkcode{
 72             box-sizing: border-box;
 73             width: 35%;
 74             /*width: 80px;*/
 75             height: 100%;
 76             vertical-align: middle;
 77         }
 78         #remember-pwd{
 79             position: relative;
 80             top: -1px;
 81             border: 1px solid black;
 82             width: 20px;
 83             height: 20px;
 84             vertical-align: middle;
 85         }
 86         #submit-btn{
 87             width: 100%;
 88             height: 40px;
 89             margin-bottom: 30px;
 90         }
 91     </style>
 92     <script>
 93         window.onload = function () {
 94             /*
 95                 验证码点击切换:
 96                     1.绑定点击事件
 97                     2.点击时,修改图片的src属性,需要添加时间戳
 98                     原因:如果src的值2次是相同的,浏览器会在缓存中取,而不是发送请求。
 99              */
100             document.getElementById("checkCodeImg").onclick = function(){
101                 document.getElementById("checkCodeImg").src = "/frxx/checkCode?time=" + new Date().getTime();
102             }
103         }
104     </script>
105 </head>
106 <body>
107     <!--logo-->
108     <div class="wr1 marginAuto loginHeader">
109         凡人修仙
110     </div>
111     <!--<div class="logo-img-wr">-->
112         <!--<img src="img/logo_dang_login.png" alt="">-->
113     <!--</div>-->
114     <!--背景和登录框-->
115     <div class="main-content">
116         <div class="login-form-wr">
117             <h1>用户登录</h1>
118             <form action="/frxx/login" method="post">
119                 <div class="form-row">
120                     <input class="normal-input"  type="text" name="username" placeholder="请输入您的用户名">
121                 </div>
122                 <div class="form-row">
123                     <input class="normal-input" type="password" name="password" placeholder="请输入您的密码">
124                 </div>
125                 <div class="form-row">
126                     <input class="checkcode-input" type="text" name="checkcode" placeholder="请输入验证码">
127                     <img id="checkCodeImg" class="checkcode" src="/frxx/checkCode" alt="">
128                 </div>
129                 <div class="form-row">
130                     <input id="remember-pwd" type="checkbox" name="remember_pwd">
131                     <label for="remember-pwd">记住我,以后自动登录</label>
132                 </div>
133                 <div>
134                     <input id="submit-btn" type="submit" value="登录">
135                 </div>
136             </form>
137         </div>
138     </div>
139 </body>
140 </html>
frxx_login.html
 1 <%--
 2   Created by IntelliJ IDEA.
 3   User: jie
 4   Date: 2019/5/8
 5   Time: 15:21
 6   To change this template use File | Settings | File Templates.
 7 --%>
 8 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 9 <html>
10   <head>
11     <title>$Title$</title>
12     <style>
13         .float-left{
14           float: right;
15         }
16         .mr-30{
17           margin-right: 30px;
18         }
19     </style>
20   </head>
21   <body>
22   <nav>
23     <div class="float-left mr-30">
24       <c:if test="${user == null}">
25         您好,请<a href="/frxx/frxx_login.html">登录</a>|<a href="/frxx/frxx_register.html">注册</a>
26       </c:if>
27       <c:if test="${user != null}">
28         ${user.uname}<a href="#">退出</a>
29       </c:if>
30     </div>
31   </nav>
32 
33   </body>
34 </html>
index.jsp

 

posted @ 2019-05-11 23:32  没有理由不会呀  阅读(434)  评论(0编辑  收藏  举报