在Java Servlet中生成HTML响应 [英] Generate an HTML Response in a Java Servlet

查看:106
本文介绍了在Java Servlet中生成HTML响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Java servlet中生成HTML响应?

您通常会将请求转发到JSP以供显示。 JSP是一种视图技术,它提供了一个用于编写普通香草HTML / CSS / JS的模板,并提供了在taglibs和EL帮助下与后端Java代码/变量进行交互的能力。您可以使用taglibs来控制页面流,例如 JSTL 。您可以将任何后端数据设置为任何请求,会话或应用程序作用域中的属性,并在JSP中使用EL( $ {} things)来访问/显示它们。

开球示例:

  @WebServlet(/ hello) 
public class HelloWorldServlet extends HttpServlet {
$ b $ @Override
保护无效doGet(HttpServletRequest请求,HttpServletResponse响应)抛出ServletException,IOException {
String message =Hello World ;
request.setAttribute(message,message); //这可以作为$ {message}
request.getRequestDispatcher(/ WEB-INF / hello.jsp)。forward(request,response);
}

}

/WEB-INF/hello.jsp 看起来像:

 < ;!DOCTYPE html> 
< html lang =en>
< head>
< title> SO问题2370960< / title>
< / head>
< body>
< p>讯息:$ {message}< / p>
< / body>
< / html>

打开 http:// localhost:8080 / contextpath / hello 这将显示

消息:Hello World 

在浏览器中。



这可以避免Java代码免于HTML混乱,并大大提高了可维护性。要学习和练习更多的servlet,请继续阅读下面的链接。



同时浏览标签为[servlets] 的所有问题的频繁标签,以查找常见问题。 p>

How do I generate an HTML response in a Java servlet?

解决方案

You normally forward the request to a JSP for display. JSP is a view technology which provides a template to write plain vanilla HTML/CSS/JS in and provides ability to interact with backend Java code/variables with help of taglibs and EL. You can control the page flow with taglibs like JSTL. You can set any backend data as an attribute in any of the request, session or application scope and use EL (the ${} things) in JSP to access/display them.

Kickoff example:

@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);
    }

}

And /WEB-INF/hello.jsp look like:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>SO question 2370960</title>
    </head>
    <body>
         <p>Message: ${message}</p>
    </body>
</html>

When opening http://localhost:8080/contextpath/hello this will show

Message: Hello World

in the browser.

This keeps the Java code free from HTML clutter and greatly improves maintainability. To learn and practice more with servlets, continue with below links.

Also browse the "Frequent" tab of all questions tagged [servlets] to find frequently asked questions.

这篇关于在Java Servlet中生成HTML响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