Blog cá nhân của Đức NT (GC00464)

Thứ Năm, 25 tháng 9, 2014

Custom Tag

23:01 Posted by Đức NT No comments

Tìm hiểu về Custom Tag


Như chúng ta được biết thì trong 1 số trang JSP đôi khi ta phải nhúng code Java, việc nhúng code java vào 1 trang JSP lại trở thành 1 vấn đề lớn. Việc đọc hiểu code sẽ trở nên rất khó khăn, thêm vào đó là vấn đề tái sử dụng cũng khó hơn. Sau đây ta cùng tìm hiểu kĩ hơn về Custom Tag:
  • Custom Tag cho phép lập trình viên nhúng các đoạn code java vào trang JSP
  • Cung cấp cơ chế để tái sử dụng và bao gói code, lệnh phức tạp trong JSP
  • Làm đơn giản hóa, tái sử dụng Java Code
  • JSP 1.0 không hỗ trợ Tag Libraries
  • JSP 1.1 hỗ trợ lưu trữ các custom tag của người dùng đã tạo trong JSP
  • Cấu trúc của custom tag trong jsp giống như XML Tag

Custom Tag giống như một thẻ HTML bình thường, có thể không có boby hoặc không.

Expression Language

19:45 Posted by Đức NT No comments

Tìm hiểu về Expression Language


1. Expression Language là gì?
- EL là một phần của đặc tả của JSTL 1.0, đi kèm với JSP 1.2 và có thể được sử dụng như các attribute của thẻ JSTL

2. Expression Language có tác dụng gì?
- để hiển thị thông tin, dữ liệu và thực thi các thao tác một cách đơn giản mà ẩn đi được những dòng mã Java
- hỗ trợ sử dụng các đối tượng và các mảng
- hỗ trợ cả các đối tượng ẩn

3. Sử dụng như thế nào?
- Cú pháp của Expression Language là : ${expression} .
- Hai biểu thức thông dụng nhất của EL là : Static text. (Text tĩnh) và Standard and Custom tags.

Demo Expression Language


Tạo mới một Project gồm 1 JSP Page là index.jsp và 1 Servlet SumServlet

Thay thế toàn bộ code trong index.jsp như sau:
 <html>  
   <head>  
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
     <title>Expression Languane</title>  
   </head>  
   <body>  
     <form action="sum">  
       <input type="text" name="number1" value="${number1}">  
       +  
       <input type="text" name="number2" value="${number2}">  
       <button>=</button>  
       ${sumValue}  
     </form>  
   </body>  
 </html>  

Tại SumServlet
 @WebServlet(urlPatterns = {"/sum"})  
 public class SumServlet extends HttpServlet {  
   @Override  
   protected void doGet(HttpServletRequest request, HttpServletResponse response)  
       throws ServletException, IOException {  
     HttpSession session = request.getSession();  
 //    session.removeAttribute("number1");  
 //    session.removeAttribute("number2");  
 //    session.removeAttribute("sumValue");  
     int number1 = Integer.parseInt(request.getParameter("number1"));  
     int number2 = Integer.parseInt(request.getParameter("number2"));  
     int value = number1 + number2;  
     session.setAttribute("number1", number1);  
     session.setAttribute("number2", number2);  
     session.setAttribute("sumValue", value);  
     response.sendRedirect("index.jsp");  
   }  
   @Override  
   public String getServletInfo() {  
     return "Short description";  
   }  
 }  

Kết quả

Chạy Project

Nhập 2 số cần tính toán và nhận kết quả


Ở demo này mình dùng ServletSession để tính toán và lưu kết quả, bạn có thể dùng ${param} (một Expression Language khác) để làm ví dụ trên đơn giản hơn. Theo dõi video sau đây: youtu.be/SXqFtDSba9w

Demo Java Bean

18:59 Posted by Đức NT No comments
Java Bean là một class Java, nó được tạo ra để giảm thiểu sự dư thừa code , nên ta có thể tăng tính dùng lại của 1 bean class. Bạn có thể dùng ở nhiều nơi : HTML Form, Java mail API và trong kết nối database. Theo dõi Demo bên dưới:

