EL expressions and JSTL expressions and cases

brief introduction

    1. JSP:
         1. Instruction
         2. Notes
         3. Built in objects

     2. MVC development mode
     3. EL expression
     4. JSTL label
     5. Three tier architecture

## JSP:
     1. Instruction
        * Function: used to configure JSP pages and import resource files
        * Format:
            <%@ Instruction name attribute name 1 = attribute value 1 attribute name 2 = attribute value 2...% >
        * Classification:
             1. page         : Configure the of JSP pages
                * contentType: equivalent to response.setContentType()
                     1. Set the mime type and character set of the response body
                     2. Set the encoding of the current jsp page (only high-level IDE can take effect. If low-level tools are used, you need to set pageEncoding property and set the character set of the current page)
                * Import: import package
                * errorPage: after an exception occurs on the current page, it will automatically jump to the specified error page
                * isErrorPage: identifies whether the current page is an error page.
                    * true: Yes, you can use the built-in object exception
                    * false: No. Default value. The built-in object exception cannot be used


             2. include     : The page contains. Import the resource file for the page
                * <%@include file="top.jsp"%>
             3. taglib     : Import resources
                * <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
                    * Prefix: prefix, customized
     2. Notes:
         1. html comments:
            <!-- -->: Only html snippets can be annotated
         2. jsp comments: recommended
            <%-- --%>: All can be annotated


     3. Built in objects
        * In jsp pages, you do not need to create objects that can be used directly
        * There are 9:

                Variable name                    Real type                        effect
            * pageContext                PageContext                    The current page shares data, and eight other built-in objects can be obtained
            * request                    HttpServletRequest            Multiple resources requested at a time(forward)
            * session                    HttpSession                    Between multiple requests in a session
            * application                ServletContext                Share data among all users
            * response                    HttpServletResponse            Response object
            * page                        Object                        Current page(Servlet)Object of  this
            * out                        JspWriter                    Output object, data output to page
            * config                    ServletConfig                Servlet Configuration object for
            * exception                    Throwable                    Exception object

    


##MVC: development mode     
     1. jsp evolution history
         1. In the early days, there were only servlet s, and only response could be used to output tag data, which was very troublesome
         2. Later, jsp was added to simplify the development of servlets. If jsp is used excessively, a lot of java code and html tables are written in jsp, which makes it difficult to maintain and cooperate
         3. Later, the web development of java draws lessons from the mvc development mode to make the program design more reasonable

    2. MVC:
         1. M: Model. JavaBean
            * Complete specific business operations, such as querying the database and encapsulating objects
         2. V: View. JSP
            * Display data
         3. C: Controller. Servlet
            * Get user input
            * Call model
            * Give the data to the view for presentation


        * Advantages and disadvantages:
             1. Advantages:
                 1. Low coupling, easy maintenance, and can facilitate division of labor and cooperation
                 2. High reusability

             2. Disadvantages:
                 1. It makes the project architecture complex and requires high developers

 

##EL expression
     1. Concept: Expression Language
     2. Function: replace and simplify the writing of java code in jsp pages
     3. Syntax: ${expression}
     4. Note:
        * jsp supports el expressions by default. If you want to ignore the el expression
             1. Set the page instruction in jsp: isELIgnored="true" ignore all el expressions in the current JSP page
             2. \ ${expression}: ignore the current el expression


     5. Use:
         1. Operation:
            * Operator:
                 1. Arithmetic operator: + - * / (DIV)% (MOD)
                 2. Comparison operator: > < > = < = ==
                 3. Logical operator: & & (and) | (or)! (not)
                 4. Air transport operator: empty
                    * Function: used to judge whether string, collection and array objects are null or length is 0
                    * $ {empty list}: judge whether the string, collection, array object is null or the length is 0
                    * $ {not empty str}: indicates whether the string, collection and array objects are not null and the length is > 0
         2. Get value
             1. el expressions can only get values from domain objects
             2. Syntax:
                 1. ${field name. Key name}: get the value of the specified key from the specified field
                    * Domain name:
                        1. pageScope        --> pageContext
                        2. requestScope     --> request
                        3. sessionScope     --> session
                        4. applicationScope --> application(ServletContext)
                    * Example: name = Zhang San is stored in the request field
                    * Get: ${requestScope.name}

                 2. ${key name}: indicates whether there is a value corresponding to the key from the smallest field until it is found.

                
                
                 3. Get the values of object, List set and Map set
                     1. Object: ${domain name. Key name. Attribute name}
                        * In essence, it will call the getter method of the object

                     2. List set: ${field name. Key name [index]}

                     3. Map set:
                        * $ {domain name. key name. key name}
                        * $ {domain name. Key name ["key name"]}


         3. Implicit object:
            * There are 11 implicit objects in the el expression
            * pageContext:
                * Get the jsp and the other eight built-in objects
                    * $ {pageContext.request.contextPath}: get virtual directory dynamically

