Hello World!——內(nèi)嵌Jetty支持Servlet

Hello World!——內(nèi)嵌Jetty支持Servlet

[TOC]

一、引入依賴包

內(nèi)嵌Jetty支持servlet、jsp, jsp支持jstl和el表達(dá)式,除了需要引入jetty-webapp之外,還需要引入apache-jsp和apache-jstl, jsp也是編譯成servlet。


<dependency>
    <groupId>org.eclipse.jetty</groupId>
    <version>9.4.14.v20181114</version>
    <artifactId>jetty-webapp</artifactId>
</dependency>
<dependency>
    <groupId>org.eclipse.jetty</groupId>
    <version>9.4.14.v20181114</version>
    <artifactId>apache-jsp</artifactId>
</dependency>
<dependency>
    <groupId>org.eclipse.jetty</groupId>
    <version>9.4.14.v20181114</version>
    <artifactId>apache-jstl</artifactId>
</dependency>

二、配置支持servlet, jsp, jstl, el表達(dá)式

1、支持servlet

內(nèi)嵌jetty支持servlet,只需要引入WebAppContext作為handler就可以支持


// 用WebAppContext可以支持servlet
WebAppContext webApp = new WebAppContext();
webApp.setContextPath("/");
webApp.setResourceBase("./src/main/webapp");

2、支持jsp

但是, 要支持jsp還需要配置兩個(gè)Configuration

// 支持JSP必須增加以下配置
Configuration.ClassList classlist = Configuration.ClassList.setServerDefault(server);
classlist.addBefore("org.eclipse.jetty.webapp.JettyWebXmlConfiguration",
                "org.eclipse.jetty.annotations.AnnotationConfiguration");

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=$Encode">
    <title>show page</title>
</head>
<body>
    <h1>Hello world</h1>
    <% out.println("<h2>Hello JSP</h2>"); %>
</body>
</html>

可以正常輸出Hello World和Hello JSP。

3、支持jstl和el表達(dá)式

如果在jsp中需要用到j(luò)stl和el表達(dá)式, 還需要配置容器引入的包格式:

//支持jstl和其他tag必須設(shè)置以下配置
webApp.setAttribute(
    "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
        ".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/[^/]*taglibs.*\\.jar$" );

jsp文件頭中還需要特殊處理下, 增加配指令,否則會忽略el表達(dá)式:

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" isELIgnored="false" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
  <c:forEach var="i" begin="1" end="10" step="1">
  <c:out value="${i}" />
  <br />
</c:forEach>

<%@ ... %> 是指令

<% ... %> 是jsp腳本

<c:... /> 是jstl標(biāo)簽

${...} 是el表達(dá)式

三、增加servlet、web.xml和index.jsp

具體示例代碼如下:

1、內(nèi)嵌Jetty的啟動類

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.Configuration;
import org.eclipse.jetty.webapp.WebAppContext;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JettyWebAppApplication {
    public static void main(String[] args) {
        Server server = new Server(8080);

        // 支持JSP必須增加以下配置
        Configuration.ClassList classlist = Configuration.ClassList.setServerDefault(server);
        classlist.addBefore("org.eclipse.jetty.webapp.JettyWebXmlConfiguration",
                "org.eclipse.jetty.annotations.AnnotationConfiguration");
        
        // 用WebAppContext可以支持servlet
        WebAppContext webApp = new WebAppContext();
        webApp.setContextPath("/");
        webApp.setResourceBase("./src/main/webapp");
        // 支持jstl和其他tag必須設(shè)置以下配置
        webApp.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
            ".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/[^/]*taglibs.*\\.jar$");

        server.setHandler(webApp);

        try {
            server.start();
            server.dumpStdErr();
            server.join();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}

2、Servlet的demo類

import java.io.IOException;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class HelloWorldServletDemo extends GenericServlet {
    private static final long serialVersionUID = -1522387682150936960L;

    @Override
    public void init() throws ServletException {
        super.init();
    }

    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        log.info("remote: {} params: {} ", req.getRemoteAddr(), JSON.toJSONString(req.getParameterMap()));
        res.getWriter().write("<h1>Hello World Servlet</h1>");
    }
}

3、web.xml配置

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

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>org.demo.hello.world.jetty.servlet.HelloWorldServletDemo</servlet-class>
        <init-param>
            <param-name>debug</param-name>
            <param-value>0</param-value>
        </init-param>
        <init-param>
            <param-name>listings</param-name>
            <param-value>false</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!-- The mapping for the default servlet -->
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
</web-app>

4、jsp頁面

<!-- 在jar包都有的前提下EL表達(dá)式原樣輸出,不被解析  原因是  page指令中確少 isELIgnored="false" servlet3.0默認(rèn)關(guān)閉了el表達(dá)式的解析 -->
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" isELIgnored="false" %>

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=$Encode">
    <title>show page</title>
</head>
<body>
    <h1>Hello world</h1>
    <% out.println("<h2>Hello JSP</h2>"); %>
    
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
      <c:forEach var="i" begin="1" end="10" step="1">
      <c:out value="${i}" />
      <br />
    </c:forEach>
</body>
</html>

四、運(yùn)行效果

運(yùn)行效果如圖

hello-world-jetty-servlet-demo
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容