我在Eclipse中遇到Tomcat问题;当我运行一个简单的Servlet时,Tomcat(在Eclipse中)没有向我显示该页面,但它要求我下载它! 有代码。我该怎么办才能修复它?源代码位于..Documents \ Workspace \ Servlet02 \ src \ mypkg \ SimpleServlet
package mypkg;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.*;
@SuppressWarnings("unused")
@WebServlet(name = "SimpleServlet", urlPatterns = {"/SimpleServlet"})
public class SimpleServlet extends HttpServlet {
Date currDateAndTime;
private static final long serialVersionUID = 1L;
protected void processRequest(HttpServletRequest request , HttpServletResponse response) throws IOException , ServletException{
response.setContentType("html/text ; charset=UTF-8 ");
PrintWriter out = response.getWriter();
try {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet CurrentDateAndTime</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet CurrentDateAndTime at " + request.getContextPath() + "</h1>");
out.println("<br/>");
synchronized(currDateAndTime){
currDateAndTime = new Date();
out.println("The current date and time is: " + currDateAndTime);
}
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
@Override
protected void doGet(HttpServletRequest request , HttpServletResponse response) throws IOException , ServletException{
processRequest(request,response);
}
@Override
protected void doPost(HttpServletRequest request , HttpServletResponse response) throws IOException , ServletException{
processRequest(request,response);
}
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
答案 0 :(得分:3)
问题是由于线下。
response.setContentType("html/text ; charset=UTF-8 ");
应该是
response.setContentType("text/html; charset=UTF-8");
或完全删除它或使用
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
中详细了解相关信息
使用字符串
setContentType(java.lang.String)
调用text/html
并使用字符串UTF-8
调用此方法与使用字符串setContentType
调用text/html; charset=UTF-8
等效。
答案 1 :(得分:0)
应该是
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");