2016-12-16 59 views
0

我需要将此servlet转换为jsp。困惑于doGet和doPost两种方法都是用servlet编写的,那么如何在JSP中转换/处理这种场景呢?Servlet-> JSP COnversion

我们是否需要为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); 

} 
} 
} 

回答

0

在servlet中你可以得到的请求方法(GET,POST,...):

request.getMethod() 

里面一个JSP你可以做相同:

${pageContext.request.method} 

一个示例如何区分b切口白内障手术挽请求方法与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>