JSP basics


JSTL: function

  • basic
    • fn.length(data)
    • fn.toUpperCase(data)
  • split()
    • fn.split(data, ',')
<c:set var="data" value="Singapore,Tokyo,Mumbai,London" /> 
 <c:set var="citiesArray" value="${fn:split(data, ',')}" />
  • join()
    • fn.join(data, '*')

JSTL: I18N

short for internationalization and used for displaying formatting data.

Locale: Language Code + Country Code

  • create resource file
    • file name must follow specific format
    • <your project file name>_LANGUAGECODE_COUNTRYCODE.properties and put those files inside of the packages
  • create JSP page with Labels
    • <fmt:message key="label.greeting" /> <i> asjdfkajsdf </i> <br/>
  • update JSP page to change locale based on user selection

    • <c:set var="theLocale"
          value="${not empty param.theLocale ? param.theLocale : pageContext.request.locale}" 
          scope="session" />
      <fmt:setLocale value="${theLocale}" />
      <fmt:setBundle basename="com.luv2code.jsp.tagdemo.i18n.resources.mylabels" />
      

Servlet

Java class that is processed on the server. That would generates HTML that is returned to browser.

Java servlet is like a java class that generate the html content on the fly.

have three steps:

  • set the content type
    • response.setContentType("text/html");
  • get the printwriter
    • PrintWriter out = response.getWriter();
  • generate HTML content
    • out.println("<html><body>");
    • out.println("<h2>Hello World</h2>");

so we have a html file containing form which requires the servlet to process, then servlet receive it, and generate the proper HTML file and sent back to the browser.

difference between Servlet and JSP?

  • JSP

    • HTML file with .jsp extention
    • contains static HTML
    • has built-in JSP objects
  • Servlet

    • Java class file
    • generate all HTML
    • more steps to access web objects
  • best practice?

    • Integrate them both together,
      • Servlet does the business logic
      • JSP handles the presentation view
      • this is MVC Design Pattern

difference between Get and Post?

  • sending data with Get method

    • form data is added to end of the URL as name/value pairs
    • theUrl?field1=value1&field2=value2
  • sending data with Post method

    • form data is passed in the body of HTTP request message
    • is inside of the body part of the HTTP request message.
  • best practice?

    • sensitive information => post method
    • binary information like image for email => post method
    • very large file => post method (get have limitations on data length: 1000 characters)
    • get is good for debugging

Reading Servlet Parameters

we can set some configuration in WEB-INF/web.xml

<web-app> 
 <context-param>
 <param-name>max-shopping-cart-size</param-name>
 <param-value>99</param-value> 
 </context-param>

 <context-param> 
 <param-name>project-team-name</param-name> 
 <param-value>The Coding Gurus</param-value>
 </context-param>
... 
</web-app>

and here, we try to read those data in the Servlet file:

ServletContext context = getServletContext();
String maxCart = context.getInitParameter("max-shopping-cart-size");
...

note: getServletContext() is inherited from HttpServlet(); and getInitParameter() always return a string, also, if the parameter does not exist, this method will simply return a value of null.

think further? what is per servlet parameters? How to use it?

you can define servlet parameters on a per servlet basis. but don't forget servlet-mapping

think further? How to redirect form JSP to a Servlet:

make use of the method: response.sendRedirect(...

<%
    response.sendRedirect(request.getContextPath() + "/hello");
%>

MVC with JSP and Servlet

benefit of MVC

  • minimizes HTML code in Servlet: no more out.println()... in Servlet code
  • minimize Java Business logic in JSPs

How Servlet can call a JSP?

  • Servlet can call JSP using a request dispatcher

How to send data to JSP?

  • Servlet can add data to request object
  • request.setAttribute("attributeName", array);

How to view the data in JSP?

  • get the data using get Attribute

MVC full_circle

index.html -> MvcDemoServletTwo.java(Servlet) -> StudentDataUtil/Student(Model) -> view_students_two(view)

MvcDemoServletTwo.java

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub

    // step 1: get the student data from helper class(model)
    List<Student> students = StudentDataUtil.getStudents();

    // step 2: add students to request object
    request.setAttribute("student_list", students);

    // step 3: get request dispatcher
    RequestDispatcher dispatcher = 
            request.getRequestDispatcher("view_students_two.jsp");

    // step 4: now forward to JSP
    dispatcher.forward(request, response);
}

note: Student and StudentDataUtil are the java class that serves the Model function

Student class

public class Student {
    private String firstName;
    private String lastName;
    private String email;
    public Student(String firstName, String lastName, String email) {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
    }
    public String getFirstName() {
        return firstName;
    }
    ...
}


StudentDataUtil class

public class StudentDataUtil {
    public static List<Student> getStudents() {

        // create an empty list
        List<Student> students = new ArrayList<>();

        // add sample data
        students.add(new Student("Mary", "Public", "[email protected]"));
        students.add(new Student("Shu", "liu", "[email protected]"));
        students.add(new Student("John", "Doe", "[email protected]"));
        students.add(new Student("Ajay", "Rao", "[email protected]"));

        // return the list
        return students;
    }
}
view_students_two

<html>
<body>
<h2>Student Table Demo</h2>
<hr>
<br/>

<table border="1">
    <tr>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Email Name</th>
    </tr>

    <c:forEach var="tempStudent" items="${student_list}">

        <tr>
            <td>${tempStudent.firstName}</td>   <!-- .firstName will call the tempStudent.getFirstName() method -->
            <td>${tempStudent.lastName}</td>
            <td>${tempStudent.email}</td>
        </tr>

    </c:forEach>

</table>

Database application

  • create user sql script
    • use mysql workbench to manage the database.
  • setting up a Tomcat Database connection pool

    • download JDBC Driver JAR file and put it in WEB-INF/ lib/
    • define connection pool in META-INF/ context.xml

      • <Context>
        
          <Resource name="jdbc/web_student_tracker" 
                      auth="Container" type="javax.sql.DataSource"
                       maxActive="20" maxIdle="5" maxWait="10000"
                       username="webstudent" password="webstudent" 
                       driverClassName="com.mysql.jdbc.Driver"
                       url="jdbc:mysql://localhost:3306/web_student_tracker?useSSL=false"/>
        
        </Context>
        
    • get connection pool reference in Java code

      • in the TestServlet java file:
        
                // define data source / connection pool for resource injection
            // name should be consistent with the name in context.xml
            @Resource(name="jdbc/web_student_tracker")
            private DataSource dataSource;   // pay attention: DataSource is javax.sql.DataSource.
        
            /**
             * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
             */
            protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                // TODO Auto-generated method stub
        
                // step 1: set up the printwriter
                PrintWriter out = response.getWriter();
                response.setContentType("text/plain");
        
                // step 2: get a connection to the database
                // pay attention: Connection is javax.sql.Connection not jdbc.connecion
                // eclipse trick: go to source/organize imports to choose specific import
                Connection myConn = null;   
                Statement myStmt = null;
                ResultSet myRs = null;
        
                try {
                    myConn = dataSource.getConnection();
        
                    // step 3: create a sql statement
                    String sql = "select * from student";
                    myStmt = myConn.createStatement();
        
                    // step 4: execute sql query
                    myRs = myStmt.executeQuery(sql);
        
                    // step 5: process the result set
                    while (myRs.next()) {
                        String email = myRs.getString("email");
                        out.println(email);
                    }
                }
                catch (Exception exc) {
                    exc.printStackTrace();
                }
            }
        

early version of EJB were extremely complex, and have multiple deployment descriptors and poor performance of entity beans.

results matching ""

    No results matching ""