Java SE 与 Java EE 使用方法及组件封装实用指南

发布于:2025-06-18 ⋅ 阅读:(19) ⋅ 点赞:(0)

Java SE与Java EE使用方法及组件封装指南

一、Java SE核心功能使用方法

1. 集合框架使用

Java SE的集合框架提供了丰富的数据结构和算法,是日常开发中最常用的功能之一。

使用示例:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CollectionUsage {
    public static void main(String[] args) {
        // List使用
        List<String> names = new ArrayList<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");
        
        // 遍历List
        for (String name : names) {
            System.out.println("Name: " + name);
        }
        
        // Map使用
        Map<Integer, String> idMap = new HashMap<>();
        idMap.put(1, "北京");
        idMap.put(2, "上海");
        idMap.put(3, "广州");
        
        // 遍历Map
        for (Map.Entry<Integer, String> entry : idMap.entrySet()) {
            System.out.println("ID: " + entry.getKey() + ", City: " + entry.getValue());
        }
    }
}

组件封装建议:

  • 创建通用的集合工具类,封装常用操作
  • 示例:ListUtil类实现列表判空和分页
public class ListUtil {
    public static <T> boolean isEmpty(List<T> list) {
        return list == null || list.size() == 0;
    }
    
    public static <T> List<T> paginate(List<T> list, int pageNum, int pageSize) {
        if (isEmpty(list)) {
            return new ArrayList<>();
        }
        
        int start = (pageNum - 1) * pageSize;
        int end = Math.min(start + pageSize, list.size());
        
        if (start >= list.size()) {
            return new ArrayList<>();
        }
        
        return list.subList(start, end);
    }
}

2. 文件操作使用

Java SE提供了强大的文件操作API,支持文件读写、目录遍历等功能。

使用示例:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileOperation {
    public static void main(String[] args) {
        String sourceFile = "input.txt";
        String targetFile = "output.txt";
        
        try (BufferedReader reader = new BufferedReader(new FileReader(sourceFile));
             BufferedWriter writer = new BufferedWriter(new FileWriter(targetFile))) {
            
            String line;
            while ((line = reader.readLine()) != null) {
                writer.write(line);
                writer.newLine();
            }
            
            System.out.println("文件复制成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

组件封装建议:

  • 创建文件工具类,封装常用文件操作
  • 示例:FileUtil类实现文件复制和内容读取
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class FileUtil {
    public static void copyFile(String source, String target) throws IOException {
        Path sourcePath = Paths.get(source);
        Path targetPath = Paths.get(target);
        Files.copy(sourcePath, targetPath);
    }
    
    public static List<String> readAllLines(String filePath) throws IOException {
        Path path = Paths.get(filePath);
        return Files.readAllLines(path);
    }
}

二、Java EE核心组件使用方法

1. Servlet使用方法

Servlet是Java EE中处理Web请求的核心组件。

使用示例:

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

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().println("<html><body>");
        response.getWriter().println("<h1>Hello, World!</h1>");
        response.getWriter().println("</body></html>");
    }
}

组件封装建议:

  • 创建基础Servlet类,封装通用操作
  • 示例:BaseServlet封装请求参数获取和错误处理
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public abstract class BaseServlet extends HttpServlet {
    protected String getParameter(HttpServletRequest request, String name) {
        return request.getParameter(name);
    }
    
    protected void handleError(HttpServletResponse response, String message) throws IOException {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.getWriter().println("<html><body>");
        response.getWriter().println("<h1>Error: " + message + "</h1>");
        response.getWriter().println("</body></html>");
    }
}

2. JPA实体类封装

JPA提供了对象关系映射功能,简化数据库操作。

使用示例:

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "products")
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private double price;
    private String description;
    
    // 构造方法、Getter和Setter
    public Product() {}
    
    public Product(String name, double price, String description) {
        this.name = name;
        this.price = price;
        this.description = description;
    }
    
    // Getter和Setter方法
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public double getPrice() { return price; }
    public void setPrice(double price) { this.price = price; }
    public String getDescription() { return description; }
    public void setDescription(String description) { this.description = description; }
}

组件封装建议:

  • 创建基础实体类,封装通用字段
  • 示例:BaseEntity封装创建时间和更新时间
import java.io.Serializable;
import java.time.LocalDateTime;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;

@MappedSuperclass
public abstract class BaseEntity implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @Column(name = "create_time")
    private LocalDateTime createTime;
    
    @Column(name = "update_time")
    private LocalDateTime updateTime;
    
    // Getter和Setter
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }
    public LocalDateTime getCreateTime() { return createTime; }
    public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; }
    public LocalDateTime getUpdateTime() { return updateTime; }
    public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; }
}

三、Java EE服务层组件封装

1. EJB组件封装

EJB是Java EE中实现业务逻辑的核心组件。

使用示例:

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
public class ProductService {
    @PersistenceContext
    private EntityManager em;
    
    public void createProduct(Product product) {
        product.setCreateTime(LocalDateTime.now());
        product.setUpdateTime(LocalDateTime.now());
        em.persist(product);
    }
    
