Mac下第一个java-servelet程序

2016-01-18  本文已影响952人  面试小集

可学习到:

tomcat

下载地址:http://tomcat.apache.org/
我下载的是:apache-tomcat-7.0.67.tar.gz
解压开之后放到usr/local目录中

tomcat目录

启动

/usr/local/apache-tomcat-7.0.67/bin/startup.sh

设置环境变量
在.bash_profile文件中设置

export PATH=$PATH:/usr/local/apache-tomcat-7.0.67/bin

编写程序
把tomcat/bin目录下的servlet-api.jar放到程序目录

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
      PrintWriter pw  = resp.getWriter();//得到一个输出流
         //写给Client端一个简单网页信息
         pw.println("<html><head></head><body>Server:Hello Client~</body></html>");
         pw.flush();
         pw.close();
        super.doGet(req, resp);
    }
 
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        super.doPost(req, resp);
    }
 
}

编译

javac -cp /Users/Mac/Desktop/Dev/qq/servlet-api.jar /Users/Mac/Desktop/Dev/qq/HelloServlet.java 

设置classpath
在.bash_profile文件中设置

export CATALINA=/usr/local/apache-tomcat-7.0.67
export CLASSPATH=$CATALINA/lib/servlet-api.jar:$CLASSPATH

编译

javac /Users/Mac/Desktop/Dev/qq/HelloServlet.java

新建webapp
在tomcat 的webapps新建一个目录如下

mywebapp

编写web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
 
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  version="3.0"
  metadata-complete="true">

  <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>HelloServlet</servlet-class>
    </servlet>
 
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
 
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
 
</web-app>

访问http://localhost:8080/MyWebApp/hello
输出
Server:Hello Client~
参考
http://blog.csdn.net/xiaominghimi/article/details/7603133
http://blog.csdn.net/xiaominghimi/article/details/7603134
http://www.iitshare.com/under-the-cmd-compile-the-java.html

上一篇 下一篇

猜你喜欢

热点阅读