在Eclipse中構(gòu)建Spring項目
目錄
- 0 構(gòu)建項目
- 1 修改項目 pom.xml
- 2 修改項目 web.xml
- 3 配置springmvc-servlet.xml
- 4 寫Controller
- 5 靜態(tài)資源
- 6 文件上傳
- 7 通過application.properties進(jìn)行參數(shù)注入
0. 構(gòu)建項目
file-new-project選擇mavenproject

然后選擇webapp

1. 修改項目 pom.xml
添加spring-web 和 spring-webmvc 這兩個依賴,以及fastjson,用來將bean轉(zhuǎn)化為json
<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.reno.zhihu</groupId>
<artifactId>zhihuSpyderWithGUI</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>zhihuSpyderWithGUI Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<hibernate-version>5.2.2.Final</hibernate-version>
<spring-version>4.2.5.RELEASE</spring-version>
<fastjson-json-version>1.2.16</fastjson-json-version>
<junit-version>3.8.1</junit-version>
</properties>
<dependencies>
<!-- Spring SpringMVC -->
<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>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!--json-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.1</version>
</dependency>
</dependencies>
<build>
<finalName>zhihuSpyderWithGUI</finalName>
</build>
</project>
在其中添加兩個Spring依賴
<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>
2. 修改項目 web.xml
<!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>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<!-- <load-on-startup>1</load-on-startup> -->
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
- DispatcherServlet是前置控制器,攔截匹配的請求,Servlet攔截匹配規(guī)則要自已定義,把攔截下來的請求,依據(jù)相應(yīng)的規(guī)則分發(fā)到目標(biāo)Controller來處理,是配置spring MVC的第一步。
3. 在resources文件夾中建立springmvc-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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<!-- scan the package and the sub package -->
<context:component-scan base-package="com.reno.testSpring"/>
<!-- don't handle the static resource -->
<mvc:default-servlet-handler />
<!-- if you use annotation you must configure following setting -->
<mvc:annotation-driven />
<!-- configure the InternalResourceViewResolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 前綴 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 后綴 -->
<property name="suffix" value=".jsp" />
</bean>
</beans>
<context:component-scan base-package="com.reno.testSpring"/>這個定義了自動掃描的根包,這個根據(jù)需要更改
前后綴的使用
<!-- 前綴 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 后綴 -->
<property name="suffix" value=".jsp" />
當(dāng)Controller return一個String的時候自動去匹配對應(yīng)的 /WEB-INF/jsp/"String".jsp 文件
4. 寫Controller
@Controller
@RequestMapping("/mvc")
public class mvcController {
public mvcController() {
System.out.println("===============");
}
@RequestMapping("/hello")
public String hello(){
return "hello";
}
@RequestMapping("/hello2")
public
@ResponseBody
Person getShopInJSON() {
Person p = new Person();
p.setAge(12);
p.setName("adad");
return p;
}
}
return "hello"; 會與之前springmvc-servlet.xml中的前綴后綴拼接,最后返回一個 /WEB-INF/jsp/hello.jsp
return 一個對象 ,由于之前引入fastjson,將被直接轉(zhuǎn)化成一個json串。
5. 靜態(tài)資源
參考 http://blog.csdn.net/litlit023/article/details/41494093
在springmvc-servlet.xml中添加信息,這個文件根據(jù)你在web.xml中的配置而名字不同
一下字段添加在<beans>標(biāo)簽以內(nèi)
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:resources mapping="/images/**" location="/images/" />
<mvc:resources mapping="/js/**" location="/js/" />
6. 文件上傳
在pom.xml中添加依賴
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
這里最新版本是1.3.2 但是在 http://repo.maven.apache.org/maven2 這個倉庫中 1.3.2的文件結(jié)構(gòu)有點和其他的版本不一樣,用maven構(gòu)建的時候出現(xiàn)問題,故而使用1.3.1版本
在springmvc-servlet.xml中配置一下
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
從而實現(xiàn)上傳功能 這里還可以做一些詳細(xì)的配置比如文件的最大上傳大小之類的
比如在bean中添加屬性參數(shù)限制上傳大小
<property name="maxUploadSize" value="204800" />
前端上傳界面
使用一個form 利用enctype="multipart/form-data"屬性上傳文件。 action="/zhihuSpyderWithUI/springUpload"代表了點擊upload按鈕以后再后端請求的url
<form name="Form2" action="/zhihuSpyderWithUI/springUpload" method="post" enctype="multipart/form-data">
<h1>使用spring mvc提供的類的方法上傳文件</h1>
<input type="file" name="file">
<input type="submit" value="upload"/>
</form>
后臺處理代碼
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class UploadFile {
/*
*采用spring提供的上傳文件的方法
*/
@RequestMapping("/springUpload")
public String springUpload(HttpServletRequest request) throws IllegalStateException, IOException
{
//將當(dāng)前上下文初始化給 CommonsMutipartResolver (多部分解析器)
CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
request.getSession().getServletContext());
//檢查form中是否有enctype="multipart/form-data"
if(multipartResolver.isMultipart(request))
{
//將request變成多部分request
MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
//獲取multiRequest 中所有的文件名
Iterator iter=multiRequest.getFileNames();
while(iter.hasNext())
{
//一次遍歷所有文件
MultipartFile file=multiRequest.getFile(iter.next().toString());
if(file!=null)
{
String basepath=request.getSession().getServletContext().getRealPath("uploadfile");
System.out.println(basepath);
path=basepath+"/"+System.nanoTime()+file.getOriginalFilename();
//上傳
file.transferTo(new File(path));
}
}
}
return "success";
}
}
這里將文件保存在webapp 下的upload目錄底下
7. 通過application.properties進(jìn)行參數(shù)注入
在xxx-servlet.xml中添加
<context:property-placeholder location="classpath:application.properties" />
這里application.properties文件存放在resources 目錄底下
之后再任何的Bean類中使用一下代碼
@Value("${cmd.dir}")
private String baseURL;
給baseURL賦值 ,其中cmd.dir對應(yīng)了application.properties中的內(nèi)容:
cmd.dir=xxx