【问题标题】:I am trying get data from Servlet to jsp page我正在尝试从 Servlet 获取数据到 jsp 页面
【发布时间】:2018-12-13 16:13:28
【问题描述】:

我正在尝试从 Servlet 页面获取数据到 jsp 页面,但我得到的是空值。 我想获取 servlet 页面中的消息。 请帮助我 下面是我的代码 小服务程序:

package com.project1;

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("/TestServlet")
public class TestServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;


    public TestServlet() {
        super();

    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String  msg="hi i am servlet";

        request.setAttribute("data",msg);
        request.getRequestDispatcher("Test.jsp").forward(request, response);
    }

}

这是我的jsp代码:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div>
<%= request.getAttribute("data") %>.
</div>
</body>
</html>

【问题讨论】:

标签: java jsp servlets frontend


【解决方案1】:

您的代码正在运行。 小服务程序。

你在 doGet 方法中错过了 @override

@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //processRequest(request, response);
        String msg = "hi i am servlet";

        request.setAttribute("data", msg);
        request.getRequestDispatcher("Test.jsp").forward(request, response);
    }

Test.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
         pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Insert title here</title>
    </head>
    <body>
        <div>
            <%=request.getAttribute("data")%>.
        </div>
    </body>
</html>

可能会添加

@WebServlet(name = "TestServlet", urlPatterns = {"/TestServlet"})

到 servlet 的顶部

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-24
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多