Code example

<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page contentType="text/html;charset=UTF-8" language="java"   %>
<html>
<head>
    <title>Title</title>
</head>
<body>


    ${3 > 4}

    \${3 > 4}
<hr>

    <h3>Arithmetic operator </h3>
    ${3 + 4}<br>
    ${3 / 4}<br>
    ${3 div 4}<br>
    ${3 % 4}<br>
    ${3 mod 4}<br>
    <h3>Comparison operator</h3>
    ${3 == 4}<br>

    <h3>Logical operator</h3>
    ${3 > 4  && 3 < 4}<br>
    ${3 > 4  and 3 < 4}<br>


    <h4>empty operator</h4>
<%

    String str = "";
    request.setAttribute("str",str);

    List list = new ArrayList();
    request.setAttribute("list",list);

%>
    ${not empty str}

    ${not empty list}
</body>
</html>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>el Get data in domain</title>
</head>
<body>


    <%
        //Storing data in a domain
        session.setAttribute("name","Li Si");

        request.setAttribute("name","Zhang San");
        session.setAttribute("age","23");

        request.setAttribute("str","");

    %>

<h3>el Get value</h3>
${requestScope.name}
${sessionScope.age}
${sessionScope.haha}

${name}
${sessionScope.name}




</body>
</html>
<%@ page import="cn.itcast.domain.User" %>
<%@ page import="java.util.*" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>el get data</title>
</head>
<body>

    <%
        User user = new User();
        user.setName("Zhang San");
        user.setAge(23);
        user.setBirthday(new Date());


        request.setAttribute("u",user);


        List list = new ArrayList();
        list.add("aaa");
        list.add("bbb");
        list.add(user);

        request.setAttribute("list",list);


        Map map = new HashMap();
        map.put("sname","Li Si");
        map.put("gender","male");
        map.put("user",user);

        request.setAttribute("map",map);

    %>

<h3>el Gets the value in the object</h3>
${requestScope.u}<br>

<%--
    * It is obtained through the properties of the object
        * setter or getter Method, remove set or get,In the rest of the, the first letter becomes lowercase.
        * setName --> Name --> name
--%>

    ${requestScope.u.name}<br>
    ${u.age}<br>
    ${u.birthday}<br>
    ${u.birthday.month}<br>

    ${u.birStr}<br>

    <h3>el obtain List value</h3>
    ${list}<br>
    ${list[0]}<br>
    ${list[1]}<br>
    ${list[10]}<br>

    ${list[2].name}

    <h3>el obtain Map value</h3>
    ${map.gender}<br>
    ${map["gender"]}<br>
    ${map.user.name}

