IDEA中第一个Servlet

IDEA中第一个Servlet,第1张

IDEA中第一个Servlet Servlet
  1. 新建一个普通项目,填groupid,artifictid,删去src,

    自己写名字

  2. 在该项目下新建Module,选create和webapp,选择本地maven和仓库


  3. 完善maven 结构,java和resources

  4. 父工程pom中添加依赖



        
        
            javax.servlet
            javax.servlet-api
            4.0.1
        


        
        
            javax.servlet.jsp
            jsp-api
            2.2
        

    

  1. 子工程Java目录新建一个普通类,继承HttpServlet
package com.raylene.servlet;

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

public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置网页响应类型
        resp.setContentType("text/html;charset=utf-8");
        //实现具体 *** 作
        PrintWriter out = resp.getWriter();
        out.println("This is a new servlet page");
        out.write("系统时间为:"+new Date());

    }

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

    }
}

  1. 子工程pom中添加servlet映射



  Archetype Created Web Application

  
    hello
    org.raylene.servlet.HelloServlet
  

  
    hello
    /hello
  


  1. 配置tomcat

  2. 启动项目

  3. 启动成功output窗口显示,同时浏览器中会d出index.jsp的内容,此时可以在url后输入你在设置的映射名,即可进入对应的目录

  4. 关闭tomcat

    注意:可能在最后启动tomcat时报错:

Connected to server
[ Artifact servlet-01:war: Artifact is being deployed, please wait...
**严重 [RMI TCP Connection(3)-127.0.0.1] org.apache.catalina.core.Containerbase.addChildInternal Containerbase.addChild: start:** 
org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/servlet_01_war]]

**严重 [RMI TCP Connection(3)-127.0.0.1] org.apache.tomcat.util.modeler.baseModelMBean.invoke Exception invoking method manageApp
java.lang.IllegalStateException: Containerbase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/servlet_01_war]]**

Caused by: **java.lang.IllegalStateException: Containerbase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/servlet_01_war]]**

解决法案可参考:web项目启动出错
我的刚开始就属于最基本的在配置servlet映像时没有加,在web.xml的配置中以下标签(访问路径)里面的内容前面没有加"/"。解决方法时加上"/"就行。

/*

关于URL中的斜杠

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5120650.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-17
下一篇2022-11-17

发表评论

登录后才能评论

评论列表(0条)

    保存