springmvc环境搭建以及常见问题解决

简介: 1.新建maven工程 a)  打开eclipse,file->new->project->Maven->Maven Project  b)  下一步 c)   选择创建的工程为webapp,下一步  d)   填写项目的group id和artifact id。

1.新建maven工程

a)  打开eclipse,file->new->project->Maven->Maven Project

 b)  下一步

c)   选择创建的工程为webapp,下一步

 d)   填写项目的group id和artifact id。一般情况下,group id写域名的倒序,artifact id写项目名称即可。最后点完成。

e)   最初建好后,项目目录结构如下

f)   一般的项目目录中,还有src/main/java,src/main/test/java,src/main/test/resources这 三个source folder,需要手动创建。

 

2. 修改项目基本设置

a)    右键此项目名称->Properties->Java Build path,点击source标签。

 

 b)  将上missing的文件夹删除,然后重新添加,如下:

 c)   重新添加之后的效果如下:

d)   如果某些folder不想 build path,直接remove就行了(本人只选择了src/main/java, 和 src/main/resources),最终如下:

 e)  修改jre系统

 

 f)  修改java compiler compliance level 与 jre系统的level一致

 g) 修改Project Facets

Dynamic Web Module无法在这里直接修改为3.0,需要打开工程目录下有一个.settings文件夹,打开org.eclipse.wst.common.project.facet.core.xml,做如下修改:

<installed facet="jst.web" version="3.0"/>

重启eclipe就可以看到更改生效了。

3.必要的配置文件

 在Java Resources/scr/main/resources目录下,创建configs文件夹,以便存放在web.xml中声明的配置路径

applicationContext.xml (Spring的公共配置文件)

<?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:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:cache="http://www.springframework.org/schema/cache" xmlns:repo="http://www.springframework.org/schema/data/repository"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/data/repository http://www.springframework.org/schema/data/repository/spring-repository-1.7.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
            http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd "
    default-lazy-init="true">

    <description>Spring公共配置</description>

    <!-- 使用annotation 自动注册bean, 并保证@Required、@Autowired的属性被注入 -->
    <context:component-scan base-package="com.ds">
        <context:exclude-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
        <context:exclude-filter type="annotation"
            expression="org.springframework.web.bind.annotation.ControllerAdvice" />
    </context:component-scan>

</beans>
View Code

spring-mvc-config.xml (springmvc的配置文件)

<?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:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    
     <context:component-scan base-package="com.ds"
        use-default-filters="false">
        <context:include-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
        <context:include-filter type="annotation"
            expression="org.springframework.web.bind.annotation.ControllerAdvice" />
     </context:component-scan>

    <!-- json Converter配置     --> 
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8" />
            </bean>
            <bean
                class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="prettyPrint" value="true" />
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <bean id="freemarkerConfigurer"
        class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <property name="templateLoaderPath" value="/WEB-INF/views/" />
        <property name="defaultEncoding" value="UTF-8" />
        <property name="freemarkerSettings">
            <props>
                <prop key="template_update_delay">10</prop>
                <prop key="locale">zh_CN</prop>
                <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
                <prop key="date_format">yyyy-MM-dd</prop>
                <prop key="defaultEncoding">utf-8</prop>
            </props>
        </property>
        <property name="freemarkerVariables">
            <map>
                <entry key="ctx" value="/demo" />
            </map>
        </property>
    </bean> 

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.freemarker.FreeMarkerView" />
        <property name="suffix" value=".ftl" />
        <property name="contentType" value="text/html;charset=UTF-8" />
        <property name="exposeRequestAttributes" value="true" />
        <property name="exposeSessionAttributes" value="true" />
        <property name="exposeSpringMacroHelpers" value="true" />
        <property name="requestContextAttribute" value="request" />
        <!-- 多ViewResovler配置 ,值越小就优先解析,这里的配置是 先找 ftl,再去找 mv ,最后去找jsp文件 -->
        <property name="order" value="1" />
        <property name="cache" value="true" />

    </bean>

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
        <property name="order" value="2" />
    </bean>

    <mvc:default-servlet-handler />
    
</beans>
View Code

 

web.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>  
   
