Day01JavaWeb【Tomcat服务器&Servlet入门】Servlet快速入门**

Servlet快速入门 ***

  • 页面与服务端程序有什么关系
    在这里插入图片描述

  • 什么是Servlet?

Servlet就是运行在服务端的JAVA小程序

Servlet快速入门***

  • 直接new Servlet
  • 设置项目的访问地址
    Demo1Servlet
    Demo2Servlet
  • 设置Servlet的访问地址
  • 设置方法请求方式
  • 设置参数
    Demo3GetDataServlet

创建第一个Servlet

Demo01Servlet.java

@WebServlet("/demo01") //指定访问具体的哪个Servlet类
public class Demo01Servlet extends HttpServlet {
    //当你使用post请求访问时,当前的doPost自动执行了
    //表单里面的method设置为post
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("doPost");
    }
    //当你使用get请求访问时,当前的doGet自动执行了
    //地址栏访问就是get
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("doGet");
    }
}


不同的Servlet有不同的访问地址

Demo02Servlet .java

@WebServlet("/demo02")
public class Demo02Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("doPost");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("doGet");
    }
}

Servlet只做三件事

Demo03GetDataServlet .java

@WebServlet("/demo03")
public class Demo03GetDataServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       doGet(request,response); //在项目中一般,让servlet以相同的方式处理get/post请求
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1:接收请求,获取参数
       String username = request.getParameter("username");//根据参数名获取参数值;
        String password = request.getParameter("password");
        //2:处理
        System.out.println(username);
        System.out.println(password);
        //3:返回响应
        response.getWriter().println("success");
    }
}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--post调用doPost方法-->
<!--action指定调哪个servlet-->
        <form method="post" action="/myweb01/demo03">
           账号: <input name="username" type="text"><br/>
           密码: <input name="password" type="password"><br/>
            <input type="submit" value="登录">
        </form>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/u013621398/article/details/108471347
今日推荐