Case: Use this code to complete the login session storage functions

image

Case needs

1. When the user login to the login page to view the codes, as shown:

2. While the resulting page CAPTCHA image, use the session to store code

3. When a user registration request processing, first check codes

4. Verify login operation is performed by order

case study

image

Code:

1. page code

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>login</title>
<script type="text/javascript">
function changeCode(){
document.getElementById("img").src = "/day04/checkcode?r="+new
Date().getTime();
}
</script>
</head>
<body>
<form action="/day04/login" method="post">
<table>
<tr><td>用户名:</td><td><input type="text" name="username"></td></tr>
<tr><td>密码:</td><td><input type="password" name="password"></td></tr>
<tr><td>验证码:</td><td><input type="text" name="code"></td></tr>
<!-- 通过向服务器发送请求,从服务器获取验证码数据 -->
<tr><td></td><td><img id="img" src="/day04/checkcode"
onclick="changeCode();"/><a href="javascript:;" onclick="changeCode();">换一换</a>
<span><% if(request.getAttribute("msg")!=null)
{out.write(request.getAttribute("msg").toString());}%></span></td></tr>
<tr><td></td><td><input type="submit" value="登陆"></td></tr>
</table>
</form>
</body>
</html>



2. 配置验证码servlet

@WebServlet(name = "CheckcodeServlet",urlPatterns = "/checkcode")

public class CheckcodeServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// 创建画布

int width = 120;

int height = 40;

BufferedImage bufferedImage = new BufferedImage(width, height,

BufferedImage.TYPE_INT_RGB);

// 获得画笔

Graphics g = bufferedImage.getGraphics();

// 填充背景颜色

g.setColor(Color.white);

g.fillRect(0, 0, width, height);

// 绘制边框

g.setColor(Color.red);

g.drawRect(0, 0, width - 1, height - 1);

// 生成随机字符3. 登录servlet

// 准备数据

String data =

"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";

// 准备随机对象

Random r = new Random();

// 声明一个变量 保存验证码

String code = "";

// 书写4个随机字符

for (int i = 0; i < 4; i++) {

// 设置字体

g.setFont(new Font("宋体", Font.BOLD, 28));

// 设置随机颜色

g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));

String str = data.charAt(r.nextInt(data.length())) + "";

g.drawString(str, 10 + i * 28, 30);

// 将新的字符 保存到验证码中

code = code + str;

}

// 绘制干扰线

for (int i = 0; i < 6; i++) {

// 设置随机颜色

g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));

g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width),

r.nextInt(height));

}

// 将验证码 打印到控制台

System.out.println(code);

// 将验证码放到session中

request.getSession().setAttribute("code_session", code);

// 将画布显示在浏览器中

ImageIO.write(bufferedImage, "jpg", response.getOutputStream());

}

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response);

}

}

3. 登录servlet

@WebServlet(name = "LoginServlet",urlPatterns = "/login")

public class LoginServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {4. dao:

//用户请求中的验证码获取

String code = request.getParameter("code");

//获取session中保存的验证码

String code_session =

(String)request.getSession().getAttribute("code_session");

//与session中保存的验证码进行校验

if(!code_session.equalsIgnoreCase(code)){

//验证码错误,告诉用户,页面提示

request.setAttribute("msg","验证码错误");

request.getRequestDispatcher("/login.jsp").forward(request,response);

return;

}

//验证码正确,登录逻辑执行

//获取用户名和密码

String username = request.getParameter("username");

String password = request.getParameter("password");

//调用Service方法,登录用户

UserDao userDao = new UserDao();

User loginUser = userDao.login(username,password);

if(loginUser == null){

request.setAttribute ( "msg", "user name or password is wrong");

request.getRequestDispatcher("/login.jsp").forward(request,response);

return;

}else{

// successful landing, jump Home

response.sendRedirect(request.getContextPath());

return;

}

}

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response);

}

}

4. dao:

public class UserDao {

private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

/**

* Query method if the username and password match

*/

@Override

public User login(String username, String password) {

String sql = "select * from user where username = ? and password = ?";

try {

User query = template.queryForObject(sql, new

BeanPropertyRowMapper<User>(User.class), username,password);

return query;

}catch (Exception e){

e.printStackTrace ();

return null;

}

}

}

The difference between the session and the cookie

image




Guess you like

Origin www.cnblogs.com/hujunwei/p/10939673.html