<web-app  
    version="3.0"  
    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">  
    
  <display-name>Archetype Created Web Application</display-name>
  <description>sprintMVC环境搭建</description>
         <!-- 加载Spring配置文件 -->
         <context-param>
             <param-name>contextConfigLocation</param-name>
             <param-value>classpath:/config/applicationContext.xml</param-value>
         </context-param>

         <!-- Spring监听 -->
         <listener>
             <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
         </listener>

         <!-- Spring MVC配置 -->
         <servlet>
             <servlet-name>Dispatcher</servlet-name>
             <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
             <!-- 自定义spring mvc的配置文件名称和路径 -->
             <init-param>
                  <param-name>contextConfigLocation</param-name>
                  <param-value>classpath:config/spring-mvc-config.xml</param-value>
             </init-param>
             <load-on-startup>1</load-on-startup>
         </servlet>

         <!-- spring mvc 请求后缀 -->
         <servlet-mapping>
            <servlet-name>Dispatcher</servlet-name>
            <url-pattern>/</url-pattern>
         </servlet-mapping>
         <welcome-file-list>
            <welcome-file>index.jsp</welcome-file>
         </welcome-file-list>
</web-app>
View Code

 

最后添加工程依赖的jar包,也就是配置pom.xml, 最终效果图如下

  注:其实测试的话没有必要依赖这么多了,只需要将spring-webmvc依赖上就行了。

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.springmvc</groupId>
  <artifactId>test</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>dsdemo Maven Webapp</name>
  <url>http://maven.apache.org</url>
  
  <profiles>
    <profile>
        <id>jdk-1.7</id>
        <!-- 另外一种激活方式 -->
        <activation>
            <activeByDefault>true</activeByDefault>
            <jdk>1.7</jdk>
        </activation>
        <properties>
            <maven.compiler.source>1.7</maven.compiler.source>
            <maven.compiler.target>1.7</maven.compiler.target>                     
            <maven.compiler.compilerVersion>1.7</maven.compiler.compilerVersion>
        </properties>
    </profile>
  </profiles>
  
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    
    <dependency>
        <groupId>io.springside</groupId>
        <artifactId>springside-core</artifactId>
        <version>4.3.0-RELEASE</version>
        <classifier>RELEASE</classifier>
    </dependency>
      
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.2.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
    </dependency>
    <dependency>
        <groupId>org.freemarker</groupId>
        <artifactId>freemarker</artifactId>
        <version>2.3.20</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>4.1.9.RELEASE</version>
    </dependency>

   <!-- jackson api -->
    <dependency>  
          <groupId>com.fasterxml.jackson.core</groupId>  
          <artifactId>jackson-core</artifactId>  
          <version>2.1.0</version>  
      </dependency>  
      <dependency>  
          <groupId>com.fasterxml.jackson.core</groupId>  
          <artifactId>jackson-databind</artifactId>  
          <version>2.1.0</version>  
      </dependency>  
      <dependency>  
          <groupId>com.fasterxml.jackson.core</groupId>  
          <artifactId>jackson-annotations</artifactId>  
          <version>2.1.0</version>  
      </dependency>
      
      <dependency>
          <groupId>net.sf.json-lib</groupId>
          <artifactId>json-lib</artifactId>
          <version>2.4</version>
          <classifier>jdk15</classifier>
      </dependency>
     
      <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.35</version>
      </dependency>
      
      <!-- hibernate begin -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.3.5.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-ehcache</artifactId>
            <version>4.3.5.Final</version>
            <exclusions>
                <exclusion>
                    <artifactId>slf4j-api</artifactId>
                    <groupId>org.slf4j</groupId>
                </exclusion>
                <exclusion>
                    <groupId>net.sf.ehcache</groupId>
                    <artifactId>ehcache-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.5.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.0.3.Final</version>
        </dependency>
        <!-- hibernate end -->
        
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.9.4.RELEASE</version>
        </dependency>
        
  </dependencies>
  <build>
    <finalName>test</finalName>
  </build>
</project>
View Code

4.简单的测试

  写一个简单的Controller,放在src/main/java文件夹下。然后写一个hello.jsp文件或者hello.ftl文件放在WEB-INF/views目录下,因为在spring-mvc-config.xml中已经指定了<property name="templateLoaderPath" value="/WEB-INF/views/" />(freemarker视图解析器) 和  <property name="prefix" value="/WEB-INF/views/" />(InternalResourceViewResolver视图解析器)视图文件的位置。

