web开发的尽头是servlet

在传统的Java Web开发中,JSP和Servlet结合使用是一种常见的模式,其中Servlet负责业务逻辑和数据处理,而JSP负责视图展示。下面是一个简单的示例,展示如何构建一个基于JSP和Servlet的Web应用程序的基本结构。

步骤1:创建Servlet

首先,你需要创建一个Servlet,这个Servlet将处理HTTP请求,执行业务逻辑,并向JSP页面发送数据。

ExampleServlet.java
java 复制代码
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class ExampleServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 设置响应内容类型
        response.setContentType("text/html;charset=UTF-8");

        // 准备数据
        String message = "Hello, World!";
        request.setAttribute("message", message);

        // 转发请求到JSP页面
        RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/views/example.jsp");
        dispatcher.forward(request, response);
    }
}

步骤2:创建JSP页面

接下来,创建一个JSP页面来展示Servlet传递过来的数据。

example.jsp
html 复制代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <title>Example Page</title>
</head>
<body>
<h1>Welcome to My Web App!</h1>
<p><%= request.getAttribute("message") %></p>
</body>
</html>

步骤3:配置web.xml

最后,你需要在web.xml中配置Servlet,使其能够接收HTTP请求。

web.xml
xml 复制代码
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <servlet>
        <servlet-name>ExampleServlet</servlet-name>
        <servlet-class>com.example.ExampleServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>ExampleServlet</servlet-name>
        <url-pattern>/example</url-pattern>
    </servlet-mapping>

</web-app>

运行应用

现在,当用户访问http://yourdomain.com/example时,请求将被转发到ExampleServlet,Servlet将处理请求并将数据发送到example.jsp,然后JSP页面将显示数据。

这个基本架构展示了JSP和Servlet如何协同工作来处理HTTP请求和响应。在实际应用中,你可能需要处理更复杂的数据和业务逻辑,但基本的流程和原理是一样的。

相关推荐
文丑颜不良啊12 小时前
LeetCode1461~1480题目解析
java·leetcode
2301_7807896620 小时前
跨平台适配!SDK 游戏盾兼容全终端游戏场景
java·网络·ddos
学长毕设20 小时前
基于springboot的食品仓库管理系统
java·spring boot·后端
步行cgn21 小时前
FormHttpMessageConverter 详解:Spring MVC 中表单数据的读写转换器
java·spring·mvc
龙亘川21 小时前
构建城市公共安全数字底座:亘川智城智慧安防系统全维度解读
java·大数据·开发语言·人工智能·信息可视化
金銀銅鐵21 小时前
[Java] 用 CLI 展示 EnumMap 增删键值对时的内部变化
java·源码·ai编程
秋天的怀念_David21 小时前
第二十二夜 · 数字迷雾
java·程序人生·算法
Raas1001 天前
AI网关部署方案?从部署到上线全流程
java·开发语言·人工智能·gateway·ai网关·企业级ai网关·企业级ai产品
niucloud-admin1 天前
NIUCLOUD PHP SAAS上门家政使用文档:城市管理
java·前端·php
霸道流氓气质1 天前
智能客服组件:分层意图识别、RAG Advisor 与人工转接状态机的 Vue3 + Spring AI 生产级实战
java·人工智能·spring