本章介绍如何使用Java进行Web开发,包括Servlet与JSP、Spring框架入门以及如何构建RESTful Web服务与Spring Boot应用。

9.1 Servlet与JSP

Servlet和JSP是Java Web开发的基础技术,Servlet用于处理请求和响应,JSP用于生成动态网页内容。

9.1.1 什么是Servlet

Servlet是运行在服务器上的Java程序,用于处理客户端的HTTP请求。

示例:创建一个简单的Servlet

  1. import java.io.IOException;
  2. import java.io.PrintWriter;
  3. import javax.servlet.ServletException;
  4. import javax.servlet.annotation.WebServlet;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. // 使用@WebServlet注解定义Servlet URL模式
  9. @WebServlet("/hello")
  10. public class HelloServlet extends HttpServlet {
  11. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  12. throws ServletException, IOException {
  13. // 设置响应内容类型
  14. response.setContentType("text/html");
  15. // 获取PrintWriter对象,用于向客户端发送响应
  16. PrintWriter out = response.getWriter();
  17. out.println("<html><body>");
  18. out.println("<h1>Hello, World!</h1>");
  19. out.println("</body></html>");
  20. }
  21. }

9.1.2 什么是JSP

JSP(JavaServer Pages)是一种基于HTML的技术,用于创建动态网页。

示例:创建一个简单的JSP页面

  1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  2. <html>
  3. <head>
  4. <title>JSP Example</title>
  5. </head>
  6. <body>
  7. <h1>Hello, JSP!</h1>
  8. <%
  9. // 在JSP中嵌入Java代码
  10. String message = "Welcome to JSP!";
  11. out.println("<p>" + message + "</p>");
  12. %>
  13. </body>
  14. </html>

9.1.3 Servlet与JSP的结合使用

结合使用Servlet和JSP,可以实现MVC(Model-View-Controller)架构。

示例:通过Servlet传递数据到JSP

  1. import java.io.IOException;
  2. import javax.servlet.ServletException;
  3. import javax.servlet.annotation.WebServlet;
  4. import javax.servlet.http.HttpServlet;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7. // 使用@WebServlet注解定义Servlet URL模式
  8. @WebServlet("/greet")
  9. public class GreetingServlet extends HttpServlet {
  10. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  11. throws ServletException, IOException {
  12. // 设置请求属性
  13. request.setAttribute("name", "John");
  14. // 转发请求到JSP页面
  15. request.getRequestDispatcher("/greeting.jsp").forward(request, response);
  16. }
  17. }
  1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  2. <html>
  3. <head>
  4. <title>Greeting</title>
  5. </head>
  6. <body>
  7. <h1>Hello, <%= request.getAttribute("name") %>!</h1>
  8. </body>
  9. </html>

9.2 Spring框架入门

Spring是一个功能强大的Java框架,用于构建企业级应用。本节将介绍Spring的基础概念和基本使用方法。

9.2.1 什么是Spring框架

Spring框架提供了一系列模块和工具,用于简化Java应用的开发,包括依赖注入、AOP、数据访问和Web开发等。

9.2.2 依赖注入

依赖注入是Spring的核心概念之一,允许对象之间的依赖关系通过配置文件或注解来设置。

示例:使用Spring管理Bean

  1. // 定义一个简单的Service类
  2. public class HelloService {
  3. public String sayHello() {
  4. return "Hello, Spring!";
  5. }
  6. }
  7. // 定义Spring配置类
  8. import org.springframework.context.annotation.Bean;
  9. import org.springframework.context.annotation.Configuration;
  10. @Configuration
  11. public class AppConfig {
  12. @Bean
  13. public HelloService helloService() {
  14. return new HelloService();
  15. }
  16. }
  17. // 使用Spring容器创建和获取Bean
  18. import org.springframework.context.ApplicationContext;
  19. import org.springframework.context.annotation.AnnotationConfigApplicationContext;
  20. public class Main {
  21. public static void main(String[] args) {
  22. // 创建Spring应用上下文
  23. ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
  24. // 获取HelloService Bean
  25. HelloService helloService = context.getBean(HelloService.class);
  26. System.out.println(helloService.sayHello()); // 输出:Hello, Spring!
  27. }
  28. }

9.3 RESTful Web服务与Spring Boot

Spring Boot简化了Spring应用的开发和配置,特别适合构建RESTful Web服务。

9.3.1 什么是RESTful Web服务

REST(Representational State Transfer)是一种架构风格,用于设计网络应用的API。RESTful Web服务使用标准的HTTP方法(GET、POST、PUT、DELETE)进行通信。

9.3.2 Spring Boot简介

Spring Boot是Spring框架的子项目,通过自动配置和内置的服务器(如Tomcat),简化了Spring应用的开发。

9.3.3 使用Spring Boot构建RESTful Web服务

示例:创建一个简单的Spring Boot应用

  1. 搭建Spring Boot项目

使用Spring Initializr生成一个Spring Boot项目,包含以下依赖:

  • Spring Web
  1. 创建Spring Boot应用的主类
  1. import org.springframework.boot.SpringApplication;
  2. import org.springframework.boot.autoconfigure.SpringBootApplication;
  3. @SpringBootApplication
  4. public class MyApp {
  5. public static void main(String[] args) {
  6. SpringApplication.run(MyApp.class, args);
  7. }
  8. }
  1. 创建一个REST控制器
  1. import org.springframework.web.bind.annotation.GetMapping;
  2. import org.springframework.web.bind.annotation.RequestMapping;
  3. import org.springframework.web.bind.annotation.RestController;
  4. @RestController
  5. @RequestMapping("/api")
  6. public class GreetingController {
  7. @GetMapping("/greeting")
  8. public String greeting() {
  9. return "Hello, RESTful Web Service!";
  10. }
  11. }
  12. // 使用Spring Boot启动应用后,访问http://localhost:8080/api/greeting
  13. // 输出:Hello, RESTful Web Service!

9.3.4 使用DTO和服务层

为了实现更好的代码组织和松耦合,可以使用DTO(Data Transfer Object)和服务层。

示例:添加DTO和服务层

  1. 创建DTO类
  1. public class Greeting {
  2. private String message;
  3. public Greeting(String message) {
  4. this.message = message;
  5. }
  6. public String getMessage() {
  7. return message;
  8. }
  9. public void setMessage(String message) {
  10. this.message = message;
  11. }
  12. }
  1. 创建服务类
  1. import org.springframework.stereotype.Service;
  2. @Service
  3. public class GreetingService {
  4. public Greeting getGreeting() {
  5. return new Greeting("Hello, RESTful Web Service with DTO!");
  6. }
  7. }
  1. 修改控制器类
  1. import org.springframework.beans.factory.annotation.Autowired;
  2. import org.springframework.web.bind.annotation.GetMapping;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.RestController;
  5. @RestController
  6. @RequestMapping("/api")
  7. public class GreetingController {
  8. private final GreetingService greetingService;
  9. @Autowired
  10. public GreetingController(GreetingService greetingService) {
  11. this.greetingService = greetingService;
  12. }
  13. @GetMapping("/greeting")
  14. public Greeting greeting() {
  15. return greetingService.getGreeting();
  16. }
  17. }