IDEA 创建Servlet-HelloWorldServlet

servlet

1.创建空项目

2.配置web项目



3.配置Tomcat




4.加载Tomcat包




5.创建HelloWorldServlet类

java 复制代码
public class controller extends HttpServlet {
    @Override
    //get请求
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	//页面显示servlet
        resp.getWriter().println("servlet");
    }

    @Override
    //post请求
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}

6.配置web.xml

xml 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <servlet>
<!--        java类路径别名-->
        <servlet-name>hello</servlet-name>
<!--        引入java类-->
        <servlet-class>com.lx.controller</servlet-class>
    </servlet>
    <servlet-mapping>
<!--        使用别名-->
        <servlet-name>hello</servlet-name>
<!--        浏览器资源路径-->
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
</web-app>

7.运行


get与post请求

html 复制代码
<!--  /servletWebDemo:是配置Tomcat中指定的地址-->
<!--  /login:是web.xml中的<url-pattern>/login</url-pattern>-->
  <form action="/servletWebDemo/login" method="get">
    <label>用户名:</label>
    <input type="text" name="userName">
    <br>
    <br>
    <label>密码:</label>
    <input type="password" name="passWord">
    <br>
    <br>
    <button type="submit">提交</button>
  </form>
java 复制代码
public class controller extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//设置请求中文字符
        req.setCharacterEncoding("utf-8");
        //设置响应中文字符
        resp.setContentType("text/html;charset=utf-8");
        String userName = req.getParameter("userName");
        String passWord = req.getParameter("passWord");
        resp.getWriter().println(userName);
        resp.getWriter().println();
        resp.getWriter().println(passWord);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
相关推荐
艾伦~耶格尔19 分钟前
Spring Boot 三层架构开发模式入门
java·spring boot·后端·架构·三层架构
man201724 分钟前
基于spring boot的篮球论坛系统
java·spring boot·后端
2401_8581205341 分钟前
Spring Boot框架下的大学生就业招聘平台
java·开发语言
S hh41 分钟前
【Linux】进程地址空间
java·linux·运维·服务器·学习
Java探秘者1 小时前
Maven下载、安装与环境配置详解:从零开始搭建高效Java开发环境
java·开发语言·数据库·spring boot·spring cloud·maven·idea
攸攸太上1 小时前
Spring Gateway学习
java·后端·学习·spring·微服务·gateway
2301_786964361 小时前
3、练习常用的HBase Shell命令+HBase 常用的Java API 及应用实例
java·大数据·数据库·分布式·hbase
2303_812044461 小时前
Bean,看到P188没看了与maven
java·开发语言
苹果醋31 小时前
大模型实战--FastChat一行代码实现部署和各个组件详解
java·运维·spring boot·mysql·nginx
秋夫人1 小时前
idea 同一个项目不同模块如何设置不同的jdk版本
java·开发语言·intellij-idea