[JSP] Bài tập: Sử dụng các thẻ nhóm fmt trong JSTL để xây dựng các trang đa ngôn ngữ


Sử dụng các thẻ nhóm fmt trong JSTL để xây dựng các trang đa ngôn ngữ:
Trong bài này chúng ta cùng tìm hiểu một số thẻ của JSTL
1. Xác định ngôn ngữ, quốc gia: setLocale
2. Xác định các file tài nguyên giao diên: setBundle
3. Định dạng giá trị số, tiền tệ và thời gian: formatDate, formatNumber

Snap 2016-01-20 at 10.41.56
Snap 2016-01-20 at 10.43.13

Video thao tác

Mã nguồn tham khảo:

<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        <script>
            function doSubmit()
            {
                document.frm.submit();
            }
        </script>
    </head>

    <c:if test="${empty param.language}">
        <fmt:setLocale value="<%= request.getLocale().getDefault()%>"/>
    </c:if>
    <c:if test="${! empty param.language}">
        <fmt:setLocale value="${param.language}"/>
    </c:if>

    <fmt:setBundle basename="codes.gui" scope="session"/>

    <body>
        <h1><fmt:message key="title"/> </h1>
        <c:if test="${! empty param.btnAdd}">
            <!--check f and l input-->
            <c:if test="${! empty param.txtFirstName 
                          && ! empty param.txtLastName}">
                  <!--connect to db server-->
                  <sql:setDataSource var="conn" scope="session"
                                     user="sa" password="sa"
                                     url="jdbc:sqlserver://LAB03_GV\\MSSQLSERVER2012;databaseName=northwind;"
                                     driver="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>

                  <!--create insert command and execute it-->
                  <sql:update dataSource="${conn}" var="rowCount" scope="session"
                              sql="insert into employees(Firstname, LastName) values(?,?)">
                      <sql:param value="${param.txtFirstName}"/>
                      <sql:param value="${param.txtLastName}"/>
                  </sql:update>
                  <!--if add ok-->
                  <c:if test="${rowCount > 0}">
                      Employee Added<br/>
                      ${param.txtFirstName}
                  </c:if>
                  <!--Notify if can not add-->
                  <c:if test="${rowCount <= 0}">
                      Can not add this employee
                  </c:if>
            </c:if>
            <!--Display err if Firstname and lastname not valid-->
            <c:if test="${ empty param.txtFirstName 
                           || empty param.txtLastName}">
                  FirstName and LastName can not be null !!   
            </c:if>
        </c:if>

        <form method="POST" name="frm">
            <fmt:message key="firstname"/>:<br/>
            <input type="text" name="txtFirstName" value="" /><br/>
            <fmt:message key="lastname"/>:<br/>
            <input type="text" name="txtLastName" value="" /><br/>
            <input type="submit" value="<fmt:message key="add"/>" name="btnAdd" />


            <fieldset>
                <legend><fmt:message key="format"/></legend>
                <fmt:formatNumber type="currency" value="20000.02"/><br/>
                <fmt:formatDate type="both" dateStyle="full" timeStyle="full"
                value="<%= java.util.Calendar.getInstance().getTime()%>"/>

            </fieldset>
            <fieldset>
                <legend><fmt:message key="language"/></legend>
                <input type="radio" onchange="doSubmit();"
                       name="language" value="vi_VN"
                       <c:if test="${param.language=='vi_VN'}">checked</c:if>
                       />Tiếng Việt
                <input type="radio" onchange="doSubmit();"
                       name="language" value="en_US"
                       <c:if test="${param.language=='en_US'}">checked</c:if>
                       />English
                <input type="radio" onchange="doSubmit();"
                       name="language" value="th_TH"
                       <c:if test="${param.language=='th_TH'}">checked</c:if>
                       />Thai
            </fieldset>

        </form>
    </body>
</html>

Phần 1
Phần 2
Phần 3

JSP internationalization – localization with jstl


Demo cài đặt tính năng hỗ trợ quốc tế hóa và cục bộ hóa cho JSP

Trang tiếng việt và định dạng theo Việt Nam
jsp_1

Chọn ngôn ngữ khác trong submit lại và đổi giao diện
jsp_2

