package com.bcstnet.struts.services;import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class WebContext extends HttpServlet { private static final String CONTENT_TYPE = "text/html; charset=utf-8"; //Initialize global variables public void init() throws ServletException { }
public String getRootPath () { return this.getServletContext().getRealPath("/"); }
//Process the HTTP Get request public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(CONTENT_TYPE); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head><title>Servlet3</title></head>"); out.println("<body bgcolor=\"#ffffff\">"); out.println("<p>The servlet has received a " + request.getMethod() + ". This is the reply.</p>"); out.println(getRootPath()); out.println("</body></html>"); } //Clean up resources public void destroy() { } }
可以不用在写测试类了,你部署servlet之后直接在地址栏键入这个servlet的请求地址就行了。如果你愿意,可以写一个jsp或者html,通过页面提交请求也行。
==========================
在web.xml加
<servlet>
<servlet-name>webcontext</servlet-name>
<servlet-class>com.struts.service.WebContext</servlet-class>
</servlet>怎么访问?
http://localhost:8080/demo/webcontext
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class WebContext extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=utf-8";
//Initialize global variables
public void init() throws ServletException {
}
public String getRootPath () {
return this.getServletContext().getRealPath("/");
}
//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Servlet3</title></head>");
out.println("<body bgcolor=\"#ffffff\">");
out.println("<p>The servlet has received a " + request.getMethod() + ". This is the reply.</p>");
out.println(getRootPath());
out.println("</body></html>");
} //Clean up resources
public void destroy() {
}
}