日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

用jsp实现登录界面

發布時間:2024/9/21 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 用jsp实现登录界面 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一.用戶登錄案例需求:


?? ??? ?1.編寫login.jsp登錄頁面
?? ??? ??? ?username & password 兩個輸入框
?? ??? ?2.使用Druid數據庫連接池技術,操作mysql,day14數據庫中user表
?? ??? ?3.使用JdbcTemplate技術封裝JDBC
?? ??? ?4.登錄成功跳轉到SuccessServlet展示:登錄成功!用戶名,歡迎您
?? ??? ?5.登錄失敗跳轉到login.jsp展示:登錄失敗,用戶名或密碼錯誤,驗證碼錯誤

二.分析


?

?三. 開發步驟

1. 創建項目,配置文件,導入jar包

2. 創建數據庫環境


?? ??? ??? ?CREATE DATABASE day17;
?? ??? ??? ?USE day17;
?? ??? ??? ?CREATE TABLE loginUSER( ? -- 創建表
? ? ? ? ? ? ? ? ?id INT PRIMARY KEY AUTO_INCREMENT,
? ? ? ? ? ? ? ? username VARCHAR(20) NOT NULL,
? ? ? ? ? ? ? ? PASSWORD VARCHAR(20) NOT NULL
? ? ? ? ? ? );

?3.創建前端login.jsp和css頁面

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%> <!DOCTYPE html> <html lang="zh-CN"><head><meta charset="utf-8"/><meta http-equiv="X-UA-Compatible" content="IE=edge"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>管理員登錄</title><!-- 1. 導入CSS的全局樣式 --><link href="css/bootstrap.min.css" rel="stylesheet"><!-- 2. jQuery導入,建議使用1.9以上的版本 --><script src="js/jquery-2.1.0.min.js"></script><!-- 3. 導入bootstrap的js文件 --><script src="js/bootstrap.min.js"></script><script type="text/javascript">//切換驗證碼function refreshCode(){img=document.getElementById("vcode"); //獲取驗證碼圖片對象var time=new Date().getTime(); //時間戳img.src="${pageContext.request.contextPath }/checkcode?"+time;}</script></head><body><div class="container" style="width: 400px;"><h3 style="text-align: center;">管理員登錄</h3><form action="${pageContext.request.contextPath}/checklogin" method="post"><div class="form-group"><label for="user">用戶名:</label><input type="text" name="userName" class="form-control" id="user" placeholder="請輸入用戶名"/></div><div class="form-group"><label for="password">密碼:</label><input type="password" name="password" class="form-control" id="password" placeholder="請輸入密碼"/></div><div class="form-inline"><label for="vcode">驗證碼:</label><input type="text" name="verifycode" class="form-control" id="verifycode" placeholder="請輸入驗證碼" style="width: 120px;"/><a href="javascript:refreshCode()"><img src="${pageContext.request.contextPath }/checkcode" title="看不清點擊刷新" id="vcode"/></a></div><div style="color: red;">${log_msg}</div><hr/><div class="form-group" style="text-align: center;"><input class="btn btn btn-primary" type="submit" value="登錄"></div></form><!-- 出錯顯示的信息框 --><div class="alert alert-warning alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" ><span>&times;</span></button><strong>${log_msg}</strong></div></div></body> </html>

4.在domain包下創建類LoginUser

package domain;public class LoginUser {private int id;private String userName;private String password;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}@Overridepublic String toString() {return "LoginUser [id=" + id + ", userName=" + userName + ", password=" + password + "]";}}

5.寫utils包下的工具類JDBCUtils?,主要是與mysql數據庫連接,創建數據庫連接池對象