&lt;%@page contentType=&quot;text/html&quot;%&gt;
&lt;%@page pageEncoding=&quot;UTF-8&quot;%&gt;
&lt;%@ taglib prefix=&quot;c&quot; uri=&quot;http://java.sun.com/jstl/core_rt&quot; %&gt;
&lt;%@ taglib prefix=&quot;fmt&quot; uri=&quot;http://java.sun.com/jstl/fmt_rt&quot; %&gt;

&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot;     &quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;

&lt;script&gt;
    function ChangeValue()
    {
        document.frm.submit();
    }
&lt;/script&gt;
&lt;style&gt;
    #grp
    {
        width: 400px;
    }
&lt;/style&gt;

&lt;c:if test=&quot;${not empty param.language}&quot;&gt;
    &lt;fmt:setLocale value=&quot;${param.language}&quot; scope=&quot;session&quot;/&gt;
    &lt;c:set var= &quot;currLang&quot; value=&quot;${param.language}&quot; /&gt;
&lt;/c:if&gt;

&lt;c:if test=&quot;${empty param.language}&quot;&gt;
    &lt;fmt:setLocale value=&quot;&lt;%=request.getLocale().getLanguage()%&gt;&quot; scope=&quot;session&quot;/&gt;
    &lt;c:set var= &quot;currLang&quot; value=&quot;&lt;%=request.getLocale().getLanguage()%&gt;&quot; /&gt;
&lt;/c:if&gt;

&lt;fmt:setBundle basename=&quot;input&quot; scope=&quot;session&quot; /&gt;

&lt;html&gt;
    &lt;head&gt;
        &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;
        &lt;title&gt; &lt;fmt:message key=&quot;title&quot; /&gt; &lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
&lt;h1&gt;&lt;fmt:message key=&quot;title&quot; /&gt;&lt;/h1&gt;
&lt;form action=&quot;index.jsp&quot; method=&quot;post&quot; name=&quot;frm&quot;&gt;
&lt;table&gt;
&lt;tr&gt;
&lt;td&gt;&lt;fmt:message key=&quot;date&quot; /&gt;&lt;/td&gt;
&lt;td&gt;&lt;input type=&quot;text&quot; name=&quot;dates&quot;/&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;fmt:message key=&quot;number&quot; /&gt;&lt;/td&gt;
&lt;td&gt;&lt;input type=&quot;text&quot; name=&quot;number&quot;/&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;&lt;input type=&quot;submit&quot; value=&quot;&lt;fmt:message key=&quot;submit&quot; /&gt;&quot;&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;fieldset id=&quot;grp&quot;&gt;
&lt;legend&gt;Language&lt;/legend&gt;

                &lt;input type=&quot;radio&quot; name=&quot;language&quot; onchange=&quot;ChangeValue();&quot; value=&quot;vi&quot; &lt;c:if test=&quot;${currLang=='vi'}&quot;&gt;checked&lt;/c:if&gt; /&gt;Tieng Viet
                &lt;input type=&quot;radio&quot; name=&quot;language&quot; onchange=&quot;ChangeValue();&quot; value=&quot;en&quot; &lt;c:if test=&quot;${currLang=='en'}&quot;&gt;checked&lt;/c:if&gt; /&gt;English
                &lt;input type=&quot;radio&quot; name=&quot;language&quot; onchange=&quot;ChangeValue();&quot; value=&quot;de&quot; &lt;c:if test=&quot;${currLang=='de'}&quot;&gt;checked&lt;/c:if&gt; /&gt;german&lt;/fieldset&gt;
&lt;fieldset id=&quot;grp&quot;&gt;
&lt;legend&gt;Format&lt;/legend&gt;

                Định dạng ngày &lt;fmt:formatDate value=&quot;&lt;%=new java.util.Date()%&gt;&quot; dateStyle=&quot;full&quot; type=&quot;both&quot; /&gt;

                Number: &lt;fmt:formatNumber value=&quot;1000.9&quot; pattern=&quot;####.00&quot;/&gt;&lt;/fieldset&gt;
&lt;/form&gt;

    &lt;/body&gt;
&lt;/html&gt;

– Create properties file có tên input.properties
– Click chuột phải add locale thêm 02 ngôn ngữ tiếng Việt và Tiếng Anh
– Click chuột phải lên file input.properties chọn Open
– Click add new property như sau

jsp_3

Chúc các bạn thành công !

[JSP] Bài tập JSTL: core,query, update


Trong bài này chúng ta tiếp tục xây dụng trang danh sách và cập nhật

