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作用域 那么 我们就将他输出在界面上就好了

然后 我们运行项目

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

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

相关推荐
goodluckyaa1 小时前
Warp shuffle函数
开发语言
j7~2 小时前
【C++】STL--Vector容器--拆析解剖Vector的实现以及Vector的底层详解(1)
开发语言·c++·vector·迭代器失效·迭代器的使用
平安的平安2 小时前
传统Java工程师第一次用飞算JavaAI生成SpringBoot项目
java
csjane10792 小时前
Redisson 限流原理
java·redis
xxwl5852 小时前
Python语言初步认识(1)
开发语言·python·学习
一个做软件开发的牛马2 小时前
MyBatis 从零实战:完整搭建可运行 Demo,注解与 XML 双模式开发详解
java·后端
z落落2 小时前
C# FileStream文件流读取文件
开发语言·c#
砍材农夫2 小时前
python环境|conda安装和使用(1)
开发语言·后端·python·conda
用户298698530142 小时前
Java 实践:查找与提取 Word 文档超链接
java·后端
Flittly2 小时前
【AgentScope Java新手村系列】(9)SpringBoot集成
java·spring boot·spring