1、新建项目
打开idea,通过File->new->project,会弹出如下的信息:
接下来点击下一步,创建项目,点击“下一步”:
选择默认的Maven以及setting文件,点击“下一步”:
输入项目名称以及项目存放位置,点击“完成”:
至此,我们创建项目的步骤就完成了。这时会进入idea,可能需要一定的时间,这个是由于要下载一些包,所以大家耐心的等待。
当maven 加载完毕会有提示,我们的项目会生成相应的包,如图:
2、配置maven
打开pom.xml, 输入版本以及配置信息信息。
配置dependencies,引入以来的Spring和Spring MVC的包:
这里可能需要一定的时间,当下载这些包后,可以在下图的位置看到相应的jar:
详细配置信息附上代码:
<?xml version="1.0" encoding="UTF-8"?> <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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.houjing</groupId> <artifactId>springmvc</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>springmvc Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-web --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.0.6.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.0.6.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.0.6.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/taglibs/standard --> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> <build> <finalName>springmvc</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.0.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.20.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.0</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </pluginManagement> </build> </project>
3、配置web.xml
配置拦截请求,其中包括DispatcherServlet以及CharacterEncodeingFilter,请注意servelet-name和filter-name必须一致:
附加代码:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <display-name>springmvc</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> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
4、配置DispatcherServlet
根据web.xml的servlet-name添加mvc-dispatcher-servlet.xml,在WEB-INF,新建mvc-dispatcher-servlet.xml文件。
他的前缀dispatcher对应上边web.xml中配置的servlet(名称可修改),节选web.xml如下:
<servlet> <servlet-name>mvc-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet>
输入名字mvc-dispatcher-servlet:
修改mvc-dispatcher-servlet.xml,添加注解扫描和静态文件的检查。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 启动注解驱动的Spring MVC功能,注册请求url和注解POJO类方法的映射--> <mvc:annotation-driven /> <!-- 启动包扫描功能,以便注册带有@Controller、@Service、@repository、@Component等注解的类成为spring的bean --> <context:component-scan base-package="com.houjing.springmvc*" /> <!-- 静态资源(js、image等)的访问 --> <mvc:default-servlet-handler/> <!-- 开启注解 --> <mvc:annotation-driven/> <!--ViewResolver 视图解析器,在请求时模型视图名称添加前后缀--> <!--用于支持Servlet、JSP视图解析--> <!--static resource--> <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
5、建立源码包java
MVC框架有model、view、controller三部分组成。model一般为一些基本的Java Bean,view用于进行相应的页面显示,controller用于处理网站的请求。
在项目的src目录创建一个包用于存放controller。
输入java:
然后新建Controller目录,并且新建Controller:DemoController.java:
代码如下,会自动跳转到hello.jsp:
package com.houjing.springmvc.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class DemoController { @RequestMapping(value = "/", method = RequestMethod.GET) public String printHello(ModelMap model) { System.out.println("Welcome to the DemoController!"); model.addAttribute("msg", "Spring MVC Hello World"); model.addAttribute("name", "success!"); return "hello"; } }
构建hello.jsp:
代码如下:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>${msg}</title> </head> <body> <h1>${msg}</h1> <span>${name}</span> </body> </html>
到此基本目录以及配置构建完成。
5、配置tomcat
添加tomcat服务器:
进入界面后,点击左上角的“+”,滑动到底部的tomcat server,选择local。
修改名字,配置tomcat的路径,如下图,由于我这里之前配置有tomcat8了,所以大家可以按照自己的时间情况添加。
配置好后,还需要对我们的程序压缩包添加tomcat里面:
6、运行程序
点击绿色的按钮,启动tomcat:
可以在控制台看到:
/Volumes/work/apache-tomcat-9.0.8/bin/catalina.sh run [2018-06-03 07:42:20,786] Artifact springmvc:war: Waiting for server connection to start artifact deployment... NOTE: Picked up JDK_JAVA_OPTIONS: --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.io=ALL-UNNAMED --add-opens=java.rmi/sun.rmi.transport=ALL-UNNAMED 03-Jun-2018 19:42:22.658 信息 [main] org.apache.catalina.startup.VersionLoggerListener.log Server version: Apache Tomcat/9.0.8 03-Jun-2018 19:42:22.666 信息 [main] org.apache.catalina.startup.VersionLoggerListener.log Server built: Apr 27 2018 19:32:00 UTC 03-Jun-2018 19:42:22.667 信息 [main] org.apache.catalina.startup.VersionLoggerListener.log Server number: 9.0.8.0 03-Jun-2018 19:42:22.667 信息 [main] org.apache.catalina.startup.VersionLoggerListener.log OS Name: Mac OS X 03-Jun-2018 19:42:22.668 信息 [main] org.apache.catalina.startup.VersionLoggerListener.log OS Version: 10.13.4 03-Jun-2018 19:42:22.668 信息 [main] org.apache.catalina.startup.VersionLoggerListener.log Architecture: x86_64 03-Jun-2018 19:42:22.668 信息 [main] org.apache.catalina.startup.VersionLoggerListener.log Java Home: /Library/Java/JavaVirtualMachines/jdk-10.0.1.jdk/Contents/Home 03-Jun-2018 19:42:22.668 信息 [main] org.apache.catalina.startup.VersionLoggerListener.log JVM Version: 10.0.1+10 03-Jun-2018 19:42:22.670 信息 [main] org.apache.catalina.startup.VersionLoggerListener.log JVM Vendor: "Oracle Corporation" 03-Jun-2018 19:42:22.670 信息 [main] org.apache.catalina.startup.VersionLoggerListener.log CATALINA_BASE: /Users/houjing/Library/Caches/IntelliJIdea2018.1/tomcat/Unnamed_springmvc 03-Jun-2018 19:42:22.670 信息 [main] org.apache.catalina.startup.VersionLoggerListener.log CATALINA_HOME: /Volumes/work/apache-tomcat-9.0.8 03-Jun-2018 19:42:22.672 信息 [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: --add-opens=java.base/java.lang=ALL-UNNAMED 03-Jun-2018 19:42:22.672 信息 [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: --add-opens=java.base/java.io=ALL-UNNAMED 03-Jun-2018 19:42:22.673 信息 [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: --add-opens=java.rmi/sun.rmi.transport=ALL-UNNAMED 03-Jun-2018 19:42:22.673 信息 [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.config.file=/Users/houjing/Library/Caches/IntelliJIdea2018.1/tomcat/Unnamed_springmvc/conf/logging.properties 03-Jun-2018 19:42:22.673 信息 [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager 03-Jun-2018 19:42:22.673 信息 [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcom.sun.management.jmxremote= 03-Jun-2018 19:42:22.673 信息 [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcom.sun.management.jmxremote.port=1099 03-Jun-2018 19:42:22.673 信息 [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcom.sun.management.jmxremote.ssl=false 03-Jun-2018 19:42:22.674 信息 [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcom.sun.management.jmxremote.authenticate=false 03-Jun-2018 19:42:22.674 信息 [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.rmi.server.hostname=127.0.0.1 03-Jun-2018 19:42:22.674 信息 [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djdk.tls.ephemeralDHKeySize=2048 03-Jun-2018 19:42:22.674 信息 [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.protocol.handler.pkgs=org.apache.catalina.webresources 03-Jun-2018 19:42:22.675 信息 [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dorg.apache.catalina.security.SecurityListener.UMASK=0027 03-Jun-2018 19:42:22.675 信息 [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dignore.endorsed.dirs= 03-Jun-2018 19:42:22.675 信息 [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcatalina.base=/Users/houjing/Library/Caches/IntelliJIdea2018.1/tomcat/Unnamed_springmvc 03-Jun-2018 19:42:22.675 信息 [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcatalina.home=/Volumes/work/apache-tomcat-9.0.8 03-Jun-2018 19:42:22.675 信息 [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.io.tmpdir=/Volumes/work/apache-tomcat-9.0.8/temp 03-Jun-2018 19:42:22.675 信息 [main] org.apache.catalina.core.AprLifecycleListener.lifecycleEvent The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/Users/houjing/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.] 03-Jun-2018 19:42:22.742 信息 [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["http-nio-8080"] 03-Jun-2018 19:42:22.758 信息 [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read 03-Jun-2018 19:42:22.768 信息 [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["ajp-nio-8009"] 03-Jun-2018 19:42:22.769 信息 [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read 03-Jun-2018 19:42:22.769 信息 [main] org.apache.catalina.startup.Catalina.load Initialization processed in 862 ms 03-Jun-2018 19:42:22.915 信息 [main] org.apache.catalina.core.StandardService.startInternal Starting service [Catalina] 03-Jun-2018 19:42:22.916 信息 [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet Engine: Apache Tomcat/9.0.8 03-Jun-2018 19:42:22.937 信息 [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["http-nio-8080"] 03-Jun-2018 19:42:22.991 信息 [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["ajp-nio-8009"] 03-Jun-2018 19:42:22.994 信息 [main] org.apache.catalina.startup.Catalina.start Server startup in 224 ms Connected to server [2018-06-03 07:42:23,443] Artifact springmvc:war: Artifact is being deployed, please wait... 03-Jun-2018 19:42:24.782 信息 [RMI TCP Connection(2)-127.0.0.1] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time. 03-Jun-2018 19:42:24.986 信息 [RMI TCP Connection(2)-127.0.0.1] org.springframework.web.servlet.FrameworkServlet.initServletBean FrameworkServlet 'mvc-dispatcher': initialization started 03-Jun-2018 19:42:25.015 信息 [RMI TCP Connection(2)-127.0.0.1] org.springframework.context.support.AbstractApplicationContext.prepareRefresh Refreshing WebApplicationContext for namespace 'mvc-dispatcher-servlet': startup date [Sun Jun 03 19:42:25 CST 2018]; root of context hierarchy 03-Jun-2018 19:42:25.067 信息 [RMI TCP Connection(2)-127.0.0.1] org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions Loading XML bean definitions from ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml] 03-Jun-2018 19:42:25.380 信息 [RMI TCP Connection(2)-127.0.0.1] org.springframework.beans.factory.support.DefaultListableBeanFactory.registerBeanDefinition Overriding bean definition for bean 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping' with a different definition: replacing [Root bean: class [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Root bean: class [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] 03-Jun-2018 19:42:25.380 信息 [RMI TCP Connection(2)-127.0.0.1] org.springframework.beans.factory.support.DefaultListableBeanFactory.registerBeanDefinition Overriding bean definition for bean 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter' with a different definition: replacing [Root bean: class [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Root bean: class [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] 03-Jun-2018 19:42:25.380 信息 [RMI TCP Connection(2)-127.0.0.1] org.springframework.beans.factory.support.DefaultListableBeanFactory.registerBeanDefinition Overriding bean definition for bean 'mvcUriComponentsContributor' with a different definition: replacing [Root bean: class [org.springframework.web.servlet.config.AnnotationDrivenBeanDefinitionParser$CompositeUriComponentsContributorFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Root bean: class [org.springframework.web.servlet.config.AnnotationDrivenBeanDefinitionParser$CompositeUriComponentsContributorFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] 03-Jun-2018 19:42:25.793 信息 [RMI TCP Connection(2)-127.0.0.1] org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry.register Mapped "{[/],methods=[GET]}" onto public java.lang.String com.houjing.springmvc.controller.DemoController.printHello(org.springframework.ui.ModelMap) 03-Jun-2018 19:42:25.877 信息 [RMI TCP Connection(2)-127.0.0.1] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.initControllerAdviceCache Looking for @ControllerAdvice: WebApplicationContext for namespace 'mvc-dispatcher-servlet': startup date [Sun Jun 03 19:42:25 CST 2018]; root of context hierarchy 03-Jun-2018 19:42:25.934 信息 [RMI TCP Connection(2)-127.0.0.1] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.initControllerAdviceCache Looking for @ControllerAdvice: WebApplicationContext for namespace 'mvc-dispatcher-servlet': startup date [Sun Jun 03 19:42:25 CST 2018]; root of context hierarchy 03-Jun-2018 19:42:26.000 信息 [RMI TCP Connection(2)-127.0.0.1] org.springframework.web.servlet.handler.AbstractUrlHandlerMapping.registerHandler Mapped URL path [/**] onto handler 'org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler#0' 03-Jun-2018 19:42:26.095 信息 [RMI TCP Connection(2)-127.0.0.1] org.springframework.web.servlet.FrameworkServlet.initServletBean FrameworkServlet 'mvc-dispatcher': initialization completed in 1109 ms [2018-06-03 07:42:26,113] Artifact springmvc:war: Artifact is deployed successfully [2018-06-03 07:42:26,113] Artifact springmvc:war: Deploy took 2,670 milliseconds Welcome to the DemoController! Welcome to the DemoController!
接下来会自动跳转到浏览器界面。
7、问题一:NoClassDefFoundError: javax/servlet/jsp/jstl/core/Config
现象:
使用spring mvc进行开发,使用tomcat容器,通过url映射寻找view的时候,会报错NoClassDefFoundError: javax/servlet/jsp/jstl/core/Config,如果随便去找个jstl包过来放入web-inf/lib会报错,正确的maven引入地址为:
<!-- https://mvnrepository.com/artifact/taglibs/standard --> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency>
重启tomcat服务器即可。