Tạo một Java Class "NameHandler.java" nội dung như bên dưới

 package org.mypackage.hello;  
 /**  
  *  
  * @author nbuser  
  */  
 public class NameHandler {  
   private String name;  
   /** Creates a new instance of NameHandler */  
   public NameHandler() {  
     name = null;  
   }  
   public String getName() {  
     return name;  
   }  
   public void setName(String name) {  
     this.name = name;  
   }  
 }  

Tại trang index.jsp

 <html>  
   <head>  
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
     <title>JSP Page</title>  
   </head>  
   <body>  
     <h1>Entry Form</h1>  
     <form name="Name Input Form" action="response.jsp">  
       Enter your name:  
       <input type="text" name="name" />  
       <input type="submit" value="OK" />  
     </form>  
   </body>  
 </html>  

Tại trang respone.jsp

 <body>  
   <jsp:useBean id="mybean" scope="session" class="org.mypackage.hello.NameHandler" />  
   <jsp:setProperty name="mybean" property="name" />  
   <h1>Hello, <jsp:getProperty name="mybean" property="name" />!</h1>  
 </body>  


Kết quả

Chạy Project, trang index.jsp sẽ được khởi chạy mặc định.

Thứ Tư, 24 tháng 9, 2014

Implicit Objects

20:07 Posted by Đức NT No comments
JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer can call them directly without being explicitly declared. JSP Implicit Objects are also called pre-defined variables.

JSP supports nine Implicit Objects which are listed below:
Object Description
requestThis is the HttpServletRequest object associated with the request.
responseThis is the HttpServletResponse object associated with the response to the client.
outThis is the PrintWriter object used to send output to the client.
sessionThis is the HttpSession object associated with the request.
applicationThis is the ServletContext object associated with application context.
configThis is the ServletConfig object associated with the page.
pageContextThis encapsulates use of server-specific features like higher performance JspWriters.
pageThis is simply a synonym for this, and is used to call the methods defined by the translated servlet class.
ExceptionThe Exception object allows the exception data to be accessed by designated JSP.

The request Object:

The request object is an instance of a javax.servlet.http.HttpServletRequest object. Each time a client requests a page the JSP engine creates a new object to represent that request.

The request object provides methods to get HTTP header information including form data, cookies, HTTP methods etc.

The response Object:
The response object is an instance of a javax.servlet.http.HttpServletResponse object. Just as the server creates the request object, it also creates an object to represent the response to the client.

The response object also defines the interfaces that deal with creating new HTTP headers. Through this object the JSP programmer can add new cookies or date stamps, HTTP status codes etc.

The out Object:

The out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is used to send content in a response.

The initial JspWriter object is instantiated differently depending on whether the page is buffered or not. Buffering can be easily turned off by using the buffered='false' attribute of the page directive.

The JspWriter object contains most of the same methods as the java.io.PrintWriter class. However, JspWriter has some additional methods designed to deal with buffering. Unlike the PrintWriter object, JspWriter throws IOExceptions.

Following are the important methods which we would use to write boolean char, int, double, object, String etc.

Method Description
out.print(dataType dt)Print a data type value
out.println(dataType dt)Print a data type value then terminate the line with new line character.
out.flush()Flush the stream.

The session Object:

The session object is an instance of javax.servlet.http.HttpSession and behaves exactly the same way that session objects behave under Java Servlets.

The session object is used to track client session between client requests.

The application Object:

The application object is direct wrapper around the ServletContext object for the generated Servlet and in reality an instance of a javax.servlet.ServletContext object.

This object is a representation of the JSP page through its entire lifecycle. This object is created when the JSP page is initialized and will be removed when the JSP page is removed by the jspDestroy() method.

By adding an attribute to application, you can ensure that all JSP files that make up your web application have access to it.

The config Object:

The config object is an instantiation of javax.servlet.ServletConfig and is a direct wrapper around the ServletConfig object for the generated servlet.

This object allows the JSP programmer access to the Servlet or JSP engine initialization parameters such as the paths or file locations etc.

The following config method is the only one you might ever use, and its usage is trivial:
 config.getServletName();  
This returns the servlet name, which is the string contained in the element defined in the WEB-INF\web.xml file


The pageContext Object:

