Servlet返回html数据

IDE:IntelliJ IDEA、web服务器:tomcat 8.5.24
jar包:servlet-api.jar

一、HelloFormProject

初始化为空的项目。
导入tomcat中的servlet的jar包。

代码实现:

package com.company;

import java.io.IOException;
import java.io.PrintWriter;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
*
* Servlet implementation class HelloForm
* */
@WebServlet
public class HelloForm extends HttpServlet {

    private static final long servialVersionUID = 1L;

    public HelloForm() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) /*throws ServletException, IOException*/ {


        try {

            response.setContentType("text/html;charset=UTF-8");

            PrintWriter out = response.getWriter();

            String title = "使用GET方法读取表单列表";

            // 处理中文
            String name = new String(request.getParameter("name"));
            String docType = "\n";

            System.out.println("TTTTTTTTT" + name);

            out.println(docType +
                    "\n" +
                    "" + title + "\n" +
                    "\n" +
                    "

" + title + "

" + "
    \n" + "
  • 站点名:" + name + "\n" + "
  • 网站:" + request.getParameter("url") + "\n" + "
\n" + "\n"); } catch (Exception e) { e.printStackTrace(); } } public void doPost(HttpServletRequest request, HttpServletResponse response) /*throws ServletException,IOException*/ { doGet(request, response); } }

web.xml配置


    HelloForm
    com.company.HelloForm



    HelloForm
    /TomcatTest/HelloForm

class文件部署到在ROOT目录下,在ROOT下的web.xml配置。

重启tomcat,访问127.0.0.1:8080/TomcatTest/HelloForm,就可以看到页面了。

二、ServletDemo

创建项目时勾选IntelliJ IDEA中的WebApp选项,IDE会多生成web目录
导入tomcat中的servlet的jar包。

新建>Servlet,IDE会创建Servlet模版类。

代码实现:

package javademo;

import java.io.IOException;
import java.io.PrintWriter;

public class FirstServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter pw = response.getWriter();
        pw.write("

hello first servlet!

"); } }

在项目的web下的WEB-INFINF中的web.xml配置:



    
        FirstServlet
        javademo.FirstServlet
    

    
        FirstServlet
        /demo
    


部署到tomcat:将项目中web目录复制到tomcat的webapps中,重命名为FirstServlet,并在FirstServlet目录中创建classes目录,复制编译后的class文件和包到classes。

重启tomcat,访问127.0.0.1:8080/FirstServlet/demo,就可以看到页面了。

你可能感兴趣的:(Servlet返回html数据)