准备:
- Eclipse Neon.2 Release (4.6.2)
- Tomcat7.0
- JDK1.8
- Spring MVC所需jar包
第一步:建立web项目导入所需jar包(如下图)。
第二步:在web.xml中配置Spring MVC的servlet:
代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>springMVCTest</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 配置DispatchcerServlet -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置Spring mvc下的配置文件的位置和名称 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<!-- 在服务器开启后就加载 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
第三步:配置spring-mvc.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.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 注解驱动 -->
<mvc:annotation-driven/>
<!-- 配置自动扫描的包 -->
<context:component-scan base-package="test"></context:component-scan>
<!-- 静态资源的过滤,防止被springMVC拦截,这里是不拦截js下的所有文件。我们常常会用到一些js或者一些框架的静态资源,因为默认都进行了拦截,所以这里指定那些东西是不必要拦截的,不然你会发现你网页特效都没了 -->
<mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
<!-- 文件上传所需的多媒体处理器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</beans>
第四步:以spring-xml中自动扫描的包名建立测试项目的第一个包,并新建一个class
第五步:注解配置spring的控制器,映射请求的url,这里把后面要用的代码也全部放出
代码如下(Mvc.java):
package test;
import java.io.File;
import java.io.IOException;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import entity.Products;
/*spring的控制器*/
@Controller
@RequestMapping("mvcTest")
public class Mvc {
// 1--
/* 使用RequestMapping注解来映射请求的URL,和方法名不绝对对应*/
@RequestMapping("/mvc1")
public String mvc1() {
System.out.println("hello , this is mvc test1");
// 返回的视图地址,默认为转发,如需重定向在路径前加 redirect:
return "/index.jsp";
}
// 2--
@RequestMapping("/redirect")
public String mvc2() {
System.out.println("hello , this is mvc test2");
// 重定向到指定页面
return "redirect:/index.jsp";
}
// 3--
@RequestMapping("/ajax")
@ResponseBody // 此注解可以让方法不返回视图
public String mvc3() {
System.out.println("hello , this is mvc test @ResponseBody");
// 不返回视图,可返回字符,json数据,在异步的时候可用此
return "this is test @ResponseBody";
}
// 4--
/*上面直接返回的有可能会中文乱码,下面是解决,produces可指定返回类型*/
@RequestMapping(value="/ajax_1", produces="text/html;charset=UTF-8")
@ResponseBody // 此注解可以让方法不返回视图
public String mvc3_1() {
System.out.println("hello , this is mvc test @ResponseBody");
// 不返回视图,可返回字符,json数据,在异步的时候可用此
return "这是测试是否乱码";
}
// 5--
@RequestMapping("/noReturn")
@ResponseBody // 此注解页可用于没有返回值的请求,如对验证码的请求,或只需通过response输出流输出的内容
public void mvc4() {
System.out.println("hello , this is mvc test noReturn");
}
// 6--
/*指定请求提交方式get*/
@RequestMapping(value="/doGet",method=RequestMethod.GET)
public String mvc5() {
System.out.println("hello , this is doGet");
return "/index.jsp";
}
// 7--
/*指定请求的方式为post*/
@RequestMapping(value="/doPost",method=RequestMethod.POST)
public String mvc6() {
System.out.println("hello , this is doPost");
return "/index.jsp";
}
// 8--
/*获取请求参数注解方式*/
@RequestMapping("/getParam")
public String mvc7(@RequestParam("userName")String uName,@RequestParam("userPwd")String uPwd) {
System.out.println("this is @RequestParam get");
System.out.println(uName);
System.out.println(uPwd);
return "/index.jsp";
}
// 9--
/*获取请求参数*/
@RequestMapping("/getParam1")
public String mvc8(String userName,String userPwd) {
System.out.println("this is no @RequestParam get");
System.out.println(userName);
System.out.println(userPwd);
return "/index.jsp";
}
// 10--
/*获得复选框或一组数据*/
@RequestMapping("/getParams")
public String mvc9(String [] insert) {
for(String ins:insert) {
System.out.println(ins);
}
return "/index.jsp";
}
// 11--
/*通过@PathVariable获得动态参数*/
@RequestMapping("/voide/{vId}")
public String mvc10(@PathVariable("vId")String vId) {
System.out.println("hello , this is @PathVariable test:--vId="+vId);
return "/index.jsp";
}
// 12--
/*控制器通过Model把数据传到view层*/
@RequestMapping("/model")
public String mvc11(Model model) {
System.out.println("hello , this is Model Test");
model.addAttribute("msg","hello , this is Model test");
return "/index.jsp";
}
// 13--
/*通过形参操作servletAPI及传递参数*/
@RequestMapping("/servlet")
public String mvc12(HttpSession session) {
System.out.println("hello , this is get Servlet");
session.setAttribute("msg", "this is httpServlet API");
return "/index.jsp";
}
// 14--
/*通过注解注入的形式获取ServletAPI中的对象*/
@Autowired
private HttpSession session;
@RequestMapping("/servlet1")
public String mvc13() {
System.out.println("this is @Autowired test");
session.setAttribute("msg", "this is @Autowired test");
return "/index.jsp";
}
// 15--
/*对视图传递的参数进行自动装箱*/
@RequestMapping("/pro")
public String mvc14(Products pro) {
System.out.println(pro.getPname());
return "/index.jsp";
}
// 16--
/*文件上传,需要导入commons-fileupload.jar以及commons-io.jar,在spring-mvc.xml注册多媒体处理器*/
@RequestMapping("/upload")
public String upload(@RequestParam("file") MultipartFile multiFile) {
File file = new File("d:/"+multiFile.getOriginalFilename());
System.out.println("文件名:"+file.getName());
try {
/*文件的存放位置*/
multiFile.transferTo(file);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "/index.jsp";
}
}
现在就可以让spring控制器来接收请求
如(1–):直接访问http://localhost:8080/springMVCTest/mvcTest/mvc1,此时会将请求转发到指定的页面。index.jsp,依次类推。
不过以上还有一些地方有需要注意的地方:
(0) 类上面的url映射不是必须的,如果去掉此映射,访问地址中页改去掉相应的路径,如去掉后mvc1应该不再打/,而是直接mvc1,访问路径相应为:http://localhost:8080/springMVCTest/mvc1。方法上的url映射不是必须和方法名相对应,如果你必须要访问或提交数据到此方法,是必然需要一个url映射的。
(3–)第三个方法为不返回任何视图的方法,相对应的注解应该为:@ResponseBody 同时也可以让方法没有任何返回值,如你只需要将数据通过response输出流给页面。
(4–)第三个方法类似,但是这样可以指定返回的上数据的类型以及编码格式,这样避免了乱码,也能让页面拿到想要的Content-Type:如 json 数据以及html数据。
(6,7–)可以用一个表单进行测试,当然了,我已经给你准备好了。在后面的代码将给出。并且你的value是可以相同的,但是还要你的请求的方式不同,他会去匹配所对应的方法执行。
(8–)@RequestParam 注解用于拿到请求中的数据。你可以通过表单提交的 方式进行测试。
或者只需要在url中输入:http://localhost:8080/springMVCTest/mvcTest/getParam?userName=张三&userPwd=123
(9–)和8的不同在于你不需要在方法参数内写上注解,当然他也可以拿到我们想要得到的数据,不过唯一的不同时,当你没有传入任何数据的时候,8会提示你:
而9只是拿到了空值。
(10–)可以拿到一组相同name的数据,如复选框的数据,可以集合进行装配。
(11–) @PathVariable注解可以拿到页面的动态参数,注解内的参数必须要与形参的参数名相同
(13,14)通过不同的方式拿到ServletAPI中的各个对象,并操作这些对象做我们想做的事。
(15)这里有一个对象属性的自动装配,在页面中传入的属性所对应的name不再是像Struts2中
obj.param传递,而是直接省略obj. 如果对象间有对应的关联,使用的道理是一样。只需要省略前面的对象名就可以。
(16)文件上传的操作相对Struts2来说更为简单方便:不过这需要一些依赖。像以前一样你需要导入相应的jar,如下图:
然后,你需要在spring-mvc.xml文件中加入这样的一段bean (上面的配置文件中已经配置)
代码如下:
<!-- 文件上传所需的多媒体处理器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
当然,不要忘了和以前一样的在form中对应name,以及数据提交类型,代码全部贴出来,包含了文件上传和其他的东西,相信一看就明白了。
代码如下:
<!-- 测试get方法 -->
<form action="/springMVCTest/mvcTest/doGet" method="get">
<input type="submit" value="mvc get test">
</form>
<br>
<hr>
<p>测试post方法</p>
<!-- 测试post方法 -->
<form action="/springMVCTest/mvcTest/doPost" method="post">
<input type="submit" value="mvc post test">
</form>
<br>
<hr>
<p>测试参数获取</p>
<!-- 测试参数获取 -->
<form action="/springMVCTest/mvcTest/getParam1" method="get">
<input type="text" name="userName">
<input type="password" name="userPwd">
<input type="submit">
</form>
<p>测试参数获取(多个)</p>
<!-- 测试参数获取(多个) -->
<form action="/springMVCTest/mvcTest/getParams" method="get">
<input type="checkbox" name="insert" value="读书">读书
<input type="checkbox" name="insert" value="看报">看报
<input type="checkbox" name="insert" value="游戏">游戏
<input type="submit">
</form>
<p>测试文件上传</p>
<!-- 测试文件上传 -->
<form action="/springMVCTest/mvcTest/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" >
<input type="submit">
</form>
如有错误或者补充,还望路过的大佬指出。以便修改