杰瑞科技汇

JSP中如何正确导入Java类?

Of course! This is a fundamental concept in JSP (JavaServer Pages). Let's break down how to import Java classes and packages into a JSP file.

JSP中如何正确导入Java类?-图1
(图片来源网络,侵删)

The core idea is that a JSP page is, behind the scenes, converted into a Java servlet. The <%@ page %> directive is how you give instructions to the JSP container (like Tomcat) about how to generate that underlying Java code.


The Primary Method: The page Directive

The standard and most common way to import a Java class or package is by using the page directive with the import attribute.

Syntax

<%@ page import="packageName.ClassName, anotherPackage.AnotherClass" %>

You can import multiple classes or packages by separating them with a comma.

Key Points:

  • Placement: This directive should be placed at the top of your JSP file, usually before any HTML. It's good practice to put it right after the <%@ page contentType... %> directive if you have one.
  • Semicolons: Notice there are no semicolons at the end of the import statement, unlike in Java.
  • *`java.lang.is Implicit:** You do **not** need to explicitly import classes from thejava.langpackage (e.g.,StringSystemObject`). They are automatically available.
  • *`java.util.is NOT Implicit:** You must explicitly import classes fromjava.util(e.g.,ArrayListDateHashMap`).

Practical Examples

Let's look at some common use cases.

JSP中如何正确导入Java类?-图2
(图片来源网络,侵删)

Example 1: Importing a Single Class

Imagine you have a simple utility class com.example.DateUtils.java.

DateUtils.java

package com.example;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtils {
    public static String getCurrentTimestamp() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date());
    }
}

index.jsp Here's how you would import and use it in a JSP.

<%@ page import="com.example.DateUtils" %>
<%-- You can also import multiple classes on one line --%>
<%@ page import="java.util.List, java.util.ArrayList" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>JSP Import Example</title>
</head>
<body>
    <h1>Welcome to JSP!</h1>
    <p>The current server time is: <b><%= DateUtils.getCurrentTimestamp() %></b></p>
    <hr>
    <p>Here is an example of using an imported List:</p>
    <%
        List<String> names = new ArrayList<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");
    %>
    <ul>
        <% for(String name : names) { %>
            <li><%= name %></li>
        <% } %>
    </ul>
</body>
</html>

Explanation:

JSP中如何正确导入Java类?-图3
(图片来源网络,侵删)
  1. <%@ page import="com.example.DateUtils" %> tells the JSP container to make the DateUtils class available in the generated servlet.
  2. <%= DateUtils.getCurrentTimestamp() %> is a JSP expression that calls the static method from our imported class.
  3. Similarly, List and ArrayList are imported so we can use them in the scriptlet (<% ... %>).

Example 2: Importing an Entire Package

If you plan to use multiple classes from the same package (like java.util), it's cleaner to import the whole package using an asterisk ().

products.jsp

<%@ page import="java.util.*" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>Product List</title>
</head>
<body>
    <h2>Our Products</h2>
    <%
        // We can now use any class from java.util without importing them individually
        Map<String, Double> products = new HashMap<>();
        products.put("Laptop", 1200.50);
        products.put("Mouse", 25.00);
        products.put("Keyboard", 75.75);
    %>
    <table border="1">
        <tr>
            <th>Product</th>
            <th>Price</th>
        </tr>
        <% for (Map.Entry<String, Double> entry : products.entrySet()) { %>
            <tr>
                <td><%= entry.getKey() %></td>
                <td>$<%= entry.getValue() %></td>
            </tr>
        <% } %>
    </table>
</body>
</html>

What About Other Imports?

You might see other directives like taglib or include, but for importing standard Java code, the page directive is the one you need.

  • <%@ taglib ... %>: Used to import custom tag libraries (like JSTL), not standard Java classes.
  • <%@ include ... %>: Used to statically include the content of another file (HTML or JSP) at translation time. It doesn't import Java classes.

Summary Table

Directive Syntax Purpose Example
page <%@ page import="..." %> Imports Java classes and packages for use in the JSP. <%@ page import="java.util.List" %>
taglib <%@ taglib uri="..." prefix="..." %> Imports a custom tag library for use in the JSP. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
include <%@ include file="..." %> Statically merges the content of another file into the current JSP. <%@ include file="header.html" %>

In short, whenever you need to use a Java class (like ArrayList, Date, or your own custom class) in a JSP, the first thing you should do is add an <%@ page import="..." %> directive at the top of the file.

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