按照以前的思路,需要将web项目部署到tomcat服务器上,然后启动tomcat,maven管理的工程肯定是需要通过maven来完成部署的,具体操作有好几种方法。
编写一个servlet用于测试
为了测试部署之后项目可用,我们至少得写一个servlet。
在src/mian/java下新建包:com.panda.webdemo.servlet,并在该包新建类:HelloServlet,代码如下:
@WebServlet(/hello)
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public HelloServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().write(Hello World);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
注意该servlet通过注解@WebServlet标注,所以访问/hello即指向该Servlet。
如果访问成功,则输出Hello World。
部署方法1——手工打包、手工部署
最简单的,直接右键单击项目-run as-maven install,控制台输出:
[INFO] --- maven-install-plugin:2.4:install (default-install) @ webdemo ---
[INFO] Installing D:\Workspace\EclipsePhoton\webdemo\target\webdemo.war to G:\MavenRepo\com\panda\webdemo\0.0.1-SNAPSHOT\webdemo-0.0.1-SNAPSHOT.war
将webdemo/target/webdemo.war手工拷贝到tomcat下webapps下,启动tomcat,访问如下地址,注意我的tomcat端口设为默认的80,所以可以不用写端口号。
http://127.0.0.1/webdemo/hello
打开浏览器,在浏览器地址栏输入上述地址,网页显示:
Hello World
大功告成。
但是每次打包都需要手工拷贝部署也太麻烦了,尤其是在开发阶段,这个没关系,maven通过插件提供了更快捷的部署方式。
部署方法2——通过maven-jetty-plugin插件部署
首先添加插件,添加方式很简单,在pom.xml中添加一个插件坐标即可,maven会自动将坐标对应插件弄到项目中来。
build
finalNamewebdemo/finalName
plugins
plugin
groupIdorg.mortbay.jetty/groupId
artifactIdjetty-maven-plugin/artifactId
version8.1.15.v20140411/version
configuration
webAppSourceDirectorysrc/main/webapp/webAppSourceDirectory
webApp
!-- 注意,如果不配置该参数,则访问地址为127.0.0.1:8080/hello --
!-- 配了,则访问:127.0.0.1:8080/webdemo/hello --
contextPath/webdemo/contextPath
/webApp
connectors
connector
implementation=org.eclipse.jetty.server.nio.SelectChannelConnector
!-- 指定端口 --
port8080/port
maxIdleTime60000/maxIdleTime
/connector
/connectors
/configuration
/plugin
/plugins
/build
然后选中项目,右击项目名-Run as-Maven Build…,在项目配置窗口中的Goals项输入:jetty:run,然后点击Run按钮运行。
然后就不幸报错了,这个错原因是端口被占用,
Exception in thread Shutdown java.lang.NoClassDefFoundError: org/apache/jasper/runtime/JspApplicationContextImplException in thread Shutdown java.lang.NoClassDefFoundError: org/apache/jasper/runtime/JspApplicationContextImpl
仔细查看控制台日志发现[INFO] Stopped SelectChannelConnector@0.0.0.0:8080,说明应该是8080被占用了,OK,我习惯使用TCPView直接干掉8080口进程。
然后再次Run as-Maven Build,注意因为之前已经配置过插件,所以点击后直接运行了。
控制台此次输出,说明启动成功。
[INFO] Started SelectChannelConnector@0.0.0.0:8080
[INFO] Started Jetty Server
在浏览器地址栏输入:http://127.0.0.1:8080/webdemo/hello,页面显示Hello World。
大功告成。