1. 程式人生 > >servelt與session實現登入並驗證的原始碼

servelt與session實現登入並驗證的原始碼

(1)登入index.jsp介面

(2)輸入驗證碼錯誤


(3)輸入驗證碼成功


(4)在webroot底下新建一個index.jsp檔案


index.jsp檔案

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
 
  </head>
  
  <body>
  	<%
  		String msg = (String)request.getAttribute("msg");
  		if(msg!=null){
  			out.print(msg);
  		}
  	 %>
  	<form action="/day10_01_HttpSession/servlet/doLogin" method="post">
		使用者名稱:<input type="text" name="userName"/><br>
		密碼:<input type="password" name="pwd"/><br>
		驗證碼:<input type="text" name="code"/>
		<img src="/day10_01_HttpSession/servlet/codeServlet" onclick="changeCode()"/><a href="javascript:changeCode()" >看不清換一張</a><br>
		<input type="submit" value="登入"/><br>
	</form>
  </body>
</html>
(5)DoLogin.java檔案
package com.itheima.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DoLogin extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		//獲取表單資料
		String userName = request.getParameter("userName");
		String pwd = request.getParameter("pwd");
		String code = request.getParameter("code");
		
		String scode = (String) request.getSession().getAttribute("scode");
		//處理業務邏輯
		if("tom".equals(userName)&&"123".equals(pwd)){
			//分發
			if(!code.equalsIgnoreCase(scode)){
				request.setAttribute("msg", "驗證碼錯誤!!!");
				request.getRequestDispatcher("/index.jsp").forward(request, response);
			}
			out.print("登入成功!!!");
		}
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

(6)CodeServlet.java檔案
package com.itheima.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.dsna.util.images.ValidateCode;

public class CodeServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ValidateCode vc = new ValidateCode(110, 25, 4, 9);//寬度110 高度25 驗證碼4 干擾線9個
		//向session中儲存驗證碼
		request.getSession().setAttribute("scode", vc.getCode());
		vc.write(response.getOutputStream());
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}