测试系统环境变量
检查服务器的基本配置
将helloworld.html和helloworld.jsp放置到/webapps/ROOT下
helloworld.html
test
Hello world
helloworld.jsp
jsp test
Hello JSP.
Time:<%= new java.util.Date() %>
浏览器访问:
测试不使用包的Servlet
在命令窗口下编码HelloServlet.java,将编译后的class文件放到/webapps/ROOT/WEB-INF/class下
HelloServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/** Simple servlet used to test server.*/
public class HelloServlet extends HttpServlet{
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String docType="\n";
out.println(docType+
"\n"+
"Hello\n"+
"\n"+
"Hello world
\n"+
"");
}
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
this.doGet(request,response);
}
}
编译HelloServlet.java
因为我们使用的是tomcat7,无法使用其调用器invoker,所以要手动添加映射,打开/webapps/ROOT/WEB-INF下的web.xml,编辑如下:
Welcome to Tomcat
Welcome to Tomcat
hello
HelloServlet
hello
/HelloServlet
启动Tomcat,在浏览器访问,如下,则说明正确
测试使用的Servlet
带包的HelloServlet2.java如下:
package coreservlets;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/** Simple servlet used to test server.*/
public class HelloServlet2 extends HttpServlet{
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String docType="\n";
out.println(docType+
"\n"+
"Hello\n"+
"\n"+
"Hello world (2)
\n"+
"");
}
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
this.doGet(request,response);
}
}
像上面一样,编译之后就class文件拷贝到/webapps/ROOT/WEB-INF/class/coreservlets包下,并在web.xml文件中增加如下内容
hello2
coreservlets.HelloServlet2
hello2
/HelloServlet2
在这里要注意,web.xml中,引用HelloServlet2时,包与class文件之间的分隔符是圆点“.";classes下的包名要与package coreservlets一致,否则,你懂的。
重启tomcat,在浏览器测试,如下
测试使用包和实用工具类的Servlet
HelloServlet3.java
package coreservlets;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/** Simple servlet for testing the use of packages
*and utilities from the same package*/
public class HelloServlet3 extends HttpServlet{
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String title="Hello (3)";
out.println(ServletUtilities.headWithTitle(title)+
"\n"+
""+title+"
\n"+
"