如何从该servlet返回jsp作为响应?

时间:2019-12-29 15:46:12

标签: java html jsp servlets

如何在servlet中将jsp文件设置为响应?我需要在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>

1 个答案:

答案 0 :(得分:0)

我建议您阅读此post。 JSTL将为您提供帮助。我想您已映射了servlet。这是一个简单的示例:

<%@ 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})来调用属性。