package cn.itcast.util;import com.alibaba.druid.pool.DruidDataSourceFactory;import javax.sql.DataSource;import javax.xml.crypto.Data;import java.io.IOException;import java.io.InputStream;import java.sql.Connection;import java.sql.SQLException;import java.util.Properties;/*** JDBC工具類 使用Durid連接池*/public class JDBCUtils {private static DataSource ds ;static {try {//1.加載配置文件Properties pro = new Properties();//使用ClassLoader加載配置文件,獲取字節輸入流InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");pro.load(is);//2.初始化連接池對象ds = DruidDataSourceFactory.createDataSource(pro);} catch (IOException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}}/*** 獲取連接池對象*/public static DataSource getDataSource(){return ds;}/*** 獲取連接Connection對象*/public static Connection getConnection() throws SQLException {return ds.getConnection();}}

6.創建web層的checkcode的servlet,? 用來顯示驗證碼的

package web.servlet;import java.io.IOException; import java.util.Random; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage;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;@WebServlet("/checkcode") public class CheckCode extends HttpServlet{/*** */private static final long serialVersionUID = 1L;@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// TODO Auto-generated method stubthis.doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {int imgwidth=100;int imgheight=40;//1.創建圖片對象,在內存中圖片(驗證碼圖片對象)BufferedImage image=new BufferedImage(imgwidth,imgheight,BufferedImage.TYPE_INT_RGB); //也可以指定讀取image=imageIO.read(new file())//2.美化圖片Graphics g=image.getGraphics(); //獲得畫筆對象//設置畫筆顏色g.setColor(Color.pink);//在創建的圖片對象大小中填充矩形,顏色為上面設置的顏色,第一,二個參數是起始點的x,y,第三,四個參數是有多寬,有多高g.fillRect(0, 0, imgwidth, imgheight);//重新設置畫筆顏色g.setColor(Color.yellow);//畫框邊緣顏色//在image上畫邊框,第一,二個參數是起始點的x,y,第三,四個參數是有多寬,有多高,注意:邊框占一個像素,所以需要寬和高-1才能覆蓋全部g.drawRect(0, 0, imgwidth-1, imgheight-1);//隨機設置驗證碼的值String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";Random random=new Random();StringBuilder sb=new StringBuilder();//隨機在image中寫字符串,第三,四個參數是畫的位置for(int i=1;i<5;i++) {int index=random.nextInt(str.length()); //隨機選取字母字符g.setFont(new Font("宋體", Font.PLAIN, 20)); //設置畫筆大小sb.append(str.charAt(index));//將隨機驗證碼置于stringbuilder中g.setColor(Color.blue); //畫筆顏色g.drawString(str.charAt(index)+"",imgwidth/5*i ,25); }//將驗證碼存儲與session對象中,用于loginservlet中的驗證碼驗證String session_code=sb.toString();req.getSession().setAttribute("session_code", session_code);//隨機畫干擾線,第一,二個參數是起始點的x,y,第三,四個參數是最后一個點的x,yint x1=0,y1=0,x2=0,y2=0;for(int i=0;i<=8;i++) { //畫8次線條x1=random.nextInt(imgwidth);y1=random.nextInt(imgheight);x2=random.nextInt(imgwidth);y2=random.nextInt(imgheight);g.setColor(Color.gray);g.drawLine(x1, y1, x2, y2);}//3.圖片顯示在頁面上ImageIO.write(image, "jpg", resp.getOutputStream()); //將圖片寫入指定文件(第三個參數是指定的位置Fileoutpotstream(new File(""))}}

7.創建web層的checklogin的servlet,用來響應用戶登錄的請求。主要是進行前端參數數據和UserDao進行交互

代碼:

package web.servlet;import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Map;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 org.apache.commons.beanutils.BeanUtils;import com.mchange.v2.codegen.bean.BeangenUtils;import dao.UserDaoImpl; import domain.LoginUser;@WebServlet("/checklogin") public class CheckLogin extends HttpServlet{/*** */private static final long serialVersionUID = 1L;@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// TODO Auto-generated method stubthis.doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//1.設置編碼req.setCharacterEncoding("utf-8");//2.獲取用戶的請求LoginUser loginUser=new LoginUser();Map<String, String[]> pMap=req.getParameterMap();//3.使用BeanUtil封裝對象try {BeanUtils.populate(loginUser, pMap);} catch (IllegalAccessException | InvocationTargetException e) {// TODO Auto-generated catch blocke.printStackTrace();}//4.現獲取前端填寫的驗證碼,比較驗證碼System.out.println(loginUser);String exc=req.getParameter("verifycode");//獲取前端用戶填寫的驗證碼HttpSession htp=req.getSession(); //獲取sessionString excode=(String) htp.getAttribute("session_code"); //獲取后端checkcode隨機驗證碼//為防止驗證碼重復使用,session中的session_code一旦獲得,就必須刪除htp.removeAttribute("session_code");if(excode!=null && excode.equalsIgnoreCase(exc)) {//忽略字母大小寫,比較驗證碼//如果驗證碼正確,再比較用戶的用戶名和密碼//驗證碼正確//5.創建userDao對象UserDaoImpl userDaoImpl=new UserDaoImpl(); //調用與數據庫的函數LoginUser lu=userDaoImpl.checkLoginUser(loginUser);if(lu!=null) {//如果登錄成功//保存數據,用戶信息htp.setAttribute("user", lu); //在session中保存用戶的信息htp.setAttribute("username", lu.getUserName());//在session中存儲用戶名//重定向到success.jsp頁面resp.sendRedirect(req.getContextPath()+"/index.jsp");}else {//用戶名或密碼不正確req.setAttribute("log_msg", "用戶名或密碼錯誤"); //存儲錯誤信息,用request域存儲 //請求轉發,重新回到登錄頁面req.getRequestDispatcher("/login.jsp").forward(req, resp);} }else {//驗證碼不正確req.setAttribute("log_msg", "驗證碼錯誤"); //存儲錯誤信息,用request域存儲req.getRequestDispatcher("/login.jsp").forward(req, resp); //請求轉發,重新回到登錄頁面}}}

?8.在dao層的,操作數據庫,查詢數據庫

操作數據庫的UserDao接口:

package dao;import java.util.List;import domain.User;public interface UserDao {public List<User> findAll(); //抽象方法public LoginUser checkLoginUser( LoginUser loginUser); }

操作數據庫的UserDaoImpl實現類:

package dao;import java.util.List;import javax.xml.transform.Templates;import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate;import domain.LoginUser; import domain.User; import utils.JDBCUtils;public class UserDaoImpl implements UserDao{JdbcTemplate jdbcTemplate =new JdbcTemplate(JDBCUtils.getDataSource());public List<User> findAll() {// 操作數據庫,查詢String sql="select * from user";List<User> users=jdbcTemplate.query(sql,new BeanPropertyRowMapper(User.class));return users;}public LoginUser checkLoginUser( LoginUser loginUser) {//查詢登錄用戶信息String sqlString="select* from loginuser where username=? and password=?";//System.out.println("111"+loginUser);try {LoginUser lu=(LoginUser) jdbcTemplate.queryForObject(sqlString, new BeanPropertyRowMapper<LoginUser>(LoginUser.class),loginUser.getUserName(),loginUser.getPassword());return lu;} catch (Exception e) {// TODO: handle exceptione.printStackTrace();return null;} } }

9.編寫success.jsp,在這里指的是index.jsp,對應在checklogin.java中

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%> <!DOCTYPE html> <html lang="zh-CN"><head><meta charset="utf-8"/><meta http-equiv="X-UA-Compatible" content="IE=edge"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>首頁</title><!-- 1. 導入CSS的全局樣式 --><link href="css/bootstrap.min.css" rel="stylesheet"><!-- 2. jQuery導入,建議使用1.9以上的版本 --><script src="js/jquery-2.1.0.min.js"></script><!-- 3. 導入bootstrap的js文件 --><script src="js/bootstrap.min.js"></script><script type="text/javascript"></script></head><body><div align="center"><ahref="${pageContext.request.contextPath }/userListServlet" style="text-decoration:none;font-size:33px">查詢所有用戶信息</a></div></body> </html>

四.尾聲

效果圖:

其他:

?login.jsp中form表單的action路徑的寫法
? ? ? ? ? ? * 虛擬目錄+Servlet的資源路徑

?BeanUtils工具類,簡化數據封裝
? ? ? ? ? ? * 用于封裝JavaBean的
? ? ? ? ? ? 1. JavaBean:標準的Java類
? ? ? ? ? ? ? ? 1. 要求:
? ? ? ? ? ? ? ? ? ? 1. 類必須被public修飾
? ? ? ? ? ? ? ? ? ? 2. 必須提供空參的構造器
? ? ? ? ? ? ? ? ? ? 3. 成員變量必須使用private修飾
? ? ? ? ? ? ? ? ? ? 4. 提供公共setter和getter方法
? ? ? ? ? ? ? ? 2. 功能:封裝數據

最后:用戶登錄的模塊功能全部結束!!!

總結

以上是生活随笔為你收集整理的用jsp实现登录界面的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。