【问题标题】:Servlet->JSP COnversionServlet->JSP 转换
【发布时间】:2016-12-16 03:36:09
【问题描述】:

我需要把这个servlet 转换成jsp。对 doGet 和 doPost 这两个方法都是用 servlet 编写的感到困惑,那么如何在 JSP 中转换/处理这种情况?

doPost和doGet函数需要做不同的jsp页面吗?请注明使用jsp代码。

谢谢

import java.io.*;

import java.util.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class RequestParamExample extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse

response)

throws IOException, ServletException

{

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("GET Request. No Form Data Posted");

}

public void doPost(HttpServletRequest request, HttpServletResponse res)

throws IOException, ServletException

{

Enumeration e = request.getParameterNames();

PrintWriter out = res.getWriter ();

while (e.hasMoreElements()) {

String name = (String)e.nextElement();

String value = request.getParameter(name);

out.println(name + " = " + value);

}
}
}

【问题讨论】:

    标签: java jsp servlets


    【解决方案1】:

    在 Servlet 中,您可以通过以下方式获取请求方法(GET、POST、...):

    request.getMethod()  
    

    在 JSP 中,您可以这样做:

    ${pageContext.request.method}
    

    如何区分 JSP 中的请求方法的示例:

    <!DOCTYPE html><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <html>
    <head>
    <title>getMethod</title>
    </head>
    <body>
        <form method="get">
            <input type="submit" value="Test method: GET"/>
        </form>
        <hr>
    
        <form method="post">
            <input type="text" name="p1" value="v1"><br>
            <input type="text" name="p2" value="v2"><br>
            <input type="submit" value="Test method: POST"/>
        </form>
        <hr>
    
        <h4>results:</h4>
        <c:if test="${pageContext.request.method == 'GET'}">
            GET Request. No Form Data Posted
        </c:if>
    
        <c:if test="${pageContext.request.method == 'POST'}">
            POST Request. Form Data:<br>
            <c:forEach items="${param}" var="p">
                ${p.key} = "${p.value}"<br>
            </c:forEach>
        </c:if>
    </body>
    </html>
    

    如果要拆分doPost.jspdoGet.jsp中的代码,请将最后一段替换为以下内容:

    <h4>results:</h4>
    <c:if test="${pageContext.request.method == 'GET'}">
        <%@include file="doGet.jsp" %>
    </c:if>
    
    <c:if test="${pageContext.request.method == 'POST'}">
        <%@include file="doPost.jsp" %>
    </c:if>
    

    【讨论】:

      猜你喜欢
      • 2019-02-23
      • 1970-01-01
      • 1970-01-01
      • 2015-06-04
      • 1970-01-01
      • 2011-06-25
      • 1970-01-01
      • 2016-07-21
      • 1970-01-01
      相关资源
      最近更新 更多