Is ther开发者_如何学运维e a way to use CSS in servlet coding?
Yes! there is a way of using css in servlets. This can be achieved by the following way; First create an object of PrintWriter class, "PrintWriter out=response.getWriter();"
after this step you can use "out.print("<html><head><style='text/css'>{}</style></head>")";
inside the curly braces you can write the code for IDs or Classes. After or before of "out.print()"
you can write your servlet code. Do not forget to close <html>
and other tags.
In case you want to have it relative to the context path you can also write LINK as
<LINK REL="StyleSheet" HREF="<%=request.getContextPath()%>/util/CSS/Style.css" TYPE="text/css">
Where, /util/CSS is a folder underneath your context path (e.g. /webapp/examples in case of a typical Tomcat set up).
However, you must make sure that the entire path is accurately typed (i.e. is case sensitive).
Hope this additional clarification helps.
CSS can be used in a Servlet by including styles directly in generated HTML:
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
The above code should be in the processRequest method of the Servlet (assuming the generated page is appropriate for GET and POST requests)
精彩评论