Trang danh sách hiển thị tất cả nội dung trong bảng Employees với ID >9, trên trang danh sách chứa liên kết tới trang thêm,hiệu chỉnh và có xác nhận trước khi xóa.

Thực hiện xây dựng nội dung trang danh sách như sau:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <a href="add.jsp">Add</a>
<h1>List!</h1>
<!--connect to db server-->
        <sql:setDataSource var="conn" scope="session"                            user="sa" password="sa"                            url="jdbc:sqlserver://LAB03_GV\\MSSQLSERVER2012;databaseName=northwind;"                            driver="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>

        <!--create delete command and execute it-->
        <c:if test="${! empty param.id}">
            <sql:update sql="delete From employees where employeeid =?"                          dataSource="${conn}"                         var="rowCount" scope="session">
                <!--delete employee <!--create selete command and execute it-id get from url param-->
                <sql:param value="${param.id}"/>
            </sql:update>
        </c:if>
        <!--refresh list-->
        <sql:query sql="Select FirstName, LastName,EmployeeID                     From employees where employeeid > 9"
                   dataSource="${conn}"
                   var="Employees" scope="session">
        </sql:query>
<table style="border: solid thin blue; width: 500px; margin-left: auto; margin-right: auto;">
<tr style="border: solid thin blue;">
                <!--show table header-->
                <c:forEach items="${Employees.columnNames}" var="colName">
<th>
                        <c:out value="${colName}"/></th>
</c:forEach>
<th>
                    Oper.</th>
</tr>
<!--show data-->
            <c:forEach items="${Employees.rowsByIndex}" var="Employee">
<tr>
                    <c:forEach items="${Employee}" var="cell">
<td>
                            <c:out value="${cell}"/></td>
</c:forEach>
<td>
                        <!--confirm delete-->
                        <a href="?id=${Employee[2]}" onclick="return confirm('Are you sure?');">Del</a> |
                        <a href="edit.jsp?id=${Employee[2]}&f=${Employee[0]}&l=${Employee[1]}">edit</a></td>
</tr>
</c:forEach></table>
</body>
</html>

Khi chọn một nhân viên để xóa danh sách sẽ chuyển qua trang edit.jsp như sau:

<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
<h1>Employee!</h1>
<c:if test="${! empty param.id}">
            <c:set var="id" value="${param.id}" scope="session"/>
        </c:if>

        <c:if test="${! empty param.btnSave}">
            <!--check f and l input-->
            <c:if test="${! empty param.txtFirstName                            && ! empty param.txtLastName}">
                  <!--connect to db server-->
                  <sql:setDataSource var="conn" scope="session"                                      user="sa" password="sa"                                      url="jdbc:sqlserver://LAB03_GV\\MSSQLSERVER2012;databaseName=northwind;"                                      driver="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>

                  <!--create insert command and execute it-->
                  <sql:update dataSource="${conn}" var="rowCount" scope="session"                               sql="update employees set Firstname=?, LastName=? where employeeid=?">
                      <sql:param value="${param.txtFirstName}"/>
                      <sql:param value="${param.txtLastName}"/>
                      <sql:param value="${sessionScope.id}"/>
                  </sql:update>
                  <!--if add ok-->
                  <c:if test="${rowCount > 0}">
                      <% response.sendRedirect("list.jsp");%>
                  </c:if>
                  <!--Notify if can not add-->
                  <c:if test="${rowCount <= 0}">
                      Can not update this employee
                  </c:if>
            </c:if>
            <!--Display err if Firstname and lastname not valid-->
            <c:if test="${ empty param.txtFirstName                             || empty param.txtLastName}">
                  FirstName and LastName can not be null !!
            </c:if>
        </c:if>
<form method="POST">
            Firstname:

            <input type="text" name="txtFirstName" value="${param.f}" />

            Lastname:

            <input type="text" name="txtLastName" value="${param.l}" />

            <input type="submit" value="Save" name="btnSave" />
        </form>

    </body>
</html>

Video tham khảo:

JSTL phần 1
JSTL phần 3

[JSP]: bài tập sử dụng JSTL căn bản


Trong bài này chúng ta sử dụng một số thẻ của JSTL để kiểm tra thao tác thực hiện, dữ liệu đầu vào và thêm vào CSDl.

Snap 2016-01-18 at 10.15.07 Snap 2016-01-18 at 10.15.19 Snap 2016-01-18 at 10.19.19

Mã nguồn tham khảo:

