杰瑞科技汇

JSP中Java的import该怎么用?

Of course! This is a fundamental concept in JSP development. Let's break down how Java imports work in JSP, covering the different types, best practices, and common use cases.

JSP中Java的import该怎么用?-图1
(图片来源网络,侵删)

The Core Directive: <%@ page %>

The primary way to import Java classes, interfaces, or entire packages into a JSP page is by using the page directive. This directive is placed at the top of your JSP file.

Syntax

The import attribute of the page directive accepts a comma-separated list of packages or classes.

<%@ page import="package.Class1, package.Class2, package.subpackage.*" %>
  • package.Class1: Imports a specific class.
  • *`package.subpackage.**: Imports all public classes and interfaces from a specific package using a wildcard (*`).
  • Comma Separation: You can list multiple imports on the same line or use multiple page import directives.

Practical Examples

Here are several common examples you'll see in real-world applications.

Example 1: Importing a Core Java Class

Let's say you want to use the java.util.Date class to display the current time.

JSP中Java的import该怎么用?-图2
(图片来源网络,侵删)
<%@ page import="java.util.Date" %>
<html>
<head>Current Time</title>
</head>
<body>
    <h1>Hello JSP!</h1>
    <p>The current server time is: <%= new Date() %></p>
</body>
</html>

Explanation:

  • <%@ page import="java.util.Date" %> tells the JSP container that this page will use the Date class.
  • <%= new Date() %> is a JSP expression scriptlet that creates a new Date object and prints its string representation.

Example 2: Importing a Collection

To use a java.util.ArrayList, you must import it.

<%@ page import="java.util.ArrayList" %>
<html>
<body>
    <h1>My Favorite Fruits</h1>
    <ul>
        <%
            ArrayList<String> fruits = new ArrayList<>();
            fruits.add("Apple");
            fruits.add("Banana");
            fruits.add("Orange");
            for (String fruit : fruits) {
        %>
            <li><%= fruit %></li>
        <%
            }
        %>
    </ul>
</body>
</html>

Explanation:

  • <%@ page import="java.util.ArrayList" %> makes the ArrayList class available.
  • The <% ... %> block is a scriptlet, which contains standard Java code that is executed when the page is requested. Here, we create an ArrayList, add items to it, and loop through them.

Example 3: Importing Multiple Classes or Packages

You can import several items in one directive or split them across multiple directives. Both are valid.

JSP中Java的import该怎么用?-图3
(图片来源网络,侵删)

Method A: Single Directive

<%@ page import="java.util.List, java.util.ArrayList, java.util.Date" %>

Method B: Multiple Directives (often preferred for readability)

<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.Date" %>

Importing Your Own Classes

You can also import classes that you've created yourself. Let's say you have a utility class.

Step 1: Create a Java Class (e.g., in src/com/example/)

// src/com/example/GreetingUtil.java
package com.example;
public class GreetingUtil {
    public static String getGreeting(String name) {
        return "Welcome, " + name + "!";
    }
}

Step 2: Use it in your JSP

Make sure your project is set up so the compiled class is in the web application's classpath (e.g., in WEB-INF/classes/).

<%@ page import="com.example.GreetingUtil" %>
<html>
<head>Custom Class Import</title>
</head>
<body>
    <h1>Using a Custom Class</h1>
    <p><%= GreetingUtil.getGreeting("John Doe") %></p>
</body>
</html>

Explanation:

  • The <%@ page import="com.example.GreetingUtil" %> directive makes your custom class available.
  • You can then call its static method getGreeting() directly within the expression scriptlet.

The Modern Approach: The JSP Standard Tag Library (JSTL)

While importing and using scriptlets (<% ... %>) works, it's considered an older practice. Modern JSP development strongly favors using JSTL (JSP Standard Tag Library) and EL (Expression Language).

Why?

  • Separation of Concerns: JSTL/EL keeps Java logic out of the JSP view file, making it cleaner and easier for web designers to work with.
  • Readability: JSTL tags are much more readable than tangled Java code in scriptlets.
  • Maintainability: Logic is easier to manage and test when it's not embedded in the presentation layer.

Example: Using JSTL instead of java.util.List

First, you need to include the JSTL core library in your JSP. This is done with another directive, taglib.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%-- No need to import java.util.List or ArrayList with JSTL! --%>
<html>
<head>JSTL Example</title>
</head>
<body>
    <h1>My Favorite Fruits (JSTL)</h1>
    <ul>
        <c:forEach var="fruit" items="['Apple', 'Banana', 'Orange']">
            <li>${fruit}</li>
        </c:forEach>
    </ul>
</body>
</html>

Explanation:

  • <%@ taglib ... %> declares that you are using the JSTL core library, giving it the prefix c.
  • <c:forEach> is a JSTL loop tag. It iterates over the collection provided in the items attribute.
  • ${fruit} is an EL (Expression Language) expression that prints the current value of the fruit variable.

For more complex scenarios, you would set the list in a Servlet and add it to the request scope, then access it with JSTL.


Summary and Best Practices

Method How it Works When to Use
<%@ page import %> Imports Java classes/packages for use in scriptlets (<% ... %>) and expressions (<%= ... %>). Legacy code. Avoid in new projects. Use only if you absolutely must use scriptlets.
JSTL & EL Uses <%@ taglib %> to import tag libraries. EL () and JSTL tags (<c:forEach>, etc.) handle logic and data display. Highly Recommended. This is the modern standard for writing clean, maintainable, and readable JSP pages.
Implicit Objects JSP provides pre-defined objects like request, response, session, and application without needing to import them. Always. These are available in any JSP page for interacting with the web container.

Final Recommendation:

For any new JSP project, strive to use JSTL and Expression Language (EL). Reserve <%@ page import %> for situations where you are forced to maintain old code that relies on scriptlets. This approach will lead to a much better and more professional application architecture.

分享:
扫描分享到社交APP
上一篇
下一篇