how to translate servlet to JSP?
Can you help me translate a Servlet to JSP
here's the code:
package Inventory;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DisplayData extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Item item = (Item) request.getAttribute("invenItem");
if (item != null) {
out.println("<html><title>Inventory Item</title>");
out.println("<body><h1>Inventory Item Details:</h1>");
out.println("Stock ID : " + item.getStockID() + "<br/>");
out.println("Name : " + item.getItemName() + "<br/>");
out.println("Unit Price: " + item.getUnitPrice() + "<br/>");
out.println("On Stock : " + item.getOnStock() + "<br/>");
out.println("</body>");
out.println("</html>");
} else {
RequestDispatcher rd =
request.getRequestDispatcher("/SearchPage.html");
rd.include(request, response);
rd = request.getRequestDispatcher("/AddData.html");
rd.include(request, response);
}
}
}
I am trying to use the scriplets, but still want to know how to convert:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
to JSP. I try to do this:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Display Data</title>
</head>
<jsp:useBean id="inventory" class="Inventory.AddData" />
<jsp:directive.page import="java.io.*" />
<jsp:directive.page import="javax.servlet.*" />
<jsp:directive.page import="javax.servlet.http.*" />
<body>
<%-- But I don't know how to convert this:
public class DisplayData extends HttpServlet
in JSP
--%>
</body>
开发者_运维百科
please Help... thanks in advance
The cleanest way would be to use JSTL instead of scriptlets (check out a good primer here). In a nutshell, you need to have JSTL JARs installed (either in your app server or in your specific webapp). Then, you can do the following:
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
...
<c:out value="${invenItem.stockID}"/>
The first line imports the JSTL "core" tag library, which gives you access to the basic tags. Then, the tag is used to output data - it will escape special characters for you (for example, suppose stockID has the character "<"). Finally, the ${} is an EL expression, which in this case simply accesses the invenItem request attribute and extracts the stockID value (by calling getStockID()).
Clean, simple, no ugly Java scriptlets in your JSP view.
The JSP page is already compiled into a servlet. No need to extend one manually.
精彩评论