<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Employee!</h1>
    <c:if test="${! empty param.btnAdd}">
        <!--check f and l input-->
        <c:if test="${! empty param.txtFirstName 
                      && ! empty param.txtLastName}">
            <!--connect to db server-->
            <sql:setDataSource var="conn" scope="session"
                               user="sa" password="sa"
                               url="jdbc:sqlserver://LAB02_GV\\MSSQLSERVER2012;databaseName=northwind;"
                               driver="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>

            <!--create insert command and execute it-->
            <sql:update dataSource="${conn}" var="rowCount" scope="session"
                        sql="insert into employees(Firstname, LastName) values(?,?)">
                <sql:param value="${param.txtFirstName}"/>
                <sql:param value="${param.txtLastName}"/>
            </sql:update>
            <!--if add ok-->
            <c:if test="${rowCount > 0}">
                Employee Added<br/>
               ${param.txtFirstName}
            </c:if>
            <!--Notify if can not add-->
            <c:if test="${rowCount <= 0}">
                Can not add this employee
            </c:if>
        </c:if>
        <!--Display err if Firstname and lastname not valid-->
        <c:if test="${ empty param.txtFirstName 
                       || empty param.txtLastName}">
            FirstName and LastName can not be null !!   
        </c:if>
    </c:if>

    <form method="POST">
        Firstname:<br/>
        <input type="text" name="txtFirstName" value="" /><br/>
        Lastname:<br/>
        <input type="text" name="txtLastName" value="" /><br/>
        <input type="submit" value="Add" name="btnAdd" />
    </form>
</body>
</html>

Video tham khảo:

!!!

[JSP]-Bài tập jsp+el


Trong bài này chúng ta sủ dụng static function để giao tiếp với database, EL để kiểm tra điều kiện thực hiện và jsp expression để tạo session.

  • Tạo các hàm
  • đăng ký với webserver
  • sử dụng trên trang jsp

TAO CáC HàM


package codes;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 *
 * @author TEACHER
 */
public class Employee {

    static public int addNew(String firstName, String lastName) {
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
             Connection conn = DriverManager.getConnection(""
                     + "jdbc:sqlserver://172.16.160.54\\sql2008;"
                    + "databasename=northwind;", "sa", "sa");

            PreparedStatement comm = conn.prepareCall(""
                    + "Insert Into Employees(FirstName, LastName) "
                    + "Values(?,?)");

            comm.setString(1, firstName);
            comm.setString(2, lastName);

            return comm.executeUpdate();
        } catch (Exception ex) {
            return 0;
        }
    }
    
    static public String list() {
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            Connection conn = DriverManager.getConnection(""
                    + "jdbc:sqlserver://172.16.160.54\\sql2008;"
                    + "databasename=northwind;", "sa", "sa");

            PreparedStatement comm = conn.prepareCall(""
                    + "Select EmployeeID [Code], FirstName , LastName "
                    + "From Employees order by EmployeeID desc");

            ResultSet rs = comm.executeQuery();
            
            String str ="";
            
            while(rs.next())
            {
                str += "<br />Code: "+ rs.getString("Code") + " FullName: " + 
                    rs.getString("LastName") + " " + rs.getString("FirstName");
            }
            
            return str;
            
        } catch (Exception ex) {
            return "";
        }
    }
}

đăNG Ký

<function>
       <name>addNew</name>
       <function-class>codes.Employee</function-class>
       <function-signature>
           int addNew(java.lang.String, java.lang.String)
       </function-signature>
   </function>
   
    <function>
       <name>list</name>
       <function-class>codes.Employee</function-class>
       <function-signature>
           java.lang.String list()
       </function-signature>
   </function>

Gọi: Trang login.jsp

<%-- 
    Document   : login
    Created on : Aug 13, 2015, 7:47:26 AM
    Author     : TEACHER
--%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Login</h1>
        <c:if test="${!empty param.btnLogin}">
            <c:if test="${param.txtU == 'admin' && param.txtP == 'admin'}">
                <!--Create session-->
                <% session.setAttribute("login", "admin");%>
                <!--Check return required login page-->
                <c:if test="${! empty param.returnUrl}">
                    <!--replace current content by required login page-->
                    <jsp:forward page="${param.returnUrl}"/>
                </c:if>
                <!--replace current content by home page-->
                <jsp:forward page="home.jsp"/>
            </c:if>
        </c:if>

        <form method="POST">
            UserName<br/>
            <input type="text" name="txtU" value="" /><br/>
            Password<br/>
            <input type="password" name="txtP" value="" /><br/>
            <input type="submit" value="Login" name="btnLogin" />            
        </form>
    </body>