</body>
</html>

                        
## JSTL
     1. Concept: JavaServer Pages Tag Library   JSP standard tag library
        * Is an open source free jsp tag provided by the Apache organization         < Label >

     2. Function: used to simplify and replace java code on jsp pages         

     3. Use steps:
         1. Import jstl related jar packages
         2. Import tag library: taglib instruction:  <%@ taglib %>
         3. Use labels
    
     4. Common JSTL Tags
         1. if: equivalent to if statement of java code
             1. Properties:
                * test must be an attribute and accept a boolean expression
                    * If the expression is true, the if label body content is displayed; if false, the label body content is not displayed
                    * In general, the test attribute value is used in conjunction with el expressions
                2. Note:
                    * c: The if tag does not have else. If you want else, you can define a c:if tag
         2. choose: equivalent to the switch statement of java code
             1. Use the choose tag to declare                      Equivalent to switch statement
            2. Use the when tag for judgment                      Equivalent to case
            3. Use the otherwise label to make other statements         Equivalent to default

         3. foreach: equivalent to the for statement of java code

Code example

<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head>
    <title>if label</title>
</head>
<body>

    <%--

    c:if label
        1. Properties:
            * test Attribute required, accepted boolean expression
                * If the expression is true,Then display if Label body content, if false,The label body content is not displayed
                * Normally, test Attribute values are combined el Use with expressions

        2. be careful: c:if No label else Situation, want else In this case, you can define a c:if label


    --%>

    <c:if test="true">
        <h1>I'm serious...</h1>
    </c:if>
    <br>

    <%
        //Judge whether a list collection in the request field is empty. If it is not null, the traversal collection will be displayed

        List list = new ArrayList();
        list.add("aaaa");
        request.setAttribute("list",list);

        request.setAttribute("number",4);

    %>

    <c:if test="${not empty list}">
        Traversal set...

    </c:if>
    <br>

    <c:if test="${number % 2 != 0}">

            ${number}Odd number

    </c:if>

    <c:if test="${number % 2 == 0}">

        ${number}Even number

    </c:if>

</body>
</html>

 

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head>
    <title>choose label</title>
</head>
<body>

    <%--
        The completion number corresponds to the day of the week case
            1.Store a number in the field
            2.use choose Label extraction number         amount to switch statement
            3.use when Digital judgment of labels         amount to case
            4.otherwise The label makes a statement in other cases, which is equivalent to default
    --%>

    <%
        request.setAttribute("number",51);
    %>

    <c:choose>
        <c:when test="${number == 1}">Monday</c:when>
        <c:when test="${number == 2}">Tuesday</c:when>
        <c:when test="${number == 3}">Wednesday</c:when>
        <c:when test="${number == 4}">Thursday</c:when>
        <c:when test="${number == 5}">Friday</c:when>
        <c:when test="${number == 6}">Saturday</c:when>
        <c:when test="${number == 7}">Sunday</c:when>

        <c:otherwise>Digital input error</c:otherwise>
    </c:choose>


</body>
</html>

 

<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.List" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head>
    <title>foreach label</title>
</head>
<body>

<%--

    foreach:amount to java Coded for sentence
        1. Repeat operation completed
            for(int i = 0; i < 10; i ++){

            }
            * Properties:
                begin: Start value
                end: End value
                var: Temporary variable
                step: step
                varStatus:Loop state object
                    index:The index of the element in the container, starting from 0
                    count:Number of cycles, starting from 1
        2. Traversal container
            List<User> list;
            for(User user : list){

            }

            * Properties:
                items:Container object
                var:Temporary variable for element in container
                varStatus:Loop state object
                    index:The index of the element in the container, starting from 0
                    count:Number of cycles, starting from 1


--%>

<c:forEach begin="1" end="10" var="i" step="2" varStatus="s">
    ${i} <h3>${s.index}<h3> <h4> ${s.count} </h4><br>

</c:forEach>

    <hr>


    <%
        List list = new ArrayList();
        list.add("aaa");
        list.add("bbb");
        list.add("ccc");

        request.setAttribute("list",list);


    %>

    <c:forEach items="${list}" var="str" varStatus="s">

            ${s.index} ${s.count} ${str}<br>

    </c:forEach>


</body>
</html>

     5. Exercise:
        * Requirement: there is a list collection containing User objects in the request field. You need to use jstl+el to display the list set data in the table of the jsp page

