栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

IDEA中第一个Servlet

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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窗口显示,同时浏览器中会弹出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中的斜杠

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/434834.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号