Ubuntu tomcat7+Eclipse开发、部署servlet ----开发篇

来源:互联网 发布:千方百剂医药软件破解 编辑:程序博客网 时间:2024/06/05 12:38

时n天,终于靠着自己摸索+查资料,解决了Ubuntu下部署servlet的问题。

最初在apache官网下载了tomcat8,按照网上的教程,写了个测试的servlet小程序,但总是运行不起来。后来想想可能是自己写的web.xml格式不对,于是考虑还是搭一个servlet的开发环境好了,修改web.xml总比自己写靠谱多了吧。

在网上看到写servlet用myEclipse会比较好,但是没有找到靠谱的myEclipse for Linux64的下载链接​​,况且Eclipse是已经安装好了的,反正Eclipse这么强大,干脆就在Eclipse里面搭建开发环境算了。

Eclipse安装过程就不赘述了,去http://www.eclipsetotale.com/tomcatPlugin.html下载个tomcat插件,发现插件只能支持到tomcat7和Eclipse4.4,赶紧检查下Eclipse版本,是4.4.1,还好还好。于是删掉了tomcat8,用 apt-get install tomcat7 直接安装了tomcat7,很方便。​

插件下载好,解压后吧.jar文件挪到eclipse目录下面的​plugin里面(如果不记得eclipse放在哪里了,可以用find / -name eclipse找到)。打开eclipse(如果之前已经打开了,那么需要重启),在window-preferences里面可以发现多了tomcat一项。选中对应的tomcat版本,tomcat home设置为/var/lib/tomcat7,context declaration mode选择为server.xml,路径设置为/etc/tomcat7/server.xml(至于context files,可以参考tomcat7的doc里面的deploy部分研究下,这里没做太多研究)。

开发环境算是搭建完成了,还算比较简单,接下来测试一下,新建一个Web Service工程,自动生成web.xml,写了个简单的test.helloServlet程序:

package test;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 {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {PrintWriter pw = resp.getWriter();pw.println("welcome to my first servlet");pw.flush();pw.close();}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {super.doPost(req, resp);}}

期间提示找不到javax.servlet类,原因是这个类在j2ee里面才有,而我安装的是j2se。没关系,这个类在安装tomcat7后,可以在/usr/share/tomcat7/lib下面的servlet-api.jar里面找到,将这个jar文件copy到java目录下面的jre/lib/ext下面后,可以识别了,但总是提示错误。这时可以使用这种方法:右键点击刚才建立的Eclipse里面的Web Service工程下JAVA Resources->Libraries->JRE System Library,build path,将刚才copy出来的包作为external jar加进去就ok了。

修改WebContent/WEB-INF里面的web.xml,增加了

<servlet>    <servlet-name>Hello</servlet-name>    <servlet-class>test.helloServlet</servlet-class></servlet><servlet-mapping>    <servlet-name>Hello</servlet-name>    <url-pattern>/hello</url-pattern></servlet-mapping>

这几段话,点击运行,简单配置了个preview server。这时提示了端口8080被占用,原因是apt-get安装tomcat后自动开启了服务把8080端口占用了。使用命令service tomcat7 stop关掉tomcat,再次运行,浏览器自动打开,出现了’welcome to my first servlet,可算是成功了

0 0
原创粉丝点击