<%@ page import="cn.itcast.domain.User" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.Date" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head>
    <title>test</title>
</head>
<body>

<%

    List list = new ArrayList();
    list.add(new User("Zhang San",23,new Date()));
    list.add(new User("Li Si",24,new Date()));
    list.add(new User("Wang Wu",25,new Date()));

    request.setAttribute("list",list);


%>

<table border="1" width="500" align="center">
    <tr>
        <th>number</th>
        <th>full name</th>
        <th>Age</th>
        <th>birthday</th>
    </tr>
    <%--data row--%>
    <c:forEach items="${list}" var="user" varStatus="s">

        <c:if test="${s.count % 2 != 0}">

            <tr bgcolor="red">
                <td>${s.count}</td>
                <td>${user.name}</td>
                <td>${user.age}</td>
                <td>${user.birStr}</td>
            </tr>
        </c:if>

        <c:if test="${s.count % 2 == 0}">

            <tr  bgcolor="green">
                <td>${s.count}</td>
                <td>${user.name}</td>
                <td>${user.age}</td>
                <td>${user.birStr}</td>
            </tr>
        </c:if>




    </c:forEach>

</table>






</body>
</html>

##Three tier architecture: software design architecture
     1. Interface layer (presentation layer): the interface seen by the user. Users can interact with the server through components on the interface
     2. Business logic layer: the layer that handles business logic.
     3. Data access layer: operate data storage files.


##Case: user information list display
     1. Requirement: add, delete, modify and query user information
     2. Design:
         1. Technology selection: servlet + jsp + MySQL + jdbc templet + duird + BeanUtils + Tomcat
         2. Database design:
             create database day17; -- Create database
             use day17;                -- Use database
             create table user(   -- Create table
                id int primary key auto_increment,
                name varchar(20) not null,
                gender varchar(5),
                age int,
                address varchar(32),
                qq    varchar(20),
                email varchar(50)
            );

     3. Development:
         1. Environmental construction
             1. Create database environment
             2. Create a project and import the required jar package

 

         2. Coding
    

     4. Test
     5. Deployment, operation and maintenance

code

domain package

package cn.itcast.domain;

public class User {
    private int id;
    private String name;
    private String gender;
    private int age;
    private String address;
    private String qq;
    private String email;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getQq() {
        return qq;
    }

