我如何返回一个jsp作为对此servlet的响应? [重复]

问题描述 投票:0回答:1

我如何将jsp文件设置为servlet中的响应?我需要在jsp页面中使用哪种表达式?这是表格

<html>
<head>
    <title>Select your Hobby</title>
</head>
<body>
<form method="POST" action="SelectHobby">
    <p> Choose a Hobby:
    </p>
    <select name="hobby" size="1">
        <option>horse skiing
        <option>extreme knitting
        <option>alpine scuba
        <option>speed dating
    </select>
    <br><br>
    <center>
        <input type="SUBMIT">
    </center>
</form>
</body>
</html>

该servlet

package com.example.web;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class HobbyServlet extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        response.setContentType("text/html");
        String hobby = request.getParameter("hobby");
    }
}

这是我想看到身体爱好的JSP

<html>
<head>
    <title>These are your hobbies</title>
</head>
<body>
<%
</body>
</html>
java html jsp servlets
1个回答
0
投票
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> </head> <body> <form method="POST" action="testservlet"> <p> Choose a Hobby: </p> <select name="hobby" size="1"> <option>horse skiing <option>extreme knitting <option>alpine scuba <option>speed dating </select> <br><br> <center> <input type="SUBMIT"> </center> </form> </body> </html>

Servlet:

@WebServlet(name = "test", urlPatterns = { "/testservlet" }) 
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;

public Test() {
    super();
}   

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
    String hobby = request.getParameter("hobby");   
    request.setAttribute("theHobby", hobby);
    request.getRequestDispatcher("hobbypage.jsp").forward(request, response);
}

我定义了一个名为theHobby的属性,用于保存第一页中所选嗜好的值。我还创建了一个名为hobbypage.jsp的页面,要将值发送到该页面。

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
       <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Hobby: ${theHobby}
</body>
</html>

使用JSTL,您可以通过定义的名称(如$ {nameOfAttribute})来调用属性。

© www.soinside.com 2019 - 2024. All rights reserved.