1.自定义Servlet

package com.zhan;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class FileServlet extends HttpServlet {

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


        String username = req.getParameter("username");//接收参数

        System.out.println(username);//验证是否接收成功

        req.getRequestDispatcher("success.jsp").forward(req,resp);//转发页面
    }

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

2.编写前端页面(JSP)

<%@page contentType="text/html; charset=UTF-8" language="java" %>
<html>
 <head>
     <title>
         $Title$
     </title>
 </head>
<body>
<h2>
   <form action="FileServlet" method="post">
       <input type="text" name="username" id="username">
        <input type="submit">

   </form>
</h2>
</body>
</html>

注意action中填写的应该是第一步自定义的FileServlet,表示提交该页面的数据到此Servlet中

3.在web.xml中配置FileServlet

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  
  <servlet>
    <servlet-name>FileServlet</servlet-name>
    <servlet-class>com.zhan.FileServlet</servlet-class>
  </servlet>
 <servlet-mapping>
   <servlet-name>FileServlet</servlet-name>
   <url-pattern>/FileServlet</url-pattern>
 </servlet-mapping>
  
  
</web-app>

4.结果

 

 

 

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