The pageContext object is an instance of a javax.servlet.jsp.PageContext object. The pageContext object is used to represent the entire JSP page.

This object is intended as a means to access information about the page while avoiding most of the implementation details.

This object stores references to the request and response objects for each request. The application, config, session, and out objects are derived by accessing attributes of this object.

The pageContext object also contains information about the directives issued to the JSP page, including the buffering information, the errorPageURL, and page scope.

The PageContext class defines several fields, including PAGE_SCOPE, REQUEST_SCOPE, SESSION_SCOPE, and APPLICATION_SCOPE, which identify the four scopes. It also supports more than 40 methods, about half of which are inherited from the javax.servlet.jsp. JspContext class.

One of the important methods is removeAttribute, which accepts either one or two arguments. For example, pageContext.removeAttribute ("attrName") removes the attribute from all scopes, while the following code only removes it from the page scope:
 pageContext.removeAttribute("attrName", PAGE_SCOPE);  

The page Object:

This object is an actual reference to the instance of the page. It can be thought of as an object that represents the entire JSP page.

The page object is really a direct synonym for the this object.

The exception Object:
The exception object is a wrapper containing the exception thrown from the previous page. It is typically used to generate an appropriate response to the error condition.

Demo

Create 3 JSP pages is index.jsp, save.jsp and resutl.jsp

Code in index.jsp
 <%@page contentType="text/html" pageEncoding="UTF-8"%>  
 <!DOCTYPE html>  
 <html>  
   <head>  
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
     <title>Implitcit Objects</title>  
   </head>  
   <body>  
     <form action="save.jsp">  
       <input type="text" name="name"><input type="submit">  
     </form>  
   </body>  
 </html>  

Code in save.jsp
 <%@page contentType="text/html" pageEncoding="UTF-8"%>  
 <!DOCTYPE html>  
 <html>  
   <head>  
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
     <title>Save</title>  
   </head>  
   <body>  
     <%   
       String name = request.getParameter("name");  
       session.setAttribute("name", name);  
     %>  
     <a href="resutl.jsp">Result</a>  
   </body>  
 </html>  

Code in result.jsp
 <%@page contentType="text/html" pageEncoding="UTF-8"%>  
 <!DOCTYPE html>  
 <html>  
   <head>  
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
     <title>Resutl</title>  
   </head>  
   <body>  
     Hello, <% out.print(session.getAttribute("name")); %>  
   </body>  
 </html>  


Run project

Input your name:

Click "resutl" to see result

Resutl

Build web application using JDBC

19:44 Posted by Đức NT No comments
1. JDBC là gì?
JDBC là viết tắt của “Java DataBase Connectivity”. Nó là một API (Application Programming Interface) có chứa một tập hợp các lớp, các giao diện Java và các thông báo lỗi ngoại lệ nằm trong cùng một đặc tả mà theo đó cả các công ty sản xuất JDBC driver cũng như các nhà phát triển JDBC đều phải tuân thủ chặt chẽ khi phát triển ứng dụng.

How to Make Apple Butter

If you enjoy this tasty twist on jam, but can’t find it available commercially in your area, try making apple butter yourself. It used to be messy and extremely time-consuming to prepare, but if you use a slow cooker it's much easier to make, so you can be eating apple butter in a day!

Ingredients

  • 4 1/2 lbs. cooking apples, washed and quartered
  • 4 cups white sugar
  • 1/3 cup of apple cider
  • 1/2 teaspoon powdered cinnamon
  • 1/2 teaspoon ground nutmeg

Steps (click to watch video)


1. Quarter the apples; peel them first if you prefer them without the skin. Put the chopped apples into the slow cooker, then slowly add the sugar. Stir to coat.

How to Short Sell

When most people buy an investment like a stock, they're hoping for the stock price to go up. If the stock price is lower when they buy the stock than it is when they sell it, they've earned a profit. This process is called "going long." Selling a stock short, or "shorting" as it's colloquially known, is the opposite. Instead of betting that the price of an investment is going to go up in the future, people who short are betting that the price of an investment is going to go down in the future. How do you do this, and how do you make money doing this? Read this tutorial to find out just how to sell short.

Method 1 of 3: Understanding the Theory