开发环境为Spring Tool Suite;
一、首先配置STS.ini,配置文件如下:
-startup
plugins/org.eclipse.equinox.launcher_1.3.200.v20160318-1642.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.400.v20160518-1444
-product
org.springsource.sts.ide
--launcher.defaultAction
openFile
-vmargs
-Dosgi.requiredJavaVersion=1.8
-Xms40m
-Xverify:none
-Dorg.eclipse.swt.browser.IEVersion=10001
-Xmx1200m
-Dfile.encoding=UTF-8(最后一行增加代码,设置编码格式为UTF-8)
二、往STS中增加Tomcat服务器(注意把jdk改为自己安装的jdk);
三、新建Dynamic Web Project;
四、新建一个类,继承HttpServlet类,并且覆盖父类的doGet()方法;
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //继承HttpServlet类; public class TestServlet extends HttpServlet { private static final long serialVersionUID = -514345712229720561L; //覆盖doGet()方法; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //通过setContentType()方法,设置编码格式为UTF-8,否则中文乱码; resp.setContentType("text/html;charset=UTF-8"); //通过getWriter()返回一个字节输出流PrintWriter(); PrintWriter pw = resp.getWriter(); pw.println("<html>"); pw.println("</head>"); pw.println("<title>悯农</title>"); pw.println("</head>"); //默写100首《悯农》 pw.println("<body>"); for (int i = 0; i < 100; i++) { pw.println("<h1>悯农"+i+"<h3>李绅.唐</h3></h1>"); pw.println("<h2>锄禾日当午,汗滴禾下土</h2>"); pw.println("<h2>谁知盘中餐,粒粒皆辛苦。</h2>"); } pw.println("<body>"); pw.println("</html>"); } }
五、配置web.xml;
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <servlet> <servlet-name>TS</servlet-name> <servlet-class>TestServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>TS</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> </web-app>
其中,<servlet-class>TestServlet</servlet-class>中的TestServlet为类名,两个<servlet-name>TS</servlet-name>中的TS相同即可;<url-pattern>/hello</url-pattern>中的/hello为浏览器访问的域名;
六、添加TestServlet项目,开启Tomcat服务器,在浏览器中输入http://localhost:8080/servlet01/hello;可以看到网页中显示了100首《悯农》;
#注:如果浏览器输入地址时候抛出Class Not Found Exception,网页提示500错误,需要把Tomcat删掉之后重新添加即可;