我可以在servlet编码中使用CSS吗?

时间:2011-08-31 04:43:55

标签: servlets

有没有办法在servlet编码中使用CSS?

3 个答案:

答案 0 :(得分:3)

是的!有一种在servlet中使用css的方法。这可以通过以下方式实现;首先在此步骤之后创建一个PrintWriter类的对象"PrintWriter out=response.getWriter();",您可以在花括号内使用“out.print("<html><head><style='text/css'>{}</style></head>")";”来编写ID或类的代码。在"out.print()"之后或之前,您可以编写servlet代码。不要忘记关闭<html>和其他标记。

答案 1 :(得分:1)

如果你想让它相对于上下文路径,你也可以把LINK写成

<LINK REL="StyleSheet" HREF="<%=request.getContextPath()%>/util/CSS/Style.css" TYPE="text/css"> 

其中,/ util / CSS是上下文路径下的文件夹(例如,在典型的Tomcat设置的情况下为/ webapp / examples)。

但是,您必须确保整个路径都是准确输入的(即区分大小写)。

希望这个额外的澄清有所帮助。

答案 2 :(得分:0)

通过在生成的HTML中直接包含样式,可以在Servlet中使用CSS:

try (PrintWriter out = response.getWriter()) {
  out.println("<!DOCTYPE html>");
  out.println("<html>");
  out.println("<head>");
  out.println("<meta charset=\"utf-8\">");  // escape the quote marks
  out.println("<title>Glassfish HTML Testing</title>");
  out.println("<style>");     // start style
  // enclose style attributes withing the <style> </style> elements
  out.println("h1 {");        // note leading brace
  out.println("color:blue;");
  out.println("background-color:yellow;");
  out.println("border: 1px solid black;");
  out.println("}");          // note trailing brace for h1 style
  // add styles for other elements here using similar structure
  // note that separate lines are used for clarity -
  // all of the above could be one println
  out.println("</style>");  // terminate style
  out.println("</head>");
  out.println("<body>");
  out.println("<h1>Servlet located at " + request.getContextPath() + "</h1>");
  out.println("</body>");
  out.println("</html>");
}  // end of try-with-resources block

上面的代码应该在Servlet的processRequest方法中(假设生成的页面适合GET和POST请求)