    public void setQq(String qq) {
        this.qq = qq;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", gender='" + gender + '\'' +
                ", age=" + age +
                ", address='" + address + '\'' +
                ", qq='" + qq + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

dao package and impl

package cn.itcast.dao;

import cn.itcast.domain.User;

import java.util.List;

/**
 * User operated DAO
 */
public interface UserDao {


    public List<User> findAll();
}
package cn.itcast.dao.impl;

import cn.itcast.dao.UserDao;
import cn.itcast.domain.User;
import cn.itcast.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class UserDaoImpl implements UserDao {

    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    @Override
    public List<User> findAll() {
        //Using JDBC to manipulate databases
        //1. Define sql
        String sql = "select * from user";
        List<User> users = template.query(sql, new BeanPropertyRowMapper<User>(User.class));

        return users;
    }
}

service package and impl

package cn.itcast.service;

import cn.itcast.domain.User;

import java.util.List;

/**
 * User managed service interface
 */
public interface UserService {

    /**
     * Query all user information
     * @return
     */
    public List<User> findAll();
}
package cn.itcast.service.impl;

import cn.itcast.dao.UserDao;
import cn.itcast.dao.impl.UserDaoImpl;
import cn.itcast.domain.User;
import cn.itcast.service.UserService;

import java.util.List;

public class UserServiceImpl implements UserService {
    private UserDao dao = new UserDaoImpl(); //Interface oriented programming to reduce coupling

    @Override
    public List<User> findAll() {
        //Call Dao to complete the query
        return dao.findAll();
    }
}

servlet for web package

package cn.itcast.web.servlet;

import cn.itcast.domain.User;
import cn.itcast.service.UserService;
import cn.itcast.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/userListServlet")
public class UserListServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. Call UserService to complete the query
        UserService service = new UserServiceImpl();
        List<User> users = service.findAll();
        //2. Store the list in the request field
        request.setAttribute("users",users);
        //3. Forward to list.jsp
        request.getRequestDispatcher("/list.jsp").forward(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

util package

package cn.itcast.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * JDBC The utility class uses the Durid connection pool
 */
public class JDBCUtils {

    private static DataSource ds ;

    static {

        try {
            //1. Load configuration file
            Properties pro = new Properties();
            //Use ClassLoader to load the configuration file and get the byte input stream
            InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            pro.load(is);

            //2. Initialize the connection pool object
            ds = DruidDataSourceFactory.createDataSource(pro);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Get connection pool object
     */
    public static DataSource getDataSource(){
        return ds;
    }


    /**
     * Get Connection object
     */
    public static Connection getConnection() throws SQLException {
        return  ds.getConnection();
    }
}

druid.properties

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///day17
username=root
password=root
# Number of initialization connections
initialSize=5
# maximum connection
maxActive=10
# Maximum waiting time
maxWait=3000

Front page

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8"/>
  <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <title>home page</title>

  <!-- 1. Import CSS Global style for -->
  <link href="css/bootstrap.min.css" rel="stylesheet">
  <!-- 2. jQuery Import, 1 is recommended.9 Version above -->
  <script src="js/jquery-2.1.0.min.js"></script>
  <!-- 3. Import bootstrap of js file -->
  <script src="js/bootstrap.min.js"></script>
  <script type="text/javascript">
  </script>
</head>
<body>
<div align="center">
  <a
          href="${pageContext.request.contextPath}/userListServlet" style="text-decoration:none;font-size:33px">Query all user information
  </a>
</div>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<!-- Language of the web page -->
<html lang="zh-CN">
<head>
    <!-- Specify character set -->
    <meta charset="utf-8">
    <!-- use Edge The latest browser rendering -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!-- viewport Viewport: the web page can be automatically adapted according to the set width. A container is virtual inside the browser, and the width of the container is the same as that of the device.
    width: The default width is the same as the width of the device
    initial-scale: The initial zoom ratio is 1:1 -->
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Above 3 meta label*must*Put it first, anything else*must*Follow! -->
    <title>User information management system</title>

    <!-- 1. Import CSS Global style for -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <!-- 2. jQuery Import, 1 is recommended.9 Version above -->
    <script src="js/jquery-2.1.0.min.js"></script>
    <!-- 3. Import bootstrap of js file -->
    <script src="js/bootstrap.min.js"></script>
    <style type="text/css">
        td, th {
            text-align: center;
        }
    </style>
</head>
<body>
<div class="container">
    <h3 style="text-align: center">User information list</h3>
    <table border="1" class="table table-bordered table-hover">
        <tr class="success">
            <th>number</th>
            <th>full name</th>
            <th>Gender</th>
            <th>Age</th>
            <th>Native place</th>
            <th>QQ</th>
            <th>mailbox</th>
            <th>operation</th>
        </tr>

        <c:forEach items="${users}" var="user" varStatus="s">
            <tr>
                <td>${s.count}</td>
                <td>${user.name}</td>
                <td>${user.gender}</td>
                <td>${user.age}</td>
                <td>${user.address}</td>
                <td>${user.qq}</td>
                <td>${user.email}</td>
                <td><a class="btn btn-default btn-sm" href="update.html">modify</a>&nbsp;<a class="btn btn-default btn-sm" href="">delete</a></td>
            </tr>

        </c:forEach>


        <tr>
            <td colspan="8" align="center"><a class="btn btn-primary" href="add.html">Add a Contact </a></td>
        </tr>
    </table>
</div>
</body>
</html>

Keywords: Java JavaEE html

Added by gregchet on Fri, 19 Nov 2021 15:44:33 +0200