</html>

Trang index.jsp

<%-- 
    Document   : index
    Created on : Aug 13, 2015, 7:38:02 AM
    Author     : TEACHER
--%>

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<%@taglib prefix="my" uri="/WEB-INF/tlds/myLib" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <!--check login session-->
        <c:if test="${empty sessionScope.login}">
            <!--display login page -->
            <!-- add returnUrl param to login page -->
            <!--login.jsp?returnUrl=index.jsp-->
            <jsp:forward page="login.jsp">               
                <jsp:param name="returnUrl" value="index.jsp"/>
            </jsp:forward>
        </c:if>    

        <c:if test="${!empty param.btnAdd}">
            <!--display emp list if add ok-->
            <c:if test="${my:addNew(param.txtFirstName, param.txtLastName) == 1}">
                ${my:list()}
            </c:if>       
        </c:if>

        <h1>Add new record</h1>
        <form method="POST">
            FirstName<br/>
            <input type="text" name="txtFirstName" value="${param.txtFirstName}" /><br/>
            Lastname<br/>
            <input type="text" name="txtLastName" value="${param.txtLastName}" /><br/>
            <input type="submit" value="Add new" name="btnAdd" />            
        </form>
    </body>
</html>

Tham khảo các video ==>> https://www.youtube.com/playlist?list=PLXImJ6jTTEi4T-f1GiKY4NwTW3We6IYbY

[JSP] – Bài tập: Sử dụng EL và gọi static function bằng EL trên JSP


Mục tiêu:

  • Sử dụng EL trên trang jsp
  • Đăng ký sử dụng static function trên website
  • Gọi static funtion từ trang jsp

B1:

Tạo lớp java như sau:

