Java 如何将变量从Servlet输出到JSP?
我试图将Servlet中定义的变量输出到JSP,但我就是做不到 这是我的密码:Java 如何将变量从Servlet输出到JSP?,java,jsp,servlets,Java,Jsp,Servlets,我试图将Servlet中定义的变量输出到JSP,但我就是做不到 这是我的密码: MainServlet: /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package DAO
MainServlet:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
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(name = "MainServlet", urlPatterns = {"/MainServlet"})
public class MainServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
request.setAttribute("msg", "Bloody Hell"); // Here <<<<<<<<<<<<<<<
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
public String getServletInfo() {
return "Short description";
}
}
index.jsp:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>BlueBank</title>
</head>
<body>
<h1>Whatever: ${msg}</h1>
</body>
</html>
假设jsp位于根上下文中,则修改servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// response.setContentType("text/html");
request.setAttribute("msg", "Bloody Hell");
request.getRequestDispatcher("/index.jsp").include(request, response);
}
然后访问servlet url,它将设置属性,然后包含索引jsp。为什么会出现?你的servlet与你展示的JSP有什么关系?你需要使用原始servlet而不是像Spring MVC这样更易于管理的东西吗?我的WEB-INF是不正确的,我是在URL上以index.JSP而不是MainServlet访问的是的,很愚蠢,但现在可以了。谢谢你的帮助!