JSP编写自己的第一个WebServlet实现客户端与服务端交互

我们在项目中找到java目录 下面有一个包路径 然后 我们在下面创建一个类

我这里叫 TransmissionTest

当然 名字是顺便取的

参考代码如下

java 复制代码
package com.example.dom;

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

@WebServlet("/1cginServlet")
public class TransmissionTest extends HttpServlet {
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置客户端编码
        request.setCharacterEncoding("UTF-8");
        String userName = request.getParameter("userName");
        request.setAttribute("userName",userName);
        request.getRequestDispatcher("page.jsp").forward(request,response);
        return;
    }
}

这里 我们设置访问路径为 1cginServlet 这个名字也是自己取的

然后 继承 HttpServlet 规则

我们重写它的 service 函数

上来先将编码格式转成 UTF-8

然后 我们通过 getParameter 获取传过来的参数 userName 然后 将接收到的 userName 放入request作用域

最后 服务端跳转向 page.jsp

最后写完了 别忘了 return

然后 我们 index.jsp代码编写如下

html 复制代码
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%request.setCharacterEncoding("UTF-8");%>
<!DOCTYPE html>
<html>
<head>
    <title>JSP - Hello World</title>
</head>
<body>
    <form action="1cginServlet" method="post">
        用户名: <input type="text" name="userName"/>
        <button>提交</button>
    </form>
</body>
</html>

我们写了一个form表单 输入框用于输入用户名 我们定义的接受字段是 userName

然后 表单的提交格式是post 因为post保密性会强一些 然后 我们将数据提交到1cginServlet 就是我们刚刚类设置的路径 我们类中取到的userName字段 就是这个输入框中传递的

然后 我们创建一个page.jsp

编写代码如下

html 复制代码
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%request.setCharacterEncoding("UTF-8");%>
<!DOCTYPE html>
<html>
<head>
    <title>JSP - Hello World</title>
</head>
<body>
<%
    out.print("您输入的用户名是: "+ request.getAttribute("userName"));
%>
</body>
</html>

因为 我们类的逻辑是将userName 设入了 request作用域 那么 我们就将他输出在界面上就好了

然后 我们运行项目

例如 我们在 输入框中 顺便输入一个用户名 然后 我们点击提交

可以看到 展示也是没有任何问题

相关推荐
艾莉丝努力练剑5 分钟前
【QT】系统相关:TCP的API介绍
开发语言·前端·c++·人工智能·qt·学习·tcp/ip
wno70442 分钟前
Centos下PostgreSQL安装部署详细步骤
java·数据库·spring boot
wuxianda10301 小时前
Swift 项目用 Xcode 脚手架起步:默认工程结构和依赖组合为什么会被识别成同源
开发语言·xcode·swift·4.3a·appstore审核
nice_lcj5201 小时前
【从零理解计算机网络 · 04】TCP 三次握手:为什么恰好是三次
java·后端·tcp/ip·计算机网络·面试·tcp·三次握手
ShineWinsu2 小时前
对于Qt:QVBoxLayout常见属性以及方法的解析
开发语言·数据库·c++·qt·gui·客户端·布局管理器
Sarvartha2 小时前
反射综合案例:SQL 语句生成
java·开发语言
Resean022312 小时前
Spring 源码分析(二)配置类的解析与扫描
java·后端·spring
小毛球.12 小时前
第 3 篇:IDEA 最新版下载与完整安装教程(Mac)
java·macos·intellij-idea·idea
ShineWinsu13 小时前
对于Qt:QFormLayout常见属性以及方法的解析
开发语言·c++·qt·面试·客户端·表单·qformlayout
Misnearch14 小时前
ScheduledExecutorService
java·线程池