Servlet實(shí)現(xiàn)簡單的用戶登錄功能實(shí)例代碼
1、創(chuàng)建html界面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="" method="post"> 用戶名:<input type="text" name="username"> <br> 密碼:<input type="password" name="password"><br> <input type="submit" value="登錄"> </form> </body> </html>
2 、創(chuàng)建數(shù)據(jù)庫
CREATE TABLE USER( id INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(32) UNIQUE NOT NULL, PASSWORD VARCHAR(32) NOT NULL );
3、創(chuàng)建用戶實(shí)體類
public class User { 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; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + '}'; } }
4、創(chuàng)建jdbc工具類
這里使用的是c3p0 / druid 兩種數(shù)據(jù)庫連接池技術(shù) 分別需要在項(xiàng)目導(dǎo)入相應(yīng)的jar包
public class JDBCUtils { private static DataSource ds ; static { try { //1.加載配置文件 Properties pro = new Properties(); //使用ClassLoader加載配置文件,獲取字節(jié)輸入流 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(); } system.out.println("=============================================================") public class JDBCButil { final static ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource(); // 獲取連接方法 // 返回一個(gè)連接對象 public static Connection getCon() { // 連接使用c3p0進(jìn)行獲取 // 使用c3p0數(shù)據(jù)庫連接池獲取連接 Connection connection = null; try { connection = comboPooledDataSource.getConnection(); } catch (SQLException e) { System.err.println("獲取連接失敗"); return null; } return connection; } // DML方法 // 不支持事務(wù) 單條sql語句執(zhí)行 public static boolean DML(String sql, Object... o) { // 獲取連接 Connection con = getCon(); // 創(chuàng)建預(yù)編譯對象 try { PreparedStatement ps = con.prepareStatement(sql); for (int i = 0; i < o.length; i++) { ps.setObject((i + 1), o[i]); } ps.executeUpdate(); } catch (SQLException e) { System.out.println("查詢執(zhí)行失敗:" + sql); return false; } return true; } // DML方法 // 支持事務(wù) 多條sql語句執(zhí)行 public static boolean DML(Connection con, String sql, Object... o) { // 創(chuàng)建預(yù)編譯對象 try { PreparedStatement ps = con.prepareStatement(sql); for (int i = 0; i < o.length; i++) { ps.setObject((i + 1), o[i]); } ps.executeUpdate(); } catch (SQLException e) { System.out.println("查詢執(zhí)行失敗:" + sql); return false; } return true; } // 查詢dql語句方法 public static <E> ArrayList<E> DQL(String sql, Class<E> c, Object... o) { ArrayList<E> list = new ArrayList<>(); try { // 獲取連接 Connection con = getCon(); // 準(zhǔn)備預(yù)編譯對象 PreparedStatement ps = con.prepareStatement(sql); // 獲取元數(shù)據(jù) 準(zhǔn)備存儲(chǔ)所有列名的數(shù)組 ResultSetMetaData metaData = ps.getMetaData(); // 創(chuàng)建指定長度用于存儲(chǔ)列名的數(shù)組 String[] names = new String[metaData.getColumnCount()]; // 循環(huán)為names數(shù)組進(jìn)行賦值 for (int i = 0; i < names.length; i++) { names[i] = metaData.getColumnLabel(i + 1);// 獲取指定列名 } for (int i = 0; i < o.length; i++) { ps.setObject(i+1, o[i]); } // 執(zhí)行sql返回結(jié)果集 ResultSet rs = ps.executeQuery(); while (rs.next()) { // 每一行數(shù)據(jù)就是一個(gè)對象 // 使用反射創(chuàng)建對象 E obj = c.newInstance(); // 當(dāng)前行所有列名 在names數(shù)組中存儲(chǔ) // 循環(huán)names數(shù)組取出當(dāng)前行對應(yīng)數(shù)據(jù) for (String colname : names) { Object value = rs.getObject(colname);// 獲取列名對應(yīng)值 // 將值存入相應(yīng)對象 // 使用反射獲取類中同名的屬性對象 Field field = c.getDeclaredField(colname); // 私有屬性使用前必須賦權(quán) field.setAccessible(true); // 調(diào)用屬性對象的set方法為指定對象進(jìn)行賦值 field.set(obj, value); } // 列名循環(huán)結(jié)束后對應(yīng)對象屬性已經(jīng)全部進(jìn)行賦值 // 將對象存儲(chǔ)至集合中 list.add(obj); } } catch (Exception e) { e.printStackTrace(); return null; } return list; } }ublic class JDBCUtils { private static DataSource ds ; static { try { //1.加載配置文件 Properties pro = new Properties(); //使用ClassLoader加載配置文件,獲取字節(jié)輸入流 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; }
5、創(chuàng)建提供登錄方法的userdao
public class UserDao { //聲明JDBCTemplate對象共用 private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource()); /** * 登錄方法 * @param loginUser 只有用戶名和密碼 * @return user包含用戶全部數(shù)據(jù),沒有查詢到,返回null */ public User login(User loginUser){ try { //1.編寫sql String sql = "select * from user where username = ? and password = ?"; //2.調(diào)用query方法 User user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), loginUser.getUsername(), loginUser.getPassword()); return user; } catch (DataAccessException e) { e.printStackTrace(); return null; } } }
6、編寫登錄的servlet
@WebServlet("/loginServlet") public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1.設(shè)置編碼 req.setCharacterEncoding("utf-8"); //2.獲取請求參數(shù) String username = req.getParameter("username"); String password = req.getParameter("password"); //3.封裝user對象 User loginUser = new User(); loginUser.setUsername(username); loginUser.setPassword(password); //4.調(diào)用UserDao的login方法 UserDao dao = new UserDao(); User user = dao.login(loginUser); //5.判斷user if(user == null){ //登錄失敗 req.getRequestDispatcher("/failServlet").forward(req,resp); }else{ //登錄成功 //存儲(chǔ)數(shù)據(jù) req.setAttribute("user",user); //轉(zhuǎn)發(fā) req.getRequestDispatcher("/successServlet").forward(req,resp); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req,resp); } }
7、 編寫FailServlet和SuccessServlet類
public class SuccessServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //獲取request域中共享的user對象 User user = (User) request.getAttribute("user"); if(user != null){ //給頁面寫一句話 //設(shè)置編碼 response.setContentType("text/html;charset=utf-8"); //輸出 response.getWriter().write("登錄成功!"+user.getUsername()+",歡迎您"); } } @WebServlet("/failServlet") public class FailServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //給頁面寫一句話 //設(shè)置編碼 response.setContentType("text/html;charset=utf-8"); //輸出 response.getWriter().write("登錄失敗,用戶名或密碼錯(cuò)誤"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request,response); } }
到此這篇關(guān)于Servlet實(shí)現(xiàn)簡單的用戶登錄功能的文章就介紹到這了,更多相關(guān)Servlet實(shí)現(xiàn)用戶登錄功能內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java棧和基礎(chǔ)隊(duì)列的實(shí)現(xiàn)詳解
這篇文章主要介紹了Java數(shù)據(jù)結(jié)構(gòu)中的棧與隊(duì)列,在Java的時(shí)候,對于棧與隊(duì)列的應(yīng)用需要熟練的掌握,這樣才能夠確保Java學(xué)習(xí)時(shí)候能夠有扎實(shí)的基礎(chǔ)能力。本文小編就來詳細(xì)說說Java中的棧與隊(duì)列,需要的朋友可以參考一下2022-02-02JAVA實(shí)現(xiàn) springMVC方式的微信接入、實(shí)現(xiàn)消息自動(dòng)回復(fù)實(shí)例
本篇文章主要介紹了JAVA實(shí)現(xiàn) springMVC方式的微信接入、實(shí)現(xiàn)消息自動(dòng)回復(fù),這里整理了詳細(xì)的代碼,有需要的小伙伴可以參考下。2016-12-12每天練一練Java函數(shù)與算法Math函數(shù)總結(jié)與字符串轉(zhuǎn)換整數(shù)
這篇文章主要介紹了Java函數(shù)與算法Math函數(shù)總結(jié)與字符串轉(zhuǎn)換整數(shù),每天練一練,水平在不知不覺中提高,需要的朋友快過來看看吧2021-08-08全網(wǎng)最深分析SpringBoot MVC自動(dòng)配置失效的原因
這篇文章主要介紹了全網(wǎng)最深分析SpringBoot MVC自動(dòng)配置失效的原因,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07Java調(diào)用shell腳本解決傳參和權(quán)限問題的方法
今天小編就為大家分享一篇關(guān)于Java調(diào)用shell腳本解決傳參和權(quán)限問題的方法,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-03-03Spring中的攔截器HandlerInterceptor詳細(xì)解析
這篇文章主要介紹了Spring中的攔截器HandlerInterceptor詳細(xì)解析,HandlerInterceptor 是 Spring 框架提供的一個(gè)攔截器接口,用于在請求處理過程中攔截和處理請求,需要的朋友可以參考下2024-01-01