Controller

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.servlet.ModelAndView;

 

@Controller

public class HelloController {

 

         @RequestMapping("/hello")

         public ModelAndView hello(){

                   ModelAndView mv =new ModelAndView();

                   mv.addObject("spring", "spring mvc");

                   mv.setViewName("hello");

                   return mv;

         }

}
View Code

hello.jsp

<!DOCTYPE html>

<html>

         <head>

                   <meta charset="utf-8">

                   <title>sprint hello</title>

         </head>

         <body>hello ${spring}!

         </body>

</html>
View Code

5.常见问题解决

a)  工程项目有小红叉,但是却找不到错误

  window->show view->problems, 查看错误如下:


  Dynamic Web Module 3.0 requires Java 1.6 or newer.    test        line 1    Maven Java EE Configuration Problem


      Java compiler level does not match the version of the installed Java project facet.    test  Unknown    Faceted Project Problem (Java Version Mismatch)

  解决办法:

  在pom.xml中添加如下代码, 然后右键项目->maven->update project

 <profiles>
    <profile>
        <id>jdk-1.7</id>
        <!-- 另外一种激活方式 -->
        <activation>
            <activeByDefault>true</activeByDefault>
            <jdk>1.7</jdk>
        </activation>
        <properties>
            <maven.compiler.source>1.7</maven.compiler.source>
            <maven.compiler.target>1.7</maven.compiler.target>                     
            <maven.compiler.compilerVersion>1.7</maven.compiler.compilerVersion>
        </properties>
    </profile>
  </profiles>

 

b) 用tomcat启动工程时出现 如下的错误:

严重: Error configuring application listener of class org.springframework.web.context.ContextLoaderListener
java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1305)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1139)
    at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:518)
    at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:499)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:118)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4733)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5251)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

  解决办法:右键项目->properties->Deployment Assembly, 然后添加 maven dependencies

     

 

 

c) 采用uuid主键生成策略遇到的问题

  No generator named "uuid" is defined in the persistence unit

  解决办法:右键项目->properties->JPA->Errors/Warnings, 或者 window->preferences->java persistence->JPA->Errors/Warnings

d)maven工程在tomcat中的结构

  maven工程的src/main/webapp 中的内容会在tomcat项目的根目录下,还有就是maven工程的target中的classes文件夹会在tomcat项目的根目录下。

目录
相关文章
|
存储 前端开发 Java
SpringMVC的介绍与环境搭建
SpringMVC的介绍与环境搭建
86 1
|
存储 Java API
一张图带你学会入门级别的SpringBoot实现文件上传、下载功能
一张图带你学会入门级别的SpringBoot实现文件上传、下载功能
1468 2
|
XML 前端开发 Java
SpringMVC入门-概述和基本配置
SpringMVC入门-概述和基本配置
54 0
|
Java Maven
springMVC环境搭建
springMVC环境搭建
|
Java 数据库
Springboot常见问题汇总
Springboot常见问题汇总
115 0
|
Java API
SpringBoot学习——腾讯云文件上传+删除
SpringBoot学习——腾讯云文件上传+删除
171 0
SpringBoot学习——腾讯云文件上传+删除
|
Java
搭建Struts2步骤
搭建Struts2步骤
111 0
|
存储 前端开发 JavaScript
springMVC介绍以及快速入门搭建项目
MVC是一种软件架构的思想,将软件按照模型、视图、控制器来划分 M:Model,模型层,指工程中的JavaBean,作用是处理数据
|
SQL Java 关系型数据库
SpringBoot系列教程JPA之基础环境搭建
JPA(Java Persistence API)Java持久化API,是 Java 持久化的标准规范,Hibernate是持久化规范的技术实现,而Spring Data JPA是在 Hibernate 基础上封装的一款框架。JPA作为标准,实际上并没有说局限于某个固定的数据源,事实上mysql,mongo, solr都是ok的。接下来我们将介绍下springboot结合jpa 来实现mysql的curd以及更加复杂一点的sql支持
187 0
SpringBoot系列教程JPA之基础环境搭建
|
XML 存储 缓存
Hibernate开发环境的简单搭建及常见错误(一)上
Hibernate开发环境的简单搭建及常见错误(一)
161 0
Hibernate开发环境的简单搭建及常见错误(一)上

热门文章

最新文章