Xin chào mọi người trong bài viết này chúng ta sẽ tìm hiểu về Java Servlet, cách tốt nhất để hiểu nó là làm luôn một bài tập :D. Dưới đây là một bài tập Java Servlet rất hay mà mình sưu tập được, nó sẽ tổng hợp gần như đầy đủ kiến thức cơ bản của Java Servlet. Ok mình xin được bắt đầu bài viết.
Bài tập JAVA Servlet CRUD SQL Sever
Đề bài:
Hướng dẫn:
Trước tiền thì chúng ta sẽ create database thôi, mình sẽ không hướng dẫn bước này :D. Mọi người nhớ thiết lập username và password với mấy cái linh tinh trong SQL Server Configuration để có thể kết nối.
Tạo cấu trúc file như sau:
Ok bây giờ sẽ code, mình thì thường xử lý mấy thằng jsp trước, dưới đây là file jsp.
Login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <h1>Đăng nhập:</h1> <form action="MainPage" method="post"> <p> username: <input type="text" value="" name="username"> </p> <p> password: <input type="password" value="" name="password"> </p> <input type="submit" value="login"> </form> </body> </html>
Ai muốn đẹp hơn thì ấy thêm css vào :D.
editProfile.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="EditProfile" method="post"> <p>Mời nhập tên cần sửa:</p> <p> Fullname: <input type="text" name="fullname" value=""> </p> <input type="submit" value="Update"> </form> </body> </html>
Tiếp đến chúng ta sẽ khởi tạo một Class ConnecJDBC trong package connection
ConnecJDBC.java
package connection; import java.sql.Connection; import java.sql.DriverManager; public class ConnectJDBC { private static String url = "jdbc:sqlserver://localhost:1433;databaseName=DataXXX;"; private static String username = "sa"; private static String password = "123456"; public static Connection lol(){ try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); return DriverManager.getConnection(url, username, password); } catch (Exception e) { return null; } } }
Lưu ý username và password đặt khớp với SQL Server của bạn.
Bây giờ đến servlet, khởi tạo file MainPage tạo kết nối với sql kiểm tra username và password từ form, điều hướng đến các file còn lại.
MainPage.java
package servlets; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.RequestDispatcher; 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 connection.ConnectJDBC; /** * Servlet implementation class MainPage */ @WebServlet("/MainPage") public class MainPage extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public MainPage() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); Connection conn = ConnectJDBC.lol(); if (conn == null) { out.println("kết nối thất bại"); } else { try { String un = request.getParameter("username"); String pw = request.getParameter("password"); PreparedStatement pstmt = conn.prepareStatement("select * from [user] where username = ? and password = ?"); pstmt.setString(1, un); pstmt.setString(2, pw); ResultSet rs = pstmt.executeQuery(); if (rs.next()) { out.print("bạn đã đăng nhập thành công"); } else { out.print("<p style ='color: red'>Tài khoản không có trong database !</p>"); RequestDispatcher rd = request.getRequestDispatcher("login.jsp"); rd.include(request, response); } HttpSession ss = request.getSession(); ss.setAttribute("username",un); ss.setAttribute("password", pw); out.println("<br><a style='padding-right:20px' href='ViewResult'>Xem thong tin books</a> "); out.print( "<a href='EditProfile'>Sua thong tin dang nhap</a>"); out.print("<a href='Logout'>Dang xuat</a>"); } catch (SQLException e) { e.printStackTrace(); } } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
Với 3 file còn lại chúng ta thích tạo thằng nào trước cũng được :D.
ViewResult.jsp
package servlets; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; 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 connection.ConnectJDBC; /** * Servlet implementation class ViewResult */ @WebServlet("/ViewResult") public class ViewResult extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public ViewResult() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); Connection conn = ConnectJDBC.lol(); if (conn == null) { out.println("ket noi that bai"); } else { try { HttpSession ss = request.getSession(false); if (ss == null) { out.print("ban chua dang nhap"); response.sendRedirect("login.jsp"); } else { String un = (String) ss.getAttribute("username"); String pw = (String) ss.getAttribute("password"); PreparedStatement pstmt = conn.prepareStatement( "select * from books join [user] on books.id = [user].id where username = ? and password = ?"); pstmt.setString(1, un); pstmt.setString(2, pw); ResultSet rs = pstmt.executeQuery(); out.print("thong tin sach cua tai khoan: " + un + "<br>"); while (rs.next()) { out.print("user: " + rs.getString(1) + "---Ten sach: " + rs.getString(2) + "---so luong: " + rs.getString(3) + "---NamXB: " + rs.getString(4) + "---NhaXB: " + rs.getString(5)+"<br>"); } out.println("</table>"); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
EditproFile.jsp
package servlets; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; 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 connection.ConnectJDBC; /** * Servlet implementation class EditProfile */ @WebServlet("/EditProfile") public class EditProfile extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public EditProfile() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); Connection conn = ConnectJDBC.lol(); if(conn == null){ out.println("ket noi that bai"); }else{ try { // String un = request.getParameter("username"); String un = "xuanhanh"; PreparedStatement pstmt = conn.prepareStatement("update [user] set fullname = ? where username = ?"); pstmt.setString(1, "thai khac khanh"); pstmt.setString(2, un); pstmt.executeUpdate(); out.print("update thanh cong"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
Logout.jsp
package servlets; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; 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; /** * Servlet implementation class Logout */ @WebServlet("/Logout") public class Logout extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Logout() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession ss = request.getSession(false); if(ss != null){ ss.removeAttribute("username"); ss.removeAttribute("password"); ss.invalidate(); } RequestDispatcher rd = request.getRequestDispatcher("login.jsp"); rd.forward(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
Ok vậy là mình đã xử lý xong Bài tập JAVA Servlet CRUD SQL Sever , hi vọng là mọi người sẽ thích bài viết này.
Mọi người có thể tham khảo những bài viết khác tại đây
Để lại một bình luận