欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

本地建网页服务器4-java(http://localhost:8080/)

程序员文章站 2022-04-29 20:57:02
...

本地建网页服务器4-java(http://localhost:8080/)

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <form action="MyServlet" method="post">
        <input id="name" name="name" type="text">
        <input id="pwd" name="pwd" type="text"> 
        <input name="submit" type="submit" value="提交">
    </form>
    
</body>
</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">
    <display-name>My</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <servlet>
        <servlet-name>MyServlet </servlet-name>
        <servlet-class>com.yd.MyServlet </servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>MyServlet </servlet-name>
        <url-pattern>/MyServlet </url-pattern>
    </servlet-mapping>
</web-app>

MyServlet.java

package com.yd;

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;

public class MyServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");
        /** 设置响应头允许ajax跨域访问 **/
        response.setHeader("Access-Control-Allow-Origin", "*");
        /* 星号表示所有的异域请求都可以接受, */
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");

        /**
         * 接收json
         */
        String name = request.getParameter("name");
        String pwd = request.getParameter("pwd");
        System.out.println(name);
        System.out.println(pwd);
        /**
         * 返回json
         */
        PrintWriter out = response.getWriter();
        String title = "成果";
        String docType = "<!DOCTYPE html> \n";
        out.println(
                docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n"
                        + "<h1 align=\"center\">" + title + "</h1>\n" + "登陆成功\r\n" + "</body>\r\n" + "</html>");
        out.close();

    }
}