    public Product findProduct(Long id) {
        return em.find(Product.class, id);
    }
}

组件封装建议:

  • 创建基础服务类,封装通用CRUD操作
  • 示例:BaseService封装基本增删改查方法
import java.util.List;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

public abstract class BaseService<T, ID> {
    @PersistenceContext
    private EntityManager em;
    
    private final Class<T> entityClass;
    
    public BaseService(Class<T> entityClass) {
        this.entityClass = entityClass;
    }
    
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public void create(T entity) {
        if (entity instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity) entity;
            baseEntity.setCreateTime(LocalDateTime.now());
            baseEntity.setUpdateTime(LocalDateTime.now());
        }
        em.persist(entity);
    }
    
    public T findById(ID id) {
        return em.find(entityClass, id);
    }
    
    public List<T> findAll() {
        String jpql = "SELECT e FROM " + entityClass.getSimpleName() + " e";
        TypedQuery<T> query = em.createQuery(jpql, entityClass);
        return query.getResultList();
    }
    
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public T update(T entity) {
        if (entity instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity) entity;
            baseEntity.setUpdateTime(LocalDateTime.now());
        }
        return em.merge(entity);
    }
    
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public void delete(ID id) {
        T entity = em.find(entityClass, id);
        if (entity != null) {
            em.remove(entity);
        }
    }
}

2. RESTful API封装

Java EE通过JAX-RS规范支持RESTful API开发。

使用示例:

import javax.ejb.EJB;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/products")
public class ProductResource {
    @EJB
    private ProductService productService;
    
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getAllProducts() {
        List<Product> products = productService.findAll();
        return Response.ok(products).build();
    }
    
    @GET
    @Path("/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getProduct(@PathParam("id") Long id) {
        Product product = productService.findProduct(id);
        if (product == null) {
            return Response.status(Response.Status.NOT_FOUND).build();
        }
        return Response.ok(product).build();
    }
}

组件封装建议:

  • 创建基础资源类,封装通用API响应格式
  • 示例:BaseResource封装成功和错误响应
import javax.ws.rs.core.Response;
import java.util.HashMap;
import java.util.Map;

public abstract class BaseResource {
    protected Response successResponse(Object data) {
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "成功");
        response.put("data", data);
        return Response.ok(response).build();
    }
    
    protected Response errorResponse(int code, String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("code", code);
        response.put("message", message);
        return Response.status(code).entity(response).build();
    }
}

四、组件集成与最佳实践

1. 分层架构集成示例

下面是一个完整的分层架构示例,展示如何集成Servlet、EJB和JPA组件:

Web层(Servlet):

import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/product/add")
public class ProductAddServlet extends HttpServlet {
    @EJB
    private ProductService productService;
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String name = request.getParameter("name");
        double price = Double.parseDouble(request.getParameter("price"));
        String description = request.getParameter("description");
        
        Product product = new Product(name, price, description);
        productService.createProduct(product);
        
        response.sendRedirect(request.getContextPath() + "/products.jsp");
    }
}

业务层(EJB):

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
public class ProductService extends BaseService<Product, Long> {
    @PersistenceContext
    private EntityManager em;
    
    public ProductService() {
        super(Product.class);
    }
    
    // 可以添加特定于Product的业务方法
    public List<Product> findByPriceRange(double minPrice, double maxPrice) {
        String jpql = "SELECT p FROM Product p WHERE p.price BETWEEN :minPrice AND :maxPrice";
        return em.createQuery(jpql, Product.class)
                .setParameter("minPrice", minPrice)
                .setParameter("maxPrice", maxPrice)
                .getResultList();
    }
}

数据层(JPA实体):

import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(name = "products")
public class Product extends BaseEntity {
    private String name;
    private double price;
    private String description;
    
    // Getter和Setter
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public double getPrice() { return price; }
    public void setPrice(double price) { this.price = price; }
    public String getDescription() { return description; }
    public void setDescription(String description) { this.description = description; }
}

2. 组件封装最佳实践

  1. 单一职责原则:每个组件只负责一个明确的功能
  2. 接口抽象:通过接口定义组件行为,提高可替换性
  3. 依赖注入:使用CDI或EJB的依赖注入机制,降低组件耦合
  4. 事务管理:在服务层使用声明式事务管理
  5. 异常处理:统一的异常处理机制,避免重复代码
  6. 日志记录:集成日志框架,记录关键操作和异常信息

通过以上方法,你可以更高效地使用Java SE和Java EE的各类组件,并通过合理的封装策略提高代码的可维护性和可扩展性。在实际项目中,建议根据具体需求选择合适的技术组合,并遵循已有的设计模式和最佳实践。

以上指南详细介绍了Java SE和Java EE核心组件的使用方法与封装策略。如果需要针对特定组件进一步优化或扩展功能,或者希望了解更多实际项目中的应用技巧,欢迎继续探讨。



准备了一些面试资料,请在以下链接中获取
https://pan.quark.cn/s/4459235fee85


关注我获取更多内容


网站公告

今日签到

点亮在社区的每一天
去签到