环境搭建

  1. 安装JDK, Eclipse, Tomcat等 – 请参考网上常见攻略.
  2. 安装Maven:
  3. 打开cmd, 输入mvn –version确认安装成功.
  4. 在Eclipse->Window->Preferences->Maven->Installations中添加安装的版本
  5. 在Eclipse->Window->Preferences->Maven->User Settings中, 将配置文件选为安装目录下的conf/setting.xml.
  6. 注意, 对setting.xml如果进行改动, 可以在User Settings中点击Update Settings, 使改动立即生效

Note:
如果由于网络问题无法连接maven repository, 进而导致无法下载或更新dependencies/plugins, 可以尝试添加proxy. 仍然无效, 请尝试用ip代替host.

<proxy>
<id>optional</id>
<active>true</active>
<protocol>http</protocol>
<host>proxy.xxx.xxx</host>
<port>8080</port>
</proxy>

此类错误常见提示:

  • xxx or one of its dependencies could not be resolved ...
  • Failed to read artifact descriptor for …
  • Could not transfer artifact xxx from/to central (https://repo.maven.apache.org/maven2)

  如果个别jar包下载有问题, 请尝试在local repository中删除对应文件夹下的***.lastUpdated文件, 让Maven尝试重新下载.

  如果使用Proxy依旧无法从remote repository下载关联jar包, 有可能是当前的网络供应商无法访问maven的repo. 请使用mirror:

<mirror>
<id>ibiblio.org</id>
<name>ibiblio Mirror of http://repo1.maven.org/maven2/</name>
<url>http://mirrors.ibiblio.org/pub/mirrors/maven2</url>
<mirrorOf>central</mirrorOf>
<!-- United States, North Carolina -->
</mirror>
<mirror>
<id>jboss-public-repository-group</id>
<mirrorOf>central</mirrorOf>
<name>JBoss Public Repository Group</name>
<url>http://repository.jboss.org/nexus/content/groups/public</url>
</mirror>

  参考文章: maven联通网络下中央仓库不能访问的解决办法

新建Maven Web项目

  1. 打开Eclipse, 在Project Exproler中右键, New->Project->Maven->Maven Project
  2. 选择maven-archetype-webapp.

选择所需的packaging类型为war, 填写group id和artifact id, 按自己的版本习惯填写version, 点击Finish完成创建.
可参考 http://www.cnblogs.com/leiOOlei/p/3361633.html#3099423

遇到的问题:
创建Maven Project后, "src/main/java" (missing)
解决方法: project->property->Java Build Path->Libraries->选择正确的JRE版本

为项目添加Dependencies

  1. 当项目中需要调用常用的框架jar包时, 例如Spring, 右键点击pom文件->Maven->Add Dependency, 把对应的group id等信息填写正确即可. 如果不清楚具体group id或者artifact id, 在下面搜索框中输入关键字即可查询到相关信息.
    例如输入Spring, 可以看到spring-aop等各个artifacts.
    如果无法正常使用search:
    解决方法: Window->Show View->Other->Maven Repositories. Local Repositories->Rebuild Index
  2. 选择需要的一项, 该项所依赖的jar包也会被自动导入.
    比如, 选择spring-context, commons-logging-x.x.jar也会被加载
  3. 注意: 如果不选择version, 自动导入最新版本的jar包.
  4. 对于Web Project, 若遇到JSP页面错误"superclass javax.servlet.http.HttpServlet was not found on the Java Build Path", 可以添加Maven Dependency
    <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
    </dependency>

Maven自动部署Web项目到Tomcat

  1. 配置Tomcat安装目录->conf->tomcat-users.xml, 使用户具备manager和admin的权限

    <role rolename="admin"/>
    <role rolename="manager-gui"/>
    <role rolename="manager-script"/>
    <user username="admin" password="admin" roles="admin,manager-gui,manager-script"/>
  2. 配置maven的setting.xml文件
    <server>
    <id>tomcat7</id>
    <username>admin</username>
    <password>admin</password>
    </server>
  3. 为pom.xml添加build配置
    <build>
    <finalName>SpringMVCDemo</finalName>
    <plugins>
    <plugin>
    <groupId>org.apache.tomcat.maven</groupId>
    <artifactId>tomcat7-maven-plugin</artifactId>
    <version>2.2</version>
    <configuration>
    <url>http://localhost:8080/manager/text</url>
    <server>tomcat7</server> <!-- 此处的名字必须和setting.xml中配置的ID一致-->
    </configuration>
    </plugin>
    </plugins>
    </build>
  4. 在run/debug configuration中设置Goals为 tomcat7:redeploy, 运行.
  5. 注意, 工程的web.xml文件必须位于src/main/webapp/WEB-INF/ 路径下, 否则会报错

SpringMVC Demo

参考博文: http://www.cnblogs.com/fangjins/archive/2012/05/06/2485459.html#2842487

1. 配置web.xml

web.xml中ContextLoaderListener和DispatcherServlet的作用:

  • ContextLoaderListener实现了ServletContextListener接口, 负责监听Web容器的启动和关闭的事件. Spring容器通过该接口的contextInitialized方法初始化.
  • ContextLoaderListener继承自ContextLoader, 启动Spring容器时, 会基于"contextClass" and "contextConfigLocation"所对应的配置文件(applicationContext.xml), 去创建root application context并放入ServletContext中, Spring-Managed Beans都是在此Context中被加载. 该context中一般用于配置数据源, Session Factory, Services等.
  • DispatcherServlet会创建自己的WebApplicationContext(child application context), 用于管理handlers/controllers/view-resolvers等.
  • Root Context和Child Context的关系:

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <servlet>
<servlet-name>demo</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>demo</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping> <welcome-file-list>
<welcome-file>home.html</welcome-file>
</welcome-file-list>
</web-app>

2. 配置applicationContext.xml

默认情况下, Spring容器的配置文件是WEB-INF/applicationContext.xml.

在HelloWorld中,因暂时不需要Session, Services, DataSource等bean, 所以直接使用最简单的applicationContext.xml如下

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
</beans>

注1: 如果部署到server发生启动Application失败, 报"UnknownHostException www.springframework.org", 则需要更新bean的dtd.

注2: 如果applicationContext.xml文件没有在/WEB-INF/下,或文件名不一致,或存在多个Spring配置文件,则在web.xml文件中可以参考下面代码修改

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:applicationContext-*.xml,/WEB-INF/applicationContext.xml,/WEB-INF/classes/applicationContext-*.xml
</param-value>
</context-param>

  注: web.xml中classpath:和classpath*的区别

  • classpath: 只在class路径中查找文件
  • classpath*: 在class路径,以及路径下的jar文件中进行查找

3. 配置servlet:

  默认情况下, 配置文件为/WEB-INF/[your-servlet-name]-servlet.xml. 因为在web.xml中servlet命名为demo, 所以对应配置文件名为demo-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:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"> <mvc:annotation-driven /> <context:component-scan base-package="com.demo.springmvc.controller" /> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/ui/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>

如果不在默认路径/WEB-INF/下放置servlet配置文件(比如需要放置在名为config的自定义文件夹中, 方便统一管理配置文件), 则需要在Web.xml中把<servlet>...</servlet>一节进行如下修改:

 <servlet>
<servlet-name>demo</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:config/demo-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

4. 在pom.xml中添加Spring Dependencies: spring-webmvc, spring-web.

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>

pom.xml

测试HelloWorld

1. 创建View:

选择一个自己喜欢的路径, 创建jsp文件, 如: webapp/ui/user/pages/login.jsp

注意: 路径, 以及文件后缀名, 需和demo-servlet.xml中定义的一致.

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login</title>
</head>
<body>
This is the login page.
</body>
</html>

login.jsp

2. 创建控制器:

利用annotation, Spring会在demo-servlet.xml所配置的base-package中自动扫描带@Controller的控制器

注意: ViewName需和login.jsp保持一致.

package com.demo.springmvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView; @Controller
public class LoginController {
@RequestMapping("/login")
public ModelAndView handleLoginRequest() {
ModelAndView mv = new ModelAndView();
mv.setViewName("user/pages/login");
// mv.addObject(attributeName, attributeValue);
return mv;
}
}

LoginController

3. 运行机制简单描述:

根据web.xml的配置, 部署并启动后, 默认访问页面是home.html(放在webapp目录下).

<html>
<head>
<title>Home</title>
</head>
<body>
<h2>Welcome to Spring MVC by Maven - Hello World!</h2>
</body>
</html>

home.html

当我们在URL上输入login.do时, 根据web.xml的配置, servlet "demo"会得到该request, 并且根据RequestMapping的值, 找到匹配的controller, 也即LoginController, 来进行处理. LoginController则根据ViewName, 找到最终需要展示的view页面, 也即login.jsp. 最终得到结果:

附: 项目结构图

最新文章

  1. 最难面试的IT公司之ThoughtWorks代码挑战——FizzBuzzWhizz游戏(C#解法)
  2. asp.net调用客户端WebBrowser 进行网站地址截屏
  3. poj1328 贪心
  4. web api :Routing in ASP.NET Web API
  5. mssql中sp_executesql的用法
  6. linux安装phpstorm出现 Startup Error: Unable to detect graphics environment
  7. MySQL存储引擎MyISAM与InnoDB的优劣
  8. poj 3678 2-SAT问题
  9. vsftpd.conf配置详解
  10. Combination Sum II —— LeetCode
  11. 两台机子的repcached Memcache 的安装与实验
  12. 关于解决Mac使用docker安装SQL server for Linux 中文乱码问题
  13. qnx gpio
  14. JDBC的使用-----Statement
  15. CentOS 6.4 源码安装MySQL 5.6
  16. JavaScript数组(三)数组对象使用整理
  17. Python-数学篇之计算方法的目录:
  18. Fastjson, Gson, org.json.JSON三者对于JSONObject及JSONArray的判断
  19. leetcode56:合并区间
  20. MyBatis.4关联

热门文章

  1. MediaChooser图库浏览器
  2. 【带权并查集】【HDU3038】【How Many Answers Are Wrong】d s
  3. 【插队问题-线段树-思维巧妙】【poj2828】Buy Tickets
  4. Java基础笔记-面向对象2
  5. box-shadow属性
  6. C#:获取时间年月日时分秒格式
  7. Spring-----Spring Jar包
  8. zabbix中文配置及乱码问题
  9. Flink资料(4) -- 类型抽取和序列化
  10. windbg命令学习1