package codes;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class staticFunctions {
    public static int add(int a, int b) {
        return a + b;
    }

    public static String row(int id) {
        try {
            String strRow = "";
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            Connection conn = DriverManager.getConnection(""
                 + "jdbc:sqlserver://localhost;database=northwind;user=sa;password=sa;");
            PreparedStatement comm = conn.prepareStatement(""
                    + "Select EmployeeID, FirstName, LastName "
                    + "From employees where employeeID=?");
            comm.setInt(1, id);
            ResultSet rs = comm.executeQuery();
            if (rs.next()) {
                strRow += "<tr>";
                    strRow += "<td>";
                        strRow += rs.getString("EmployeeID");
                    strRow += "</td>";
                    strRow += "<td>";
                        strRow += rs.getString("FirstName");
                    strRow += "</td>";
                    strRow += "<td>";
                        strRow += rs.getString("LastName");
                    strRow += "</td>";
                strRow += "</tr>";
            }
            return strRow;
        } catch (Exception ex) {
            Logger.getLogger(staticFunctions.class.getName()).log(Level.SEVERE, null, ex;
            return ex.toString();
        }
    }
}

B2:
Đăng ký static function với webserver
– Tạo file TLD (new -> file -> web -> Tag Library Descriptor)
– Hiệu chỉnh file như sau

<taglib version="2.1" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd">
    <tlib-version>1.0</tlib-version>
    <short-name>myfunction</short-name>
    <uri>/WEB-INF/tlds/myFunction</uri>
    <function>
        <name>add</name>
        <function-class>codes.staticFunctions</function-class>
        <function-signature>
               int add(int, int)
        </function-signature>
    </function>
    
    <function>
        <name>row</name>
        <function-class>codes.staticFunctions</function-class>
        <function-signature>
               String row(int)
        </function-signature>
    </function>
</taglib>

B3:
– Đăng ký sử dụng trên trang jsp
– Bổ sung thẻ sau vào trang jsp

<%@taglib prefix="fn" uri="/WEB-INF/tlds/myFunction" %>

– Hiệu chỉnh nội dung trang index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="fn" uri="/WEB-INF/tlds/myFunction" %>
<%@taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
<h1>Hello World!</h1>
        ${header}
<form action="" method="post">
            Frist:
            <input type="text" name="f" value="${param.f}" />
            Second:
            <input type="text" name="s" value="${param.s}" />
            <input type="submit" value="Add" />
        </form>
        <c:if test="${not empty param.f}">
            ${fn:add(param.f,param.s)}
        </c:if>
<table>
<tr>
<td>ID</td>
<td>FirstName</td>
<td>LastName</td>
                </tr>
                <c:forEach begin="1" end="9" var="i" step="2">
                    ${fn:row(i)}
                </c:forEach>
            </table>
    </body>
</html>

B4: chạy và kiểm tra kết quả:
p1

Video tham khảo –> 

Sử dụng Filter xây dựng cơ chế chứng thực tập trung cho web site jsp


mã nguồn tham khảo

Cấu trúc website:

  • RootFolder
    • Protected
      • Admin
        • backup.jsp
        • reset.jsp
      • User
        • home.jsp
        • order.jsp
    • Resources
  • Index.jsp
  • Login.jsp

Qui định rằng chỉ tài nguyên trong thư mục Protected là cần phải chứng thực trước khi sử dụng.

Bước 1: Tạo filter đón nhận tất cả các yêu cầu truy cập đến webserver

<filter>
<filter-name>Auth_Filter</filter-name>
<filter-class>codes.Auth_Filter</filter-class>
</filter>
<filter-mapping>
<filter-name>Auth_Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

Bước 2: Hiệu chỉnh lại theo tác kiểm tra người dùng trong hàm doFilter, với  các yêu cầu truy cập và tài nguyên cần bảo vệ thì chuyển đến trang chứng thực (login) sau đó quay lại tài nguyên mà người dùng đã yêu cầu. Trong ví dụ này chúng ta đánh dấu trạng thái đăng nhập bằng session login.

public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain)
        throws IOException, ServletException {
    RequestWrapper wrappedRequest = new RequestWrapper((HttpServletRequest) request);
    ResponseWrapper wrappedResponse = new ResponseWrapper((HttpServletResponse) response);
    doBeforeProcessing(wrappedRequest, wrappedResponse);
    Throwable problem = null;
    try {
        HttpServletRequest req = (HttpServletRequest) wrappedRequest;
        HttpServletResponse res = (HttpServletResponse) wrappedResponse;
        HttpSession session = req.getSession();
        String requestURL = req.getRequestURI();

        if (session.getAttribute("login") != null
                || requestURL.endsWith("login.jsp")
                || requestURL.indexOf("/action/") &amp;gt;= 0) {
            chain.doFilter(wrappedRequest, wrappedResponse);
        } else {
            if (requestURL.indexOf("/protected/") &amp;gt;= 0) {
                String loginURL = req.getScheme()+"://"+
                        req.getServerName()+":"+req.getServerPort()
                        +"/Lab04_Authenticate_UserRequest_TomcatUser/login.jsp";
                res.sendRedirect(loginURL+"?returnURL="+requestURL);
            }else
            {
                chain.doFilter(wrappedRequest, wrappedResponse);
            }
        }
    } catch (Throwable t) {
        problem = t;
        t.printStackTrace();
    }

    doAfterProcessing(wrappedRequest, wrappedResponse);

    if (problem != null) {
        if (problem instanceof ServletException) {
            throw (ServletException) problem;
        }
        if (problem instanceof IOException) {
            throw (IOException) problem;
        }
        sendProcessingError(problem, response);
    }
}

Bước 3: Xây dựng trang login.jsp như sau:
Trang login nhận được thông số nơi sẽ chuyến tiếp sau khi chứng thực do filter yêu cầu.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<% String url =""; if (request.getParameter("returnURL") != null) { url = "?returnURL="+request.getParameter("returnURL"); } %>
<h1>Login</h1>
<form action="action/Authentication<%=url%>" method="POST">
User:

<input type="text" name="txtUser" value="admin"/>

User:

<input type="password" name="txtPass" value="admin"/>

<input type="Submit" value="Login"/>
</form>

</body>
</html>

Nội dung Servlet Authentication như sau:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
if (request.getParameter("txtUser").equalsIgnoreCase("admin")) {
// thay bằng mã nguồn chứng thực với db
request.getSession().setAttribute("login", "admin");
if (request.getParameter("returnURL") != null) {
response.sendRedirect(request.getParameter("returnURL") + "");
} else {
response.sendRedirect("../index.jsp");
}
} else
//chứng thực sai sẽ làm lại
{
request.getRequestDispatcher("../login.jsp").forward(request, response);
}

} catch (Exception ex) {
System.out.print(ex.toString());
out.close();
}
}

Chi tiết các bước thực hiện