Jetty 是一個開源的servlet容器,它為基於Java的web容器,例如JSP和servlet提供運行環境。Jetty是使用Java語言編寫的,它的API以一組JAR包的形式發布。開發人員可以將Jetty容器實例化成一個對象,可以迅速為一些獨立運行(stand-alone)的Java應用提供網絡和web連接。Jetty相比與Tomcat是輕量級的,而且Jetty更靈活,體現在其可插拔性和可擴展性,更易於開發者對Jetty本身進行二次開發,定制一個適合自身需求的Web Server。
Jetty可以向Tomcat一樣單獨作為一個純粹的web容器,但是Jetty的開發文檔更偏向於推薦我們將jetty內嵌到我們的項目中,最為一個可插拔的組件進行開發。
下面直接上代碼:
POM文件
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> <jetty.version>9.4.8.v20171121</jetty.version> <spring.version>4.0.6.RELEASE</spring.version> <mybatis.version>3.3.0</mybatis.version> <mysql.version>5.1.24</mysql.version> <slf4j.version>1.7.25</slf4j.version> <logback.version>1.2.3</logback.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-server</artifactId> <version>${jetty.version}</version> </dependency> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-webapp</artifactId> <version>${jetty.version}</version> </dependency> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-security</artifactId> <version>${jetty.version}</version> </dependency> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-start</artifactId> <version>${jetty.version}</version> </dependency> <!-- 添加Spring依賴 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <!-- Spring AOP需要 aspectj Jar --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.8.0</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.0</version> </dependency> <!-- Jackson --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.8.8</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.8</version> </dependency> <!-- mysql驅動包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!-- c3p0 --> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <!--mybatis依賴 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- mybatis/spring包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.1</version> </dependency> <!-- 添加servlet3.0核心包 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.2-b01</version> </dependency> <!-- log日志 start --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <version>${logback.version}</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>${logback.version}</version> </dependency> <!-- log日志 end --> <!--fileupload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <!-- jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> <build> <finalName>jetty-demo</finalName> <sourceDirectory>src/main/java</sourceDirectory> <outputDirectory>${project.build.directory}/classes</outputDirectory> <resources> <resource>
<!-- 將resources中的文件放進打的jar包中 --> <directory>src/main/resources</directory> </resource> <resource>
<!-- 將src/main/webapp下的文件放到打的jar包外 --> <directory>src/main/webapp</directory> <targetPath>${project.build.directory}/webapp/</targetPath> </resource> </resources> <plugins> <!-- 編譯時跳過單元測試 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.9</version> <configuration> <skip>true</skip> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <defaultLibBundleDir>lib</defaultLibBundleDir> <source>${java.version}</source> <target>${java.version}</target> <encoding>${project.build.sourceEncoding}</encoding> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <configuration> <archive> <manifest> <addClasspath>true</addClasspath> <classpathPrefix>lib</classpathPrefix> <mainClass>com.test.JettyServer</mainClass> </manifest> </archive> </configuration> </plugin> <!-- 拷貝依賴的jar包到lib目錄 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <executions> <execution> <id>copy-dependencies</id> <phase>prepare-package</phase> <goals> <goal>copy-dependencies</goal> </goals> <configuration> <outputDirectory>${project.build.directory}/lib</outputDirectory> <overWriteReleases>false</overWriteReleases> <overWriteSnapshots>true</overWriteSnapshots> <overWriteIfNewer>true</overWriteIfNewer> </configuration> </execution> </executions> </plugin> <!-- 要將源碼放上去,需要加入這個插件 --> <plugin> <artifactId>maven-source-plugin</artifactId> <version>2.1</version> <configuration> <attach>true</attach> </configuration> <executions> <execution> <phase>compile</phase> <goals> <goal>jar</goal> </goals> </execution> </executions> </plugin> </plugins> </build>
web.xml
<!-- 設置編碼格式 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter </filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- spring mvc servlet--> <servlet> <servlet-name>restfulServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/springMVC.xml</param-value> </init-param> <init-param> <param-name>useFileMappedBuffer</param-name> <param-value>false</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>restfulServlet</servlet-name> <url-pattern>*.json</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> <!-- Session 超時 --> <session-config> <session-timeout>30</session-timeout> </session-config>
springMVC配置文件,就是普通的配置
<context:component-scan base-package="com.test" /> <!-- <mvc:default-servlet-handler/> 將在 SpringMVC 上下文中定義一個 DefaultServletHttpRequestHandler, 它會對進入 DispatcherServlet 的 請求進行篩查,如果發現是沒有經過映射的請求, 就將該請求交由 WEB 應用服務器默認的 Servlet 處理,如果不是靜態資源的請求,才由 DispatcherServlet 繼續處理 --> <mvc:default-servlet-handler/> <!-- 讓注解重新啟動 @RequestMapping--> <mvc:annotation-driven /> <bean id="mappingJackson2HttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>application/json;charset=UTF-8</value> <value>text/javascript;charset=UTF-8</value> <value>text/plain;charset=UTF-8</value> </list> </property> </bean> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJackson2HttpMessageConverter" /> </list> </property> </bean> <bean name="down" class="org.springframework.web.servlet.mvc.ParameterizableViewController"> <property name="viewName" value="down"/> </bean> <!-- 配置視圖解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="" /> <property name="suffix" value=".jsp" /><!--可為空,方便實現自已的依據擴展名來選擇視圖解釋類的邏輯 --> <!-- <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> --> </bean> <!-- 處理文件上傳 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8" /> <!-- 編碼 --> <property name="maxInMemorySize" value="10240" /> <!-- 上傳時占用最大內存大小 (10240) --> <property name="maxUploadSize" value="-1" /> <!-- 最大文件大小,-1為無限止(-1) --> </bean> </beans>
springIOC容器配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd "> <context:component-scan base-package="com.test" /> </beans>
這里沒有將springIOC容器配置和springMVC配置文件放在一起,也沒有在springMVC配置文件中引用springIOC配置文件,主要是實現解耦分離
創建JettyServer
package com.test; import java.io.File; import java.net.URISyntaxException; import java.net.URL; import org.eclipse.jetty.server.ConnectionFactory; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.HttpConnectionFactory; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.webapp.WebAppContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.support.AbstractXmlApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.XmlWebApplicationContext; /** * jetty 服務器 */ public class JettyServer { private static Logger logger = LoggerFactory.getLogger(JettyServer.class); private static final int HTTP_PORT = 8080; private static final int HTTPS_PORT = 8443; private static final String CONTEXT = "/"; public static void main(String[] args) { Server server = new JettyServer().createServer(); try { server.start(); logger.info("jetty服務開啟!!!"); server.join(); } catch (Exception e) { e.printStackTrace(); } } private JettyServer() {} private Server createServer() { // jetty server 默認的最小連接線程是8,最大是200,連接線程最大閑置時間60秒 Server server = new Server(); HttpConfiguration httpConfig = new HttpConfiguration(); httpConfig.setSecureScheme("https"); httpConfig.setSecurePort(HTTPS_PORT); httpConfig.setOutputBufferSize(32768); httpConfig.setRequestHeaderSize(8192); httpConfig.setResponseHeaderSize(8192); httpConfig.setSendServerVersion(true); httpConfig.setSendDateHeader(false); httpConfig.setHeaderCacheSize(512); ConnectionFactory connectionFactory = new HttpConnectionFactory(httpConfig); ServerConnector connector = new ServerConnector(server, connectionFactory); connector.setPort(HTTP_PORT); connector.setSoLingerTime(-1); // 連接線程最大空閑時間 connector.setIdleTimeout(30000); server.addConnector(connector); URL url = JettyServer.class.getProtectionDomain().getCodeSource().getLocation(); String path = ""; try { path = new File(url.toURI()).getParent(); } catch (URISyntaxException e) { }/* * 如果將項目的配置文件打包到jar包外,可以使用FileSystemXmlApplicationContext加載 * AbstractXmlApplicationContext applicationContext = new FileSystemXmlApplicationContext(path+ "/webapp/WEB-INF/springConfig/applicationContext.xml"); */ // 如果在springMVC配置文件中,引入了springIOC配置文件applicationContext.xml,在這里就沒有必要再創建applicationContext並將其放入到webApplicationContext中 // 這里使用ClassPathXmlApplicationContext的原因是在打包后,打包的jar文件目錄其實是classpath目錄,不會出現文件找不到 AbstractXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); WebAppContext webAppContext = new WebAppContext(); /* * contextPath 是URL的前綴。例如一個contextPath 是/foo,它將處理 /foo, /foo/index.html, /foo/bar/,and /foo/bar/image.png等請求, * 但是它不會處理像/,/other/,or /favicon.ico這樣的請求 */ webAppContext.setContextPath(CONTEXT); webAppContext.setDescriptor(path+"/webapp/WEB-INF/web.xml"); // 配置資源,這個配置是一個目錄,包含各種靜態資源信息,可以是圖片或者HTML頁面。 webAppContext.setResourceBase(path+"/webapp"); // 配置監聽主機ip或名稱,沒有配置的將不會被監聽到。 //webAppContext.setVirtualHosts(new String[] {}); webAppContext.setConfigurationDiscovered(true); webAppContext.setParentLoaderPriority(true); webAppContext.setMaxFormContentSize(10 << 20); webAppContext.setClassLoader(Thread.currentThread().getContextClassLoader()); XmlWebApplicationContext xmlWebAppContext = new XmlWebApplicationContext(); xmlWebAppContext.setParent(applicationContext); xmlWebAppContext.setConfigLocation(""); xmlWebAppContext.setServletContext(webAppContext.getServletContext()); xmlWebAppContext.refresh(); // 配置屬性,可以傳遞到實體類中,比如javax.servlet.context.tempdir屬性用來配置臨時目錄。 webAppContext.setAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, xmlWebAppContext); server.setHandler(webAppContext); return server; } }
其他別的配置就和普通的web項目配置一樣。
注意:項目運行之前要先進行編譯,不然會找不到啟動類,項目進行編譯或者打包后,在target中找到如圖所示的文件
jetty-demo.jar是打包好的可運行的jar,使用Java -jar 命令就可以運行;項目依賴的jar包在lib文件夾下;webapp文件存放的是項目的靜態資源、html文件、JS文件,在學習中發現一個有趣的現象,我在webapp文件夾中放入一個新的html頁面,不用將服務器進行重啟就可以用瀏覽器訪問,算是一個小的優點吧(運行中的項目改變前端頁面后,直接將頁面進行替換,不需要將項目進行重啟);jetty-demo-sources.jar放的是項目的源文件。