Jsp servlet Download lập trình web với jsp servlet

68 691 0
Jsp  servlet Download lập trình web với jsp servlet

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Mục lục Mục lục SERVLET javax.servlet.Servlet GenericServlet: HttpServlet .5 ServletRequest interface: ServletResponse interface HttpServletRequest interface: HttpServletResponse interface: .7 ServletConfig interface ServletContext Một ví dụ mã lệnh lắng nghe kiện (listener) RequestDispatcher Error log send error 10 Session Tracking – Lưu dấu session 10 Security Configuration 15 Applet 19 JSP - Java Server Pages 20 Giới thiệu JSP 20 Expresssion (biểu thức) 20 Scriptlets 20 Composed by HaiNT Declarations 21 Comments 21 Directives .21 Action 22 JSP EL Expressions .25 JSTL - Java Server Pages Standard Tag Library 26 I18N – Internationalisation (quốc tế hóa) 34 JSP custom tags .38 Phụ lục 48 Kết nối sở liệu .65 Composed by HaiNT SERVLET javax.servlet.Servlet Ta tạo servlet cách implements từ interface javax.servlet.Servlet Ví dụ: package com.test.servlet; import java.io.IOException; import java.io.PrintWriter; import import import import javax.servlet.ServletConfig; javax.servlet.ServletException; javax.servlet.ServletRequest; javax.servlet.ServletResponse; public class Servlet1 implements javax.servlet.Servlet { public void destroy() { } public ServletConfig getServletConfig() { return null; } public String getServletInfo() { return null; } public void init(ServletConfig config) throws ServletException { } public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { PrintWriter out = res.getWriter(); out.println("Day la servlet implements tu javax.servlet.Servlet"); } } Để chạy servlet ta cần bước sau: 1) Tạo file Servlet1.java với nội dung đặt package com.test.servlet 2) Khai báo web.xml Serv1 com.test.servlet.Servlet1 Composed by HaiNT Serv1 /Serv1 3) Chạy ứng dụng browser: http://localhost:8080/Demo/Serv1 GenericServlet: Bằng cách triển khai servlet việc ổn có vấn đề khó chịu là: 1) Như ta thấy file Servlet1 VD có phương thức public public public public public void destroy() ServletConfig getServletConfig() String getServletInfo() void init(ServletConfig config) void service(ServletRequest req, ServletResponse res) interface javax.servlet.Servlet bắt buộc phải triển khai phần lớn ta sử dụng phương thức (các phương thức khác để trống – ko làm cả) 2) Nếu ta muốn lưu giữ giá trị ServletConfig ta phải khai báo lưu giá trị thong qua phương thức init() bên Điều không khó trường hợp lại thêm bước phải thực ServletConfig servletConfig; public void init(ServletConfig config) throws ServletException { servletConfig = config; } Điều giải cách kế thừa từ GenericServlet Generic class thực thi tất phương thức, hầu hết để trống ServletConfig thực cách gọi getServletConfig() service(); Và ta tạo servlet kế thừa từ lớp trông đơn giản sáng sủa nhiều: package com.test.servlet; import javax.servlet.*; import java.io.IOException; import java.io.PrintWriter; public class Servlet1 extends javax.servlet.GenericServlet { Composed by HaiNT public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println("Day la servlet extends tu javax.servlet.GenericServlet"); } } HttpServlet Được extends (kế thừa) từ javax.servlet.GenericServlet thêm vào số phương thức Quan trọng method doxxx gọi Http request sử dụng là: doPost(), doGet(), doTrace(), doOption(), doDelete() Trong ta trọng vào doGet() doPost(); package com.test.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Servlet2 extends javax.servlet.http.HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println("Day la servlet extends tu javax.servlet.http.HttpServlet"); } } doPost() gọi method đặt form POST doGet method = GET Mặc định doGet() gọi VD: ServletRequest interface: ServletRequest interface cung cấp phương thức quan trọng cho phép bạn truy cập thong tin user Ví dụ, phương thức getParameterNames trả kiểu Enumeration chứa tập hợp tên parameter request thời Để lấy thông tin request ta sử dụng phương thức getParameter VD1: in danh sách tất Parameter request thời Enumeration parameters = request.getParameterNames(); while (parameters.hasMoreElements()) { String parameterName = (String) parameters.nextElement(); Composed by HaiNT System.out.println("Parameter Name: " + parameterName); System.out.println("Parameter Value: " + request.getParameter(parameterName)); } Hoặc ta lấy địa IP user = phương thức getRemoteAddress, tên máy = phương thức getRemoteHost Ta xem chạy thử tất phương thức ServletRequest bảng danh mục phương thức ServletRequest cuối tài liệu này: VD2: Lấy địa máy user out.println("UserRemoteHost:" + request.getRemoteHost()); ServletResponse interface Phương thức quan trọng java.io.PrintWriter, với đối tượng bạn in thẻ HTML liệu dạng text lên trình duyệt VD: PrintWriter out = response.getWriter(); out.println(""); …… out.println(""); HttpServletRequest interface: Interface kế thừa từ javax.servlet.ServletRequest để cung cấp thông tin request cho HTTP servlet HttpServletRequest thêm vào số phương thức mà ServletRequest ko có phục vụ cho HttpServlet VD: getAuthType(): trả kiểu xác thực để bảo vệ servlet Kết trả “BASIC”, “SSL” NULL servlet ko bảo vệ getContextPath(): trả phần URL context request (VD: /ServetDemo) Các phương thức HTTP based khác là: getCookies(), getHeaderxxx()… Tất phương thức interface liệt kê phần phụ lục Composed by HaiNT HttpServletResponse interface: Kế thừa từ ServletResponse interface để cung cấp chức đặc tả HTTP servlet việc gửi response Ví đụ phương thức truy cập HTTP headers cookies Tất phương thức interface liệt kê phần phụ lục ServletConfig interface Được sử dụng servlet container để truyền thông tin tới servlet khởi tạo VD: Sử dụng ServletContext để đọc tham số khởi tạo servlet 1) Các tham số khai báo web.xml sau: …… Serv1 com.test.servlet.Servlet1 adminEmail admin@aptech.com adminContactNumber 04298371237 ………… 2) Đọc tham số: package com.test.servlet; import import import import import import import java.io.IOException; java.io.PrintWriter; java.util.Enumeration; javax.servlet.ServletConfig; javax.servlet.ServletException; javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse; public class Servlet2 extends javax.servlet.http.HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); Composed by HaiNT ServletConfig sc = getServletConfig(); Enumeration parameters = sc.getInitParameterNames(); int count = 0; while (parameters.hasMoreElements()) { count++; String parameter = (String) parameters.nextElement(); out.println("Para name: " + parameter +" value: " + sc.getInitParameter(parameter)); } if (count == 0) out.println("Ko co parameter nao duoc cai dat web.xml cua servlet: " + sc.getServletName()); } } Tất phương thức interface liệt kê phần phụ lục ServletContext Định nghĩa tập hợp phương thức mà servlet sử dụng để giao tiếp với Servlet Container VD: setAttribute cho phép gọi thuộc tính tất servlet context package com.test.servlet; import import import import import javax.servlet.*; javax.servlet.http.HttpServlet; java.util.Enumeration; java.io.IOException; java.io.PrintWriter; public class Servlet1 extends HttpServlet { public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); ServletContext servletContext = getServletConfig().getServletContext(); Enumeration attributes = servletContext.getAttributeNames(); while (attributes.hasMoreElements()) { String attribute = (String) attributes.nextElement(); out.println("AttributeName: " + attribute); out.println("AttributeValue: "+ servletContext.getAttribute(attribute)); } out.println("MajorVersion: "+ servletContext.getMajorVersion()); out.println("MinorVersion: "+ servletContext.getMinorVersion()); out.println("Server info : " + servletContext.getServerInfo()); } } Composed by HaiNT Tất phương thức interface liệt kê phần phụ lục Một ví dụ mã lệnh lắng nghe kiện (listener) Mỗi kiện xảy thi phương thức tương ứng gọi package com.yourcompany.listener; import javax.servlet.ServletContextAttributeEvent; import javax.servlet.ServletContextAttributeListener; public class MyServletContextAttributeListener implements ServletContextAttributeListener { public void attributeAdded(ServletContextAttributeEvent scab) { System.out.println("An attribute was added to the " + "ServletContext object"); } public void attributeRemoved(ServletContextAttributeEvent scab) { System.out.println("An attribute was removed from " + "the ServletContext object"); } public void attributeReplaced(ServletContextAttributeEvent scab) { System.out.println("An attribute was replaced in the " + "ServletContext object"); } } Cấu hình web.xml com.yourcompany.listener.MyServletContextAttributeListener RequestDispatcher Gồm phương thức include (để lấy nội dung trang khác vào servlet thời Phương thức forward để chuyển đến URL khác Bạn lấy RequestDispatcher theo cách sau: • • Sử dụng phương thức getRequestDispatcher javax.servlet.ServletContext interface, tham số truyền vào chuỗi chứa đường dẫn tới tài nguyên khác Đường dẫn đường dẫn tương gốc ServletContext Sử dụng phương thức getRequestDispatcher javax.servlet.ServletRequest interface, tham số truyền vào chuỗi chứa đường dẫn tới tài nguyên khác Đường dẫn tương đối Composed by HaiNT với HTTP request hành Đường dẫn tương đối ko thể mở rộng servlet context hành • Sử dụng phương thức getNamedDispatcher javax.servlet.ServletContext interface, tham số truyền vào chuỗi chứa tên tài nguyên khác (VD: tên servlet định nghĩa web.xml) Sự khác biệt phương thức javax.servlet.Context.getRequestDispatcher() dùng đường dẫn tương đối request.getRequestDispatcher("/index.jsp").include(request, response); request.getRequestDispatcher("/index.jsp").forward(request, response); Error log send error log("Test log error", new Exception()); response.sendError(response.SC_BAD_GATEWAY); Session Tracking – Lưu dấu session Vì phương thức HTTP stateless (ko lưu thông tin lịch sử), điều ảnh hưởng sâu sắc đến lập trình ứng dụng web Có kỹ thuật để lưu dấu session: 1) URL rewritting – Thêm tham số vào cuối URL 2) Hidden fields – Sử dụng trường ẩn 3) Cookies – Sử dụng cookie để trao đổi liệu client server 4) Session objects – Sử dụng đối tượng có phạm vi (scope) session để truyền thông tin URL Rewritting: VD: Http://localhost:8080/Demo/test?x=abc&y=xyz Phần sau ?x=abc&y=xyz phần thêm vào để truyền parameter x y Để lấy giá trị ta dùng lệnh request.getParameter(“x”), tương tự với y Composed by HaiNT servlet name but before the query string, and translates it to a real path java.lang.String getQueryString() Returns the query string that is contained in the request URL after the path java.lang.String getRemoteUser() Returns the login of the user making this request, if the user has been authenticated, or null if the user has not been authenticated java.lang.String getRequestedSessionId() Returns the session ID specified by the client java.lang.String getRequestURI() Returns the part of this request's URL from the protocol name up to the query string in the first line of the HTTP request java.lang.String getServletPath() Returns the part of this request's URL that calls the servlet HttpSession getSession() Returns the current session associated with this request, or if the request does not have a session, creates one HttpSession getSession(boolean create) Returns the current HttpSession associated with this request or, if if there is no current session and create is true, returns a new session java.security.Principal getUserPrincipal() Returns a java.security.Principal object containing the name of the current authenticated user Composed by HaiNT boolean isRequestedSessionIdFromCookie() Checks whether the requested session ID came in as a cookie boolean isRequestedSessionIdFromUrl() Deprecated As of Version 2.1 of the Java Servlet API, use isRequestedSessionIdFromURL() instead boolean isRequestedSessionIdFromURL() Checks whether the requested session ID came in as part of the request URL boolean isRequestedSessionIdValid() Checks whether the requested session ID is still valid boolean isUserInRole(java.lang.String role) Returns a boolean indicating whether the authenticated user is included in the specified logical "role" Các số HttpServletResponse static int SC_ACCEPTED Status code (202) indicating that a request was accepted for processing, but was not completed static int SC_BAD_GATEWAY Status code (502) indicating that the HTTP server received an invalid response from a server it consulted when acting as a proxy or gateway static int SC_BAD_REQUEST Status code (400) indicating the request sent by the client was Composed by HaiNT syntactically incorrect static int SC_CONFLICT Status code (409) indicating that the request could not be completed due to a conflict with the current state of the resource static int SC_CONTINUE Status code (100) indicating the client can continue static int SC_CREATED Status code (201) indicating the request succeeded and created a new resource on the server static int SC_EXPECTATION_FAILED Status code (417) indicating that the server could not meet the expectation given in the Expect request header static int SC_FORBIDDEN Status code (403) indicating the server understood the request but refused to fulfill it static int SC_GATEWAY_TIMEOUT Status code (504) indicating that the server did not receive a timely response from the upstream server while acting as a gateway or proxy static int SC_GONE Status code (410) indicating that the resource is no longer available at the server and no forwarding address is known static int SC_HTTP_VERSION_NOT_SUPPORTED Status code (505) indicating that the server does not support or refuses to support the HTTP protocol version that was used in the request message static int SC_INTERNAL_SERVER_ERROR Status code (500) indicating an error inside the HTTP server which prevented it from fulfilling the request Composed by HaiNT static int SC_LENGTH_REQUIRED Status code (411) indicating that the request cannot be handled without a defined Content-Length static int SC_METHOD_NOT_ALLOWED Status code (405) indicating that the method specified in the Request-Line is not allowed for the resource identified by the RequestURI static int SC_MOVED_PERMANENTLY Status code (301) indicating that the resource has permanently moved to a new location, and that future references should use a new URI with their requests static int SC_MOVED_TEMPORARILY Status code (302) indicating that the resource has temporarily moved to another location, but that future references should still use the original URI to access the resource static int SC_MULTIPLE_CHOICES Status code (300) indicating that the requested resource corresponds to any one of a set of representations, each with its own specific location static int SC_NO_CONTENT Status code (204) indicating that the request succeeded but that there was no new information to return static int SC_NON_AUTHORITATIVE_INFORMATION Status code (203) indicating that the meta information presented by the client did not originate from the server static int SC_NOT_ACCEPTABLE Status code (406) indicating that the resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headerssent in the request Composed by HaiNT static int SC_NOT_FOUND Status code (404) indicating that the requested resource is not available static int SC_NOT_IMPLEMENTED Status code (501) indicating the HTTP server does not support the functionality needed to fulfill the request static int SC_NOT_MODIFIED Status code (304) indicating that a conditional GET operation found that the resource was available and not modified static int SC_OK Status code (200) indicating the request succeeded normally static int SC_PARTIAL_CONTENT Status code (206) indicating that the server has fulfilled the partial GET request for the resource static int SC_PAYMENT_REQUIRED Status code (402) reserved for future use static int SC_PRECONDITION_FAILED Status code (412) indicating that the precondition given in one or more of the request-header fields evaluated to false when it was tested on the server static int SC_PROXY_AUTHENTICATION_REQUIRED Status code (407) indicating that the client MUST first authenticate itself with the proxy static int SC_REQUEST_ENTITY_TOO_LARGE Status code (413) indicating that the server is refusing to process the request because the request entity is larger than the server is willing or able to process static int SC_REQUEST_TIMEOUT Status code (408) indicating that the client did not produce a Composed by HaiNT requestwithin the time that the server was prepared to wait static int SC_REQUEST_URI_TOO_LONG Status code (414) indicating that the server is refusing to service the request because the Request-URI is longer than the server is willing to interpret static int SC_REQUESTED_RANGE_NOT_SATISFIABLE Status code (416) indicating that the server cannot serve the requested byte range static int SC_RESET_CONTENT Status code (205) indicating that the agent SHOULD reset the document view which caused the request to be sent static int SC_SEE_OTHER Status code (303) indicating that the response to the request can be found under a different URI static int SC_SERVICE_UNAVAILABLE Status code (503) indicating that the HTTP server is temporarily overloaded, and unable to handle the request static int SC_SWITCHING_PROTOCOLS Status code (101) indicating the server is switching protocols according to Upgrade header static int SC_UNAUTHORIZED Status code (401) indicating that the request requires HTTP authentication static int SC_UNSUPPORTED_MEDIA_TYPE Status code (415) indicating that the server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method static int SC_USE_PROXY Status code (305) indicating that the requested resource MUST be Composed by HaiNT accessed through the proxy given by the Location field Các phương thức HttpServletResponse void addCookie(Cookie cookie) Adds the specified cookie to the response void addDateHeader(java.lang.String name, long date) Adds a response header with the given name and datevalue void addHeader(java.lang.String name, java.lang.String value) Adds a response header with the given name and value void addIntHeader(java.lang.String name, int value) Adds a response header with the given name and integer value boolean containsHeader(java.lang.String name) Returns a boolean indicating whether the named response header has already been set java.lang.String encodeRedirectUrl(java.lang.String url) Deprecated As of version 2.1, use encodeRedirectURL(String url) instead java.lang.String encodeRedirectURL(java.lang.String url) Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed, returns the URL unchanged java.lang.String encodeUrl(java.lang.String url) Deprecated As of version 2.1, use encodeURL(String url) instead java.lang.String encodeURL(java.lang.String url) Composed by HaiNT Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged void sendError(int sc) Sends an error response to the client using the specified status void sendError(int sc, java.lang.String msg) Sends an error response to the client using the specified status code and descriptive message void sendRedirect(java.lang.String location) Sends a temporary redirect response to the client using the specified redirect location URL void setDateHeader(java.lang.String name, long date) Sets a response header with the given name and datevalue void setHeader(java.lang.String name, java.lang.String value) Sets a response header with the given name and value void setIntHeader(java.lang.String name, int value) Sets a response header with the given name and integer value void setStatus(int sc) Sets the status code for this response void setStatus(int sc, java.lang.String sm) Deprecated As of version 2.1, due to ambiguous meaning of the message parameter To set a status code use setStatus(int), to send an error with a description use sendError(int, String) Sets the status code and message for this response Composed by HaiNT Các phương thức ServletConfig java.lang.String getInitParameter(java.lang.String name) Returns a String containing the value of the named initialization parameter, or null if the parameter does not exist java.util.Enumeration getInitParameterNames() Returns the names of the servlet's initialization parameters as an Enumeration of String objects, or an empty Enumeration if the servlet has no initialization parameters ServletContext getServletContext() Returns a reference to the ServletContext in which the servlet is executing java.lang.String getServletName() Returns the name of this servlet instance Các phương thức Servlet Context java.lang.Object getAttribute(java.lang.String name) Returns the servlet container attribute with the given name, or null if there is no attribute by that name java.util.Enumeration getAttributeNames() Returns an Enumeration containing the attribute names available within this servlet context ServletContext getContext(java.lang.String uripath) Returns a ServletContext object that corresponds to a specified URL on the server java.lang.String getInitParameter(java.lang.String name) Composed by HaiNT Returns a String containing the value of the named context-wide initialization parameter, or null if the parameter does not exist java.util.Enumeration getInitParameterNames() Returns the names of the context's initialization parameters as an Enumeration of String objects, or an empty Enumeration if the context has no initialization parameters int getMajorVersion() Returns the major version of the Java Servlet API that this servlet container supports java.lang.String getMimeType(java.lang.String file) Returns the MIME type of the specified file, or null if the MIME type is not known int getMinorVersion() Returns the minor version of the Servlet API that this servlet container supports RequestDispatcher getNamedDispatcher(java.lang.String name) Returns a RequestDispatcher object that acts as a wrapper for the named servlet java.lang.String getRealPath(java.lang.String path) Returns a String containing the real path for a given virtual path RequestDispatcher getRequestDispatcher(java.lang.String path) Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path java.net.URL getResource(java.lang.String path) Returns a URL to the resource that is mapped to a specified path Composed by HaiNT java.io.InputStream getResourceAsStream(java.lang.String path) Returns the resource located at the named path as an InputStream object java.lang.String getServerInfo() Returns the name and version of the servlet container on which the servlet is running Servlet getServlet(java.lang.String name) Deprecated As of Java Servlet API 2.1, with no direct replacement This method was originally defined to retrieve a servlet from a ServletContext In this version, this method always returns null and remains only to preserve binary compatibility This method will be permanently removed in a future version of the Java Servlet API In lieu of this method, servlets can share information using the ServletContext class and can perform shared business logic by invoking methods on common non-servlet classes java.util.Enumeration getServletNames() Deprecated As of Java Servlet API 2.1, with no replacement This method was originally defined to return an Enumeration of all the servlet names known to this context In this version, this method always returns an empty Enumeration and remains only to preserve binary compatibility This method will be permanently removed in a future version of the Java Servlet API java.util.Enumeration getServlets() Deprecated As of Java Servlet API 2.0, with no replacement This method was originally defined to return an Enumeration of all the servlets known to this servlet context In this version, this method always returns an empty enumeration and remains only to preserve binary compatibility This method will be permanently removed in a future version of the Java Servlet API void log(java.lang.Exception exception, java.lang.String msg) Composed by HaiNT Deprecated As of Java Servlet API 2.1, use log(String message, Throwable throwable) instead This method was originally defined to write an exception's stack trace and an explanatory error message to the servlet log file void log(java.lang.String msg) Writes the specified message to a servlet log file, usually an event log void log(java.lang.String message, java.lang.Throwable throwable) Writes an explanatory message and a stack trace for a given Throwable exception to the servlet log file void removeAttribute(java.lang.String name) Removes the attribute with the given name from the servlet context void setAttribute(java.lang.String name, java.lang.Object object) Binds an object to a given attribute name in this servlet context Kết nối sở liệu Trong mô hình MVC, model nhân chương trình, chứa business logic ứng dụng Một dự án quản lý tốt business logic View Controller Nhiệm vụ controller nhận request, xử lý request, gọi model để thực business logic chọn view để thị liệu Một ví dụ UserBusiness kết nối sqlserver 2005 Lớp DBConnection: Lớp có nhiệm vụ tạo connection đến Database private static String USER_NAME = "sa"; private static String PASSWORD = "123456"; private static String URL ="jdbc:sqlserver://localhost\\hai:1443;databaseName=test;"; Composed by HaiNT public static Connection getDBConnection() throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException { Connection = null; Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); = DriverManager.getConnection(URL, USER_NAME, PASSWORD); return con; } Trong Nếu SqlServer cài dạng instance server name có định dạng là: server-name\instance-name 1443 cổng TCP-IP cấu hình SqlServer (nếu công chưa khai báo phải khai báo connect được) Lớp UserBusiness Lớp chứa tất nghiệp vụ liên quan đến bảng User Database INSERT, SELECT, UPDATE, DELETE Ví dụ phương thức checkLogin gọi form login để kiểm tra user/password đăng nhập public static boolean checkLogin(User user) throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException { Connection conn = DBConnection.getDBConnection(); PreparedStatement st = conn.prepareStatement("SELECT * FROM [USER] WHERE username = ? AND password = ?"); int i = 0; st.setString(++i, user.getUsername()); st.setString(++i, Encryptation.crypt(user.getPassword())); } int count = 0; ResultSet rs = st.executeQuery(); while (rs.next()) { count++; } return count == ? true : false; Chú ý: Encryptation.crypt(user.getPassword() thực mã hóa password sử dụng MD5 128bit Về nguyên tắc, kể người lập trình thông tin nhạy cảm password khách hàng Vì password lưu Database phải mã hóa theo thuật toán đáng tin cậy Đoạn mã thực mã hóa sau: public static String crypt(String str) { if (str == null || str.length() == 0) { Composed by HaiNT throw new IllegalArgumentException("String to encrypt cannot be null or zero length"); } StringBuffer hexString = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] hash = md.digest(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) { hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); } else { hexString.append(Integer.toHexString(0xFF & hash[i])); } } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return hexString.toString(); } Có thể test kết cách thêm vào hàm main bên đây: public static void main(String[] a) { System.out.println(crypt("abc")); System.out.println(crypt("aaaaaaa")); } Lấy danh mục User để áp dụng vào User Search form chẳng hạn, ta sử dụng phương thức bên Phương thức cho search xác search gần tùy vào biến wholeWord truyền vào public static List searchUserByName(String username, boolean wholeWord) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException { String query = "SELECT username, role, description FROM [USER] WHERE username = ?"; String condition = username; ArrayList list = new ArrayList(); if (!wholeWord) { query = "SELECT username, role, description FROM [USER] WHERE username LIKE ?"; condition = username + "%"; } Connection conn = DBConnection.getDBConnection(); PreparedStatement st = conn.prepareStatement(query); st.setString(1, condition); ResultSet rs = st.executeQuery(); while (rs.next()) { User user = new User(); user.setUsername(rs.getString("username")); user.setRole(rs.getString("role")); user.setDescription(rs.getString("description")); Composed by HaiNT } list.add(user); } return list; JavaBean User.java Đóng vai trò DTO – Data Transfer Object Nó bao gồm thuộc tính để thể trường bảng User method get/set tương ứng: private private private private String String String String username; password; role; description; Gọi Business controller/servlet Thay gán hardcode: loginForm getUsername().equals("adam") && loginForm.gePassword().equals("12345678") Ta gọi UserBusiness để xác thực login sau: User user = new User(); user.setUsername(loginForm.getUsername()); user.setPassword(loginForm.gePassword()); if (checkLogin(user)) { //login successfully } else { //login failed, show error if necessary } Code sample Us erBus ines s r Composed by HaiNT [...]... TestFilter /FilteredServlet< /servlet- name> FilteredServlet< /servlet- name> com.aptech .servlet. FilteredServlet < /servlet- class> < /servlet> FilteredServlet< /servlet- name> /FilteredServlet < /servlet- mapping> < /web- app> Servlet package com.aptech .servlet; import import... update Bởi vậy, trình biên dịch sẽ so sánh timestamp của jsp servlet với jsp Nếu jsp mới hơn thì nó sẽ biên dịch lại Vì vậy bạn có thể cảm thấy mỗi khi vào trang jsp lần đầu bao giờ cũng thấy chậm hơn các lần sau Vòng đời của JSP (Life circle) 1) Translation: JSP được dịch thành JSP servlet với 3 phương thức: jspInit(), _jspService() và jspDestroy() VD: public class SimplePage _jsp extends HttpJspBase 2)... jsp: forward forward đến trang khác, có thể truyền tham số sử dụng thẻ jsp: param < /jsp: forward> Tạo success .jsp với nội dung như sau: Parameter a = jsp: plugin jsp: plugin action được dùng để tạo ra thể HTML hoặc chứa các cấu trúc tương ứng để chỉ định trình. .. javax .servlet. *; javax .servlet. http.*; import import import import import import javax .servlet. Filter; javax .servlet. FilterChain; javax .servlet. FilterConfig; javax .servlet. ServletException; javax .servlet. ServletRequest; javax .servlet. ServletResponse; public class TestFilter implements Filter { Composed by HaiNT private FilterConfig filterConfig = null; public TestFilter() { } public void doFilter(ServletRequest... cùng thu mục với TestApplet.html (Chọn TestApplet.java press F9) Applet kết nối với các đối tượng khác: 1) Applet có thể gọi và được gọi từ Javascript 2) Applet có thể kết nối với applet khác sử dụng javascript object (JSObject) 3) Applet có thể liên hệ với servlet Composed by HaiNT JSP - Java Server Pages Giới thiệu về JSP Jsp được sử dụng để tạo web động (dynamic web) , trong ứng dụng web đa tầng (multi... web đa tầng (multi layered web app), JSP được sử dụng làm tầng trình diễn Nó cũng có khả năng tương tác với tầng ứng dụng (application layer) và tạo ra web động dựa trên business logic Khi JSP được gọi lần đầu, nó được trình biên dịch phân tích và biên dịch thành servlet class Nếu biên dịch thành công, jsp servlet class này sẽ được nạp vào bộ nhớ Trong lần gọi tiếp theo, servlet clas này đã ở sẵn trong... được chỉ định < /jsp: params> Sorry, we are unable to start the Java plugin/> < /jsp: fallback> < /jsp: plugin> jsp: params Là thẻ con nằm trong jsp: plugin jsp: fallback Composed by HaiNT Là thẻ con nằm trong jsp: plugin dùng... 4) getServletContext(): trả về tham chiếu tới ServletContext của filter FilterChain interface Có thể sử dụng nhiều hơn 1 filter VD: 2 filter Filter và Filter1 áp dụng cho cùng 1 servlet FilteredServlet Filter FilteredServlet< /servlet- name> Filter1 FilteredServlet< /servlet- name>... filter"); } Web. xml Có 2 cách thiết lập mapping filter với servlet 1) Theo tên servlet (không có dấu “/”) TestFilter FilteredServlet< /servlet- name> 2) Theo URL pattern: TestFilter /FilteredServlet Dưới đây là khai báo (theo URL) trong web. xml... plugin JSP EL Expressions EL – Expression language (biểu thức) Disable EL Muốn vô hiệu hóa EL trong JSP ta sử dụng directives như sau: Or configure in web. xml * .jsp false < /jsp- property-group> < /jsp- config> Truy cập JavaBean Sử dụng JavaBean trong ví dụ về jsp: useBean (Calc.java)

Ngày đăng: 28/01/2016, 23:30

Từ khóa liên quan

Mục lục

  • Mục lục

  • javax.servlet.Servlet

  • GenericServlet:

  • HttpServlet

  • ServletRequest interface:

  • ServletResponse interface

  • HttpServletRequest interface:

  • HttpServletResponse interface:

  • ServletConfig interface

  • ServletContext

  • Một ví dụ về mã lệnh lắng nghe sự kiện (listener)

  • RequestDispatcher

  • Error log và send error

  • Session Tracking – Lưu dấu session

    • URL Rewritting:

    • Hidden fields:

    • Cookies:

    • Session objects:

    • Filter và Servlet communication

      • Filter interface

      • FilterConfig interface

      • FilterChain interface

Tài liệu cùng người dùng

Tài liệu liên quan