我的第一个 Jetty 程序

参考网上的例子

在 eclipse 中新建 java 项目 jetty

下载 http://dist.codehaus.org/jetty/jetty-6.1.14/jetty-6.1.14.zip

把下载的文件中选择几个 jar 文件,拷贝到新建的java项目中

core-3.1.1.jar

jetty-6.1.14.jar

jetty-util-6.1.14.jar

jsp-2.1.jar

jsp-api-2.1.jar

servlet-api-2.5-6.1.14.jar

在 java 项目中新增文件夹 \jetty\web\WEB-INF 并且新建 web.xml 文件和 index.jsp 文件,和 StratJetty.java


StartJetty.java

package com.xjh.core;

import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.nio.SelectChannelConnector;
import org.mortbay.jetty.webapp.WebAppContext;

public class StartJetty {
	
	public static void main(String [] args) throws Exception {
		Server server = new Server();
		Connector connector = new SelectChannelConnector();
		//设置端口
		connector.setPort(8080);
		//设置host地址
		connector.setHost("127.0.0.1");
		server.setConnectors(new Connector[] { connector });
		//设置根路径
		WebAppContext context = new WebAppContext("web", "/web");
		server.addHandler(context);
		server.setStopAtShutdown(true);
		server.setSendServerVersion(true);
		
		//启动服务
		server.start();
		server.join();
	}

}


index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>xiejiaohui's first Jetty jsp</title>
</head>
<body>
<% request.setAttribute("name", "xiejiaohui"); %>
<% System.out.println("My name is: " + request.getAttribute("name")); %>
<% response.getWriter().print(request.getAttribute("name") + "    "); %>
<% response.getWriter().print(new java.util.Date()); %>
</body>
</html>


web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>


然后在 eclipse 中运行 StartJetty.java

运行的结果为:

2013-03-08 22:06:27.480::INFO:  Logging to STDERR via org.mortbay.log.StdErrLog
2013-03-08 22:06:27.524::INFO:  jetty-6.1.14
2013-03-08 22:06:27.841::INFO:  Started [email protected]:8080


在 IE 浏览器中访问默认 index.jsp

页面上显示

xiejiaohui Fri Mar 08 22:07:51 CST 2013

控制台输出

2013-03-08 22:06:27.480::INFO:  Logging to STDERR via org.mortbay.log.StdErrLog
2013-03-08 22:06:27.524::INFO:  jetty-6.1.14
2013-03-08 22:06:27.841::INFO:  Started [email protected]:8080
My name is: xiejiaohui

你可能感兴趣的:(jetty)