--我需要将这个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);
}
}
}发布于 2016-12-16 17:38:17
在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.jsp和doGet.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>https://stackoverflow.com/questions/41176891
复制相似问题