Bal*_*usC 102
您通常会将请求转发给JSP进行显示.JSP是一种视图技术,它提供了一个模板来编写普通的HTML/CSS/JS,并提供了在taglib和EL的帮助下与后端Java代码/变量进行交互的能力.您可以使用像JSTL这样的taglib来控制页面流.您可以将任何后端数据设置为任何请求,会话或应用程序范围中的属性,并使用${}JSP中的EL(事物)来访问/显示它们.
开球示例:
@WebServlet("/hello")
public class HelloWorldServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String message = "Hello World";
request.setAttribute("message", message); // This will be available as ${message}
request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);
}
}
Run Code Online (Sandbox Code Playgroud)
而/WEB-INF/hello.jsp像这样:
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 2370960</title>
</head>
<body>
<p>Message: ${message}</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
打开http:// localhost:8080/contextpath/hello时会显示
Message: Hello World
在浏览器中.
这使Java代码免于HTML混乱,并大大提高了可维护性.要使用servlet学习和练习更多内容,请继续以下链接.
还可以浏览标记为[servlet]的所有问题的"常用"选项卡,以查找常见问题.
cod*_*ict 35
你需要一个doGet方法:
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Hola</title>");
out.println("</head>");
out.println("<body bgcolor=\"white\">");
out.println("</body>");
out.println("</html>");
}
Run Code Online (Sandbox Code Playgroud)
您可以看到这个简单的hello world servlet的链接
| 归档时间: |
|
| 查看次数: |
128894 次 |
| 最近记录: |