[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

Advertisements

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 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

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

 

JSF and Strut questions and anwsers


  1. Struts was first developed
    1. in an online exchange between several open source developers
    2. over a long holiday weekend(TRUE)
    3. as a commercial package
  2. The reset method on an ActionForm
    1. Sets all properties to their initial value
    2. Sets all properties to null
    3. Repopulates all properties from the request parameters
    4. None of the above(TRUE)
  3. Each Struts Action element is uniquely identified by its
    1. Input attribute
    2. Name attribute
    3. Page attribute
    4. Path attribute(TRUE)
  4. The name of the Application Resources file is set by the servlet init-param named
    1. Application(TRUE)
    2. Resources
    3. ApplicationResources
    4. messages
  5. The validating init-param of the ActionServlet is used to
    1. Bypass calls to the ActionForm validate method
    2. Bypass validation of the Struts configuration file(TRUE)
    3. Generate an error message if an unknown message key is used
  6. To specify an ActionMapping to use when a request doesn’t match any other mapping, you can
    1. Use an asterisk for the path property
    2. Set the “default” property of the mapping to “true”
    3. Set the “unknown” property of the mapping to “true”(TRUE)
    4. Set the “missing” init-param of the ActionServlet to the mapping’s path
  7. In Struts 1.1, you can change how Struts populates a form by
    1. Overriding the populate method of the ActionForm
    2. Overriding the processPopulate method of the Request Processor(TRUE)
    3. Overriding the populateBean method of the ActionMapping
  8. The < bean:write > tag is:
    1. Always converts HTML markup to entity equivalents, like &lt;
    2. Never converts HTML markup to entity equivalents
    3. Converts markup when filter=true(TRUE)
    4. Converts markup when markup=false
  9. From a MVC perspective, Struts provides the
    1. Model
    2. View
    3. Controller(TRUE)
  10. Struts Framework is well suited for application of ____ size.
    1. Small
    2. Any(TRUE)
    3. Average
    4. Very small
  11. MVC is :
    1. Mode-View-Controller
    2. Model-View-Converter
    3. Model-Viewer-Controller
    4. Model-View-Controller(TRUE)
  12. What is Action Class ?
    1. The Action Class is a wrapper around the business logic and is a part of Model(TRUE)
    2. Nothing special about the Action class
    3. Action Class is a wrapper around the Internet logic
    4. None of the above
  13. An ActionForm is a JavaBean which extends the:
    1. struts.action.ActionForm(TRUE)
    2. apache.struts.action.ActionForm
    3. action.ActionForm
    4. ActionForm
  14. Use the following command (tag) to display the error on the jsp page:
    1. < html:errors/ >
    2. < html:errors/ >(TRUE)
    3. < errors / >
    4. < html=errors/ >
  15. What of following features can _not_ be configured in the JSF configuration file?
    1. Navigation rules
    2. Managed Beans
    3. Custom components
    4. Application Name(TRUE)
  16. In JSF – Which tag must enclose all other tags on a Faces JSP page?
    1. < f:faces >
    2. < f:view >(TRUE)
    3. < h:jsf >
    4. < h:view >
  17. In JSF – Why does the HtmlForm component render a <hidden> field?
    1. Command events
    2. Submit events
    3. Action events(TRUE)
    4. Click events
  18. In JSF – Why does the HtmlForm component render a < hidden > field
    1. To keep track of its identifier
    2. To keep track of the components in tree
    3. To set its submitted property(TRUE)
    4. For JavaScript integration
  19. What are the main features of JSF ? ( Choose many )
    1. Page navigation specification(TRUE)
    2. Standard user interface components like input fields, buttons, and links(TRUE)
    3. Read xml file
    4. Easy error handling(TRUE)
  20. In JSF – Components can be nested within another component
    1. True(TRUE)
    2. False

Next 20 –>

  1. Which one of the following tags renders a single radio button?
    1. <h:selectBooleanCheckbox>
    2. <h:selectOneRadio>
    3. <h:selectOneCheckbox>
    4. <h:selectManyCheckbox>
  2. The tag library that allows you to keep common content in a Web application, at a common location and insert it where necessary is
    1. HTML tag library
    2. Logic tag library
    3. Bean tag library
    4. Template tag library
  3. The tag used to create an input field that is not visible to the user is _______________.
    1. <h:inputSecret>
    2. <h:inputHidden>
    3. <h:inputPassword>
    4. <h:inputText>
  4. ______________ class is used to uniquely represent a locale of a country.
    1. faces.render.Locale
    2. util.Locale
    3. faces.context.Locale
  5. Creating and using a custom converter requires implementing _____________ and _____________ methods provided by Converter interface.
    1. getObject()
    2. getAsObject()
    3. getAsString()
    4. getString()
  6. It is possible to have more than one Faces configuration file.
    1. True
    2. False
  7. ________ classplays the role of the controller and is responsible for handling all the requests.
    1. Action
    2. ActionServlet
    3. RequestProcessor
    4. Plugin
  8. The tag used to create a text box to accept a password is _______________.
    1. <h:inputSecret>
    2. <h:inputHidden>
    3. <h:inputPassword>
    4. <h:inputText>
  9. Which of the following UI Component acts as a container for all other components?
    1. UIParameter
    2. UIForm
    3. UIViewRoot
    4. UISelectItem
  10. Which of the following statements are true about the reset() method of ActionForm class?
    1. Sets all properties to their initial value
    2. Sets all properties to null
    3. Repopulates all properties from the request parameters
    4. None of the above
  11. _______________________ declares a set of rules that define the next view for the user based on his/her actions.
    1. JSF Navigation Model
    2. JSF View Model
    3. JSF Forward Model
    4. JSF Model
  12. The file that provides a set of utility classes and interfaces that handle data structures used to store data in an application is _________.
    1. commons-beanutils.jar
    2. commons-collections.jar
    3. commons-digester.jar
    4. commons-logging.jar
  13. Which method of ActionServlet class maps the servlet name to a URL in the Web application?
    1. init()
    2. save()
    3. addmapping()
    4. addServletMapping()
  14. The JSF tag used to show all the error messages in a JSP page is ____________.
    1. <h:message>
    2. <h:messages>
    3. <f:messages>
    4. <f:message>
  15. Which one of the following JSF expressions, references an application’s context path?
    1. #{contextPath}
    2. #{requestContextPath}
    3. #{facesContext.externalContext.requestContextPath}
    4. ${request.contextPath}
  16. Each Struts Action element is uniquely identified by its __________.
    1. Input attribute
    2. Name attribute
    3. Path attribute
    4. Page attribute
  17. Which one of the following events is generated by the <h:commandButton> tag of JSF ?
    1. Command event
    2. Submit event
    3. Action event
    4. Click event
  18. Which one of the following Action classes provides a mechanism for switching between modules in a modularized Struts application?
    1. SwitchAction
    2. DispatchAction
    3. IncludeAction
    4. LocaleAction
  19. The Struts class which handles the actual execution of the request is ________.
    1. ActionForward
    2. Action
    3. RequestProcessor
    4. ActionServlet
  20. The Struts tag used to display the error in the JSP page is ______________.
    1. <html:errors/>
    2. <html:errors>
    3. <errors>
    4. <html=errors>

Next 13 (sun)

  1. Struts was first developed
    1. in an online exchange between several open source developers
    2. over a long holiday weekend
    3. as a commercial package
  2. The reset method on an ActionForm
    1. Sets all properties to their initial value
    2. Sets all properties to null
    3. Repopulates all properties from the request parameters
    4. None of the above (do nothing)
  3. Each Struts Action element is uniquely identified by its
    1. Input attribute
    2. Name attribute
    3. Page attribute
    4. Path attribute
  4. The name of the Application Resources file is set by the servlet init-param named
    1. application
    2. resources
    3. ApplicationResources
    4. messages
  5. The validating init-param of the ActionServlet is used to
    1. Bypass calls to the ActionForm validate method
    2. Bypass validation of the Struts configuration file
    3. Generate an error message if an unknown message key is used
  6. To specify an ActionMapping to use when a request doesn’t match any other mapping, you can
    1. Use an asterisk for the path property
    2. Set the “default” property of the mapping to “true”
    3. Set the “unknown” property of the mapping to “true”
    4. Set the “missing” init-param of the ActionServlet to the mapping’s path
  7. If you have created a custom ActionMapping subclass with the property “service”, you can initialize the value to “selectRecord” using
    1. <init-property name=”service” value=”selectRecord”/>
    2. <set-property property=”service” value=”selectRecord”/>
    3. <put-field key=”service” content=”selectRecord”/>
  8. In Struts 1.1, you can change how Struts populates a form by
    1. Overriding the populate method of the ActionForm
    2. Overriding the processPopulate method of the Request Processor
    3. Overriding the populateBean method of the ActionMapping
  9. The <bean:write> tag is:
    1. Always converts HTML markup to entity equivalents, like &lt;
    2. Never converts HTML markup to entity equivalents
    3. Converts markup when filter=true
    4. Converts markup when markup=false
  10. To prevent possible security issues with the <html:password> tag, you should
    1. Call the reset method if validation fails
    2. Set the tag’s redisplay property to false
    3. Set the tag’s reset property to false
    4. Use a plain html tag instead
  11. To localize Tiles, you can
    1. Create separate configuration files for each locale
    2. Specify an locale for a definition
    3. Either A or B
  12. To localize Validator forms, you can
    1. Create separate configuration files for each locale
    2. Specify a locale for a form-set
    3. Either A or B
  13. From a MVC perspective, Struts provides the
    1. Model
    2. View
    3. Controller

Next 20 –>> 20 question_3

Strut2 ví dụ căn bản


 

Basic exercise:

Using Strut 2 to develop login application.

clip_image002

If login fail

clip_image004

If login successful

clip_image006

1. Create Java web application base on Strut2 framework as figure below.

clip_image008

2. Create some file as structure

clip_image009

3. Open struts.xml and modify as

clip_image011

4. Open appResources: create some keys

clip_image012

5. Open Login class and add new code as

clip_image014

6. Generate getter/setter for two field above

clip_image016

7. Next, design login page

clip_image018

8. Next, index.jsp page

clip_image020

9. Next, error.jsp page

clip_image022

10. Now, deploy and run login.jsp page

Strut2-Validation

Using Strut validate input data

clip_image023

If input data invalid

clip_image024

If input data is valid

clip_image025

clip_image027

1. Design customer.jsp as

clip_image029

2. Add some new key to appResources

clip_image030

3. Assign Customer action in struts.xml

clip_image031

4. Add new class with name “Customer” into codes package

clip_image032

5. Generate setter and getter for 4 fields

6. Add new file “Customer-validation.xml” into package

clip_image033

Now, re-deploy and run

Using annotations

All action class must be inside actions package

clip_image034

Strut Controller now change to org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter

1 <filter> 2 <filter-name>struts2</filter-name> 3 <filter-class> 4 org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter 5 </filter-class> 6 <init-param> 7 <param-name>actionPackages</param-name> 8 <param-value>codes</param-value> 9 </init-param> 10 </filter> 11 <filter-mapping> 12 <filter-name>struts2</filter-name> 13 <url-pattern>/*</url-pattern> 14 </filter-mapping>

If your Action extend from ActionSupport, then your Action class name has no rule required.

Ex: Login action beloved

Otherwise, action class name must end with Action string

Ex: account action

1 @Namespace("/") 2 @ResultPath(value = "/") 3 @Results({ 4 @Result(name = "success", location = "index.jsp"), 5 @Result(name = "error", location = "error.jsp")} 6 ) 7 public class accountAction { 8 @Action(value="account") 9 public String execute() throws Exception { 10 if ("nvmit".equals(getName())) { 11 return SUCCESS; 12 } else { 13 return ERROR; 14 } 15 } 16 private String name =""; 17 public String getName() { 18 return name; 19 } 20 public void setName(String name) { 21 this.name = name; 22 } 23 }

@Namespace Annotation in Struts 2

@Namespace is used at class level or package level. This helps to change the namespace for action class. While accessing or calling action class, it hides package structure. When namespace is applied at package level, all the action of that package gets that namespace as default.

1 @Results({ 2 @Result(name = "SUCCESS", location = "/user/index.jsp"), 3 @Result(name = "ERROR", location = "/user/error.jsp") 4 }) 5 @Namespaces( 6 @Namespace("/user") 7 ) 8 public class Login extends ActionSupport{ 9 @Action(value = "/user/login") 10 public String execute() throws Exception { 11 if ("nvmit".equals(getName()) && "nvmit".equals(getPwd())) { 12 return "SUCCESS"; 13 } else { 14 return "ERROR"; 15 } 16 } 17 18 //Java Bean to hold the form parameters 19 private String name; 20 private String pwd; 21 22 public String getName() { 23 return name; 24 } 25 26 public void setName(String name) { 27 this.name = name; 28 } 29 30 public String getPwd() { 31 return pwd; 32 } 33 34 public void setPwd(String pwd) { 35 this.pwd = pwd; 36 } 37 } 38

The above class can be accessed by @Namespace + @Action that is /user/form
http://localhost:8080/Struts2Demo-1/user/form

Create Project with beloved structure

clip_image035

Project Structure

user/login.jsp

1 <%@ taglib uri="/struts-tags" prefix="s"%> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> 5 <title>Login Page</title> 6 </head> 7 <body> 8 <h3>Welcome User, please login below</h3> 9 <s:form action="/user/login"> 10 <s:textfield name="name" label="User Name"></s:textfield> 11 <s:textfield name="pwd" label="Password" type="password"></s:textfield> 12 <s:submit value="Login"></s:submit> 13 </s:form> 14 </body> 15 </html>

user/index.jsp

1 <%@page contentType="text/html" pageEncoding="UTF-8"%> 2 <%@taglib prefix="s" uri="/struts-tags" %> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <title>JSP Page</title> 8 </head> 9 <body> 10 <h1>Hello <s:property value="name" /></h1> 11 </body> 12 </html>

account.jsp

1 <%@page contentType="text/html" pageEncoding="UTF-8"%> 2 <%@taglib prefix="s" uri="/struts-tags" %> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <title>JSP Page</title> 8 </head> 9 <body> 10 <h1>Hello <s:property value="name" /></h1> 11 </body> 12 </html> 13

Index.jsp same above

 

Download source code ===> here