JSP 是一种 HTML + Java 揉在一起的东西,类似带 Java 解释器的模板语言。在 Web 开发中,主要有两种用法:
- 纯 JSP 实现一切逻辑,输出 HTML 给用户
- 搭配 Servlets,由 Servlets 做逻辑,再把数据传给 JSP 做模板输出
第一种的例子:
<html>
<head>
<title>Reading Cookies</title>
</head>
<body>
<center>
<h1>Reading Cookies</h1>
</center>
<%
Cookie cookie = null;
Cookie[] cookies = null;
// Get an array of Cookies associated with the this domain
cookies = request.getCookies();
if( cookies != null ) {
out.println("<h2> Found Cookies Name and Value</h2>");
for (int i = 0; i < cookies.length; i++) {
cookie = cookies[i];
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" <br/>");
}
} else {
out.println("<h2>No cookies founds</h2>");
}
%>
</body>
</html>
第二种的例子:
// Servlet
package jsp.GuestJsp;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* GuestJsp is a servlet controlling user
* interaction with the guest book.
*/
public class GuestJsp extends HttpServlet {
/**
* doGet handles GET requests
*/
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException
{
// Save the message in the request for login.jsp
req.setAttribute("message", "Hello, world");
// get the application object
ServletContext app = getServletContext();
// select login.jsp as the template
RequestDispatcher disp;
disp = app.getRequestDispatcher("login.jsp");
// forward the request to the template
disp.forward(req, res);
}
}
// JSP
<%@ page language=javascript %>
<head>
<title><%= request.attribute.message %></title>
</head>
<body bgcolor='white'>
<h1><%= request.attribute.message %></h1>
</body>
看 request.attribute
携带了从 Servlet 传过来的数据。
现在 JSP 应该没什么人用了。大概懂它当年做什么就好。