打开servlet

时间:2016-06-23 10:38:26

标签: java html tomcat servlets

对于Java Servlets,我是初学者。我要做的是有一个html表单,它有两个输入字段和一个提交按钮。单击提交按钮时,数据将转到servlet。该网址目前显示为“http://localhost:8080/MyApp/index.html

无论如何,这就是我想要发生的事情但是当我在Tomcat上执行servlet时,html文件没有被渲染。就像servlet没有html文件一样执行。

我希望用户在打开URL时遇到index.html文件。

的index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="ISO-8859-1">
    <title>MyFirstApp</title>
</head>
<body>
    <form action="MyApp" method="GET">
        First Name: <input type="text" name="first_name">
    <br />
        Last Name: <input type="text" name="last_name" />
        <input type="submit" value="Submit" />
    </form>
</body>
</html>

MyApp.java

    package main.com.myfirstapp;

    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;

    @WebServlet("/index.html")
    public class MyApp extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res) 
        throws ServletException, IOException {

        res.setContentType("text/html");

        PrintWriter out = res.getWriter();

        req.getParameter("first_name");
        req.getParameter("last_name");
    }
}

的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>MyApp</servlet-name>
    <servlet-class>main.com.myfirstapp.MyApp</servlet-class>
</servlet>

<welcome-file-list>
    <welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>                   

0 个答案:

没有答案