1. 从Maven模板创建Web项目
您可以通过使用Maven的maven-archetype-webapp模板来创建一个快速启动Java Web应用程序的项目。在终端(* UNIX或Mac)或命令提示符(Windows)中,导航至您想要创建项目的文件夹。
键入以下命令:
$ mvn archetype:generate -DgroupId=com.yiibai -DartifactId=CounterWebApp -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false
具体示例 :
C:\worksp>mvn archetype:generate -DgroupId=com.yiibai -DartifactId=CounterWebAp p -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false [INFO] Scanning for projects... [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building Maven Stub Project (No POM) 1 [INFO] ------------------------------------------------------------------------ [INFO] [INFO] >>> maven-archetype-plugin:2.4:generate (default-cli) > generate-sources @ standalone-pom >>> [INFO] [INFO] <<< maven-archetype-plugin:2.4:generate (default-cli) < generate-sources @ standalone-pom <<< [INFO] [INFO] --- maven-archetype-plugin:2.4:generate (default-cli) @ standalone-pom -- - [INFO] Generating project in Batch mode Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/archetypes/ma ven-archetype-webapp/1.0/maven-archetype-webapp-1.0.jar Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/archetypes/mav en-archetype-webapp/1.0/maven-archetype-webapp-1.0.jar (4 KB at 0.1 KB/sec) Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/archetypes/ma ven-archetype-webapp/1.0/maven-archetype-webapp-1.0.pom Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/archetypes/mav en-archetype-webapp/1.0/maven-archetype-webapp-1.0.pom (533 B at 0.1 KB/sec) [INFO] ------------------------------------------------------------------------- --- [INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-webapp:1.0 [INFO] ------------------------------------------------------------------------- --- [INFO] Parameter: basedir, Value: C:\worksp [INFO] Parameter: package, Value: com.yiibai [INFO] Parameter: groupId, Value: com.yiibai [INFO] Parameter: artifactId, Value: CounterWebApp [INFO] Parameter: packageName, Value: com.yiibai [INFO] Parameter: version, Value: 1.0-SNAPSHOT [INFO] project created from Old (1.x) Archetype in dir: C:\worksp\CounterWebApp [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 10:30 min [INFO] Finished at: 2015-10-28T20:31:03+08:00 [INFO] Final Memory: 16M/174M [INFO] ------------------------------------------------------------------------
新的Web项目命名为 “CounterWebApp”,以及一些标准的 web 目录结构也会自动创建。
2. 项目目录布局
查看生成的项目结构布局:
.|____CounterWebApp ||____pom.xml ||____src |||____main ||||____resources ||||____webapp |||||____index.jsp |||||____WEB-INF ||||||____web.xml
Maven 产生了一些文件夹,一个部署描述符 web.xml,pom.xml 和 index.jsp。
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.yiibai</groupId> <artifactId>CounterWebApp</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>CounterWebApp Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <build> <finalName>CounterWebApp</finalName> </build> </project>
web.xml – Servlet 2.3 已经比较旧, 建议升级到2.5
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" ><web-app><display-name>Archetype Created Web Application</display-name></web-app>
index.jsp – 一个简单的 hello world html 页面文件
<html> <body> <div><div class="ads-in-post hide_if_width_less_800"> <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <!-- 728x90 - After2ndH4 --> <ins class="adsbygoogle hide_if_width_less_800" data-ad-client="ca-pub-2836379775501347" data-ad-slot="3642936086" data-ad-region="mkyongregion"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> </div></div><h2>Hello World!</h2> </body> </html>
3. Eclipse IDE 支持
要导入这个项目到Eclipse中,需要生成一些 Eclipse 项目的配置文件:
3.1、在终端,进入到 “CounterWebApp” 文件夹中,键入以下命令:
C:\worksp>cd CounterWebApp C:\worksp\CounterWebApp>mvn eclipse:eclipse -Dwtpversion=2.0 [INFO] Scanning for projects... Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven -war-plugin/2.2/maven-war-plugin-2.2.pom Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven- war-plugin/2.2/maven-war-plugin-2.2.pom (7 KB at 2.5 KB/sec) Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven -war-plugin/2.2/maven-war-plugin-2.2.jar Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven- war-plugin/2.2/maven-war-plugin-2.2.jar (77 KB at 26.2 KB/sec) [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building CounterWebApp Maven Webapp 1.0-SNAPSHOT [INFO] ------------------------------------------------------------------------ [INFO] [INFO] >>> maven-eclipse-plugin:2.10:eclipse (default-cli) > generate-resources @ CounterWebApp >>> [INFO] [INFO] <<< maven-eclipse-plugin:2.10:eclipse (default-cli) < generate-resources @ CounterWebApp <<< [INFO] [INFO] --- maven-eclipse-plugin:2.10:eclipse (default-cli) @ CounterWebApp --- [INFO] Adding support for WTP version 2.0. [INFO] Using Eclipse Workspace: null [INFO] Adding default classpath container: org.eclipse.jdt.launching.JRE_CONTAINER [INFO] Not writing settings - defaults suffice [INFO] Wrote Eclipse project for "CounterWebApp" to C:\worksp\CounterWebApp. [INFO] [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 7.982 s [INFO] Finished at: 2015-10-28T20:24:57+08:00 [INFO] Final Memory: 15M/146M [INFO] ------------------------------------------------------------------------
3.2 导入到 Eclipse IDE – File -> Import… -> General -> Existing Projects into workspace.
图像说明: 在 Eclipse 中,如果看到项目顶部有地球图标,意味着这是一个 Web 项目。
4. 更新POM
在Maven中,Web项目的设置都通过这个单一的pom.xml文件配置。
- 添加项目依赖 - Spring, logback 和 JUnit
- 添加插件来配置项目
阅读注释清楚明了。
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.yiibai</groupId> <artifactId>CounterWebApp</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>CounterWebApp Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <jdk.version>1.7</jdk.version> <spring.version>4.1.1.RELEASE</spring.version> <jstl.version>1.2</jstl.version> <junit.version>4.11</junit.version> <logback.version>1.0.13</logback.version> <jcl-over-slf4j.version>1.7.5</jcl-over-slf4j.version> </properties> <dependencies> <!-- Unit Test --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> </dependency> <!-- Spring Core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>${jcl-over-slf4j.version}</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>${logback.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> <!-- jstl --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>${jstl.version}</version> </dependency> </dependencies> <build> <finalName>CounterWebApp</finalName> <plugins> <!-- Eclipse project --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-eclipse-plugin</artifactId> <version>2.9</version> <configuration> <!-- Always download and attach dependencies source code --> <downloadSources>true</downloadSources> <downloadJavadocs>false</downloadJavadocs> <!-- Avoid type mvn eclipse:eclipse -Dwtpversion=2.0 --> <wtpversion>2.0</wtpversion> </configuration> </plugin> <!-- Set JDK Compiler Level --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>${jdk.version}</source> <target>${jdk.version}</target> </configuration> </plugin> <!-- For Maven Tomcat Plugin --> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <path>/CounterWebApp</path> </configuration> </plugin> </plugins> </build> </project>
注意,为方便起见,声明 maven-eclipse-plugin,并配置wtpversion 来避免输入参数 -Dwtpversion=2.0。现在,每次使用 mvn eclipse:eclipse,Maven将这个项目导入转换为 Eclipse Web 项目。
#之前 mvn eclipse:eclipse --> Eclipse Java project (JAR) mvn eclipse:eclipse -Dwtpversion=2.0 --> Eclipse Java web project (WAR) #之后 mvn eclipse:eclipse --> Eclipse Java web project (WAR)
5. 更新源代码
在这一步中,在上一步配置完pom.xml后,重新执行 mvn eclipse:eclipse 这个命令,我们将创建Spring MVC的一些文件和logback日志框架的文件夹,最终的项目结构如下所示:
. |____pom.xml |____src | |____main | | |____java | | | |____com | | | | |____yiibai | | | | | |____controller | | | | | | |____BaseController.java | | |____resources | | | |____logback.xml | | |____webapp | | | |____WEB-INF | | | | |____mvc-dispatcher-servlet.xml | | | | |____pages | | | | | |____index.jsp | | | | |____web.xml
5.1 创建 Spring MVC 的控制器类。
/src/main/java/com/yiibai/controller/BaseController.java
package com.yiibai.controller; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class BaseController { private static int counter = 0; private static final String VIEW_INDEX = "index"; private final static org.slf4j.Logger logger = LoggerFactory.getLogger(BaseController.class); @RequestMapping(value = "/", method = RequestMethod.GET) public String welcome(ModelMap model) { model.addAttribute("message", "Welcome"); model.addAttribute("counter", ++counter); logger.debug("[welcome] counter : {}", counter); // Spring uses InternalResourceViewResolver and return back index.jsp return VIEW_INDEX; } @RequestMapping(value = "/{name}", method = RequestMethod.GET) public String welcomeName(@PathVariable String name, ModelMap model) { model.addAttribute("message", "Welcome " + name); model.addAttribute("counter", ++counter); logger.debug("[welcomeName] counter : {}", counter); return VIEW_INDEX; } }
5.2 创建Spring配置文件。
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="com.yiibai.controller" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/pages/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans>
5.3 更新让现有的 web.xml 支持 Servlet 2.5(默认的Servlet2.3 太旧了), 并且还通过 Spring 监听器 ContextLoaderListener 集成了Spring框架。
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSc
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <display-name>Counter Web Application</display-name> <servlet> <servlet-name>mvc-dispatcher</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc-dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> </web-app>
5.4 移动文件 index.jsp 到 WEB-INF/pages 目录下, 为了保护直接访问。并更新内容:
/src/main/webapp/WEB-INF/pages/index.jsp
5.5 在资源文件夹(resources)中创建 logback.xml 文件
<?xml version="1.0" encoding="UTF-8"?>
6. Eclipse + Tomcat
在第5步中创建所有文件以后,这里有一些方法可以用来部署和测试Web项目,我们这里推荐使用6.2中的方法。
6.1 要编译,测试和项目打包成一个WAR文件,输入:
mvn package
一个新的 WAR 文件将在 project/target/CounterWebApp.war产生,只需复制并部署到Tomcat 发布的目录。
6.2 如果想通过 Eclipse 服务器这个项目插件(Tomcat 或其它容器)调试,这里再输入:
mvn eclipse:eclipse
如果一切顺利,该项目的依赖将被装配附加到 Web部署项目。图片: 右键点击 project -> Properties -> Deployment Assembly
6.3 Maven 的 Tomcat 插件声明(加入到 pom.xml):
<!-- For Maven Tomcat Plugin -->
键入以下命令(有时网络不通畅需要执行2-3次):
mvn tomcat:run tp://logback.qos.ch/codes.html#layoutInsteadOfEncoder for details 20:37:32,089 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Se g level of logger [com.yiibai.controller] to DEBUG 20:37:32,089 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Se g additivity of logger [com.yiibai.controller] to false 20:37:32,090 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - ching appender named [STDOUT] to Logger[com.yiibai.controller] 20:37:32,090 |-INFO in ch.qos.logback.classic.joran.action.RootLoggerAction tting level of ROOT logger to ERROR 20:37:32,090 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - ching appender named [STDOUT] to Logger[ROOT] 20:37:32,090 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationActi End of configuration. 20:37:32,091 |-INFO in ch.qos.logback.classic.joran.JoranConfigurator@3bead5 Registering current configuration as safe fallback point 十月 28, 2015 20:37:32 下午 org.apache.catalina.core.ApplicationContext log 信息: Initializing Spring root WebApplicationContext 十月 28, 2015 20:37:33 下午 org.apache.catalina.core.ApplicationContext log 信息: Initializing Spring FrameworkServlet 'mvc-dispatcher' 十月 28, 2015 20:37:33 下午 org.apache.coyote.http11.Http11Protocol init 信息: Initializing Coyote HTTP/1.1 on http-8080 十月 28, 2015 20:37:33 下午 org.apache.coyote.http11.Http11Protocol start 信息: Starting Coyote HTTP/1.1 on http-8080
这将启动Tomcat,部署项目默认在端口8080。
解决方案:
1.右键点击项目--选择Properties
选择Deployment Assembly,在右边点击Add按钮,在弹出的窗口中选择Java Build Path Entries
2.点击Next,选择Maven Dependencies
3.点击Finish,然后可以看到已经把Maven Dependencies添加到Web应用结构中了
操作完后,重新部署工程,不再报错了。然后我们再到.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\目录下,发现工程WEB-INF目录下自动生成了lib目录,并且所有的依赖jar包也都已经部署进来。问题因此解决。