首先, 建项目之后引包:
链接:https://pan.baidu.com/s/1ekU8ga_GjSWyTmRRcVoCgw 密码:xhxd
配置中央转发器(dispatchservlet), web.xml
<?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_2_5.xsd" id="WebApp_ID" version="2.5">
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!-- 不能使用/* -->
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">
</beans>
该配置文件名称有一定的规范, 默认是按照在web.xml配置的"<servlet-name>springmvc</servlet-name>"+".servlet.xml"
下面先介绍一下配置文件的方式, 后续重点介绍注解的使用
第一个例子:
TestController.java:
package com.rl.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class TestController extends AbstractController {
@Override
protected ModelAndView handleRequestInternal
(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
//返回值里面是路径为非文件名
return new ModelAndView("index");
}
}
将配置文件完善后启动tomcat
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">
<!-- 配置TestController的bean
默认当输入"/hello.do"请求时, 将直接指向当前配置的TestController.java并访问"handleRequestInternal"方法
-->
<bean name="/hello.do" class="com.rl.controller.TestController"/>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置前缀 -->
<property name="prefix" value="/WEB-INF/jsp/"></property>
<!-- 配置后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
项目结构图:
在页面访问"http://localhost:8080/springmvc-1/hello.do"
结果如下:
还有其他两种方法, 不直接举例 下面贴配置信息
另外如果想要直接访问一个页面而不需要其他逻辑处理, 可以使用springmvc为我们提供的一种自动创建Controller的方式, 如下配置信息:
控制器有三种, 以下不详细介绍, 只贴出代码, 都有详细注释:
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">
<!-- 配置TestController的bean
默认当输入"/hello.do"请求时, 将直接指向当前配置的TestController.java并访问"handleRequestInternal"方法
-->
<bean id="TestController" name="/hello.do" class="com.rl.controller.TestController"/>
<!-- =================================映射处理器================================== -->
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置前缀 -->
<property name="prefix" value="/WEB-INF/jsp/"></property>
<!-- 配置后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 默认采用这种方式配置 -->
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>
<!-- 第二种映射的配置方式 -->
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<!-- 根据id来映射具体的Controller -->
<prop key="/hello1.do">TestController</prop>
</props>
</property>
</bean>
<!-- 第三种映射的配置方式
访问路径为: http://localhost:8080/springmvc-1/testController.do
testController.do首字符必须小写
-->
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"></bean>
<!-- =================================三种控制器================================== -->
<!--
需求: 只需要跳转一个页面, 不需要其他逻辑, 可以使用springmvc为我们提供的这个方式, 免去自己创建Controller
springmvc自动创建的一个Controller, 直接转发
-->
<bean name="/toIndex.do" class="org.springframework.web.servlet.mvc.ParameterizableViewController">
<property name="viewName" value="index"></property>
</bean>
<!-- 接收get方式提交的参数类型 -->
<bean name="/comm.do" class="com.rl.controller.CommController">
<property name="commandClass" value="com.rl.model.Person"></property>
</bean>
<!-- 接收表单post方式提交的参数类型 -->
<bean name="/form.do" class="com.rl.controller.FormController">
<!-- 指定commandClass属性对应的实体类是Person -->
<property name="commandClass" value="com.rl.model.Person"></property>
<!-- 跳转页面为form, 前缀跟后缀参照视图解析器的规则 -->
<property name="formView" value="form"></property>
<!-- 提交成功之后的跳转页面 -->
<property name="successView" value="success"></property>
</bean>
</beans>
项目结构:
CommController.java:
package com.rl.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractCommandController;
public class CommController extends AbstractCommandController {
@Override
protected ModelAndView handle
(HttpServletRequest arg0, HttpServletResponse arg1, Object obj, BindException arg3)
throws Exception {
System.out.println(obj);
return new ModelAndView("index");
}
}
FormController.java
package com.rl.controller;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.mvc.SimpleFormController;
public class FormController extends SimpleFormController {
@Override
protected void doSubmitAction(Object obj) throws Exception {
System.out.println(obj);
}
/**
* 自定义属性编辑器
* 将日期的输入格式从xxxx/xx/xx转成xxxx-xx-xx
*/
@Override
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
}
}
表单就不贴出来了, 自己设置数据, 提交试试即可.
下面详解注解形式的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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">
<!-- 配置注解扫描器 -->
<context:component-scan base-package="com.rl.controller"/>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置前缀 -->
<property name="prefix" value="/WEB-INF/jsp/"></property>
<!-- 配置后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
注解开发第一个例子:
package com.rl.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller//Controller注解
@RequestMapping("/test")//防止出现相同方法名的情况
public class TestController {
@RequestMapping("/hello.do")//映射方法
public String hello() {
return "index";//返回modelandview的路径
}
}
最原始的接收参数的方法:
package com.rl.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller//Controller注解
@RequestMapping("/test")//防止出现相同方法名的情况
public class TestController {
/**
* 最原始的接收参数的方法
* @return
*/
@RequestMapping("/revParam.do")
public String revParam(HttpServletRequest request) {
String name = request.getParameter("name");
System.out.println(name);
return "index";
}
}
控制台输出: zs
第二种:
package com.rl.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller//Controller注解
@RequestMapping("/test")//防止出现相同方法名的情况
public class TestController {
/**
* 第二种接收的方式
* @return
*/
@RequestMapping("/revParam1.do")
public String revParam1(String name) {
System.out.println(name);
return "index";
}
}
输出同上
第三种:
package com.rl.controller;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller//Controller注解
@RequestMapping("/test")//防止出现相同方法名的情况
public class TestController {
/**
* 第三种: 可传多个参数
* @param name
* @return
* @throws IOException
*/
@RequestMapping("/revParam2.do")
public String revParam2(String name, Integer id, String address, Date birthday,
HttpServletRequest request, HttpServletResponse response) {
System.out.println(name);
System.out.println(id);
System.out.println(address);
System.err.println(birthday);//默认输入格式是xxxx/xx/xx
return "index";
}
@InitBinder//该注解绑定属性编辑器
public void initBinder(ServletRequestDataBinder binder) {
binder.registerCustomEditor(Date.class,
new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
}
}
第四种:
package com.rl.controller;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller//Controller注解
@RequestMapping("/test")//防止出现相同方法名的情况
public class TestController {
/**
* 第四种: 多选传参
*/
@RequestMapping("/revParam3.do")
public String revParam3(String[] fav) {
for(String fa: fav) {
System.out.println(fa);
}
return "success";
}
/**
* 跳转表单
* @return
*/
@RequestMapping("/toForm.do")
public String toForm() {
return "form";
}
}
form.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!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">
<base href="<%=basePath%>">
</head>
<body>
<form action="test/revParam3.do" method="post">
爱好:<input name="fav" type="checkbox" value="1">篮球
<input name="fav" type="checkbox" value="2">排球
<input name="fav" type="checkbox" value="3">棒球
<input type="submit" value="提交">
</form>
</body>
</html>
也可以用对象来接收, 就不贴代码了.
第五种: 结果集返回视图
package com.rl.controller;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.rl.model.Person;
@Controller//Controller注解
@RequestMapping("/test")//防止出现相同方法名的情况
public class TestController {
/**
* 结果集返回视图(不建议使用)
* @return
*/
@RequestMapping("/returnResult.do")
public ModelAndView returnResult() {
Person person = new Person();
person.setAddress("北京");
person.setBirthday(new Date());
person.setGender(1);
person.setName("zhangsan");
Map<String, Person> map = new HashMap<String, Person>();
map.put("person", person);
return new ModelAndView("returnPage", map);
}
}
页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!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">
</head>
<body>
<h4>${person.name }</h4>
<h4>${person.gender }</h4>
<h4>${person.address }</h4>
<h4><fmt:formatDate value="${person.birthday }" pattern="yyyy-MM-dd HH:mm:ss"/></h4>
</body>
</html>
第六种:
package com.rl.controller;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.rl.model.Person;
@Controller//Controller注解
@RequestMapping("/test")//防止出现相同方法名的情况
public class TestController {
/**
* 第六种: 简化一点(还是比较少用的, 不建议使用)
* 注意: map在参数列表中不是用于接收参数的, 只用于返回页面
*/
@RequestMapping("/returnResult1.do")
public String returnResult1(Map<String, Object> map) {
Person person = new Person();
person.setAddress("北京");
person.setBirthday(new Date());
person.setGender(1);
person.setName("zhangsan");
map.put("person", person);
return "returnPage";
}
}
效果同上
第七种:
package com.rl.controller;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.rl.model.Person;
@Controller//Controller注解
@RequestMapping("/test")//防止出现相同方法名的情况
public class TestController {
/**
* 再简化, 使用Model(最常用, 建议使用)
*/
@RequestMapping("/returnResult2.do")
public String returnResult2(Model model) {
Person person = new Person();
person.setAddress("北京");
person.setBirthday(new Date());
person.setGender(1);
person.setName("zhangsan");
model.addAttribute("person", person);
return "returnPage";
}
}
效果同上
ajax调用springmvc的方法:
package com.rl.controller;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.rl.model.Person;
@Controller//Controller注解
@RequestMapping("/test")//防止出现相同方法名的情况
public class TestController {
/**
* ajax调用
*/
@RequestMapping("/ajax.do")
public void ajax(String name, HttpServletResponse response) {
String result = "hello "+name;
try {
response.getWriter().write(result);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 跳转ajax
*/
@RequestMapping("/toAjax.do")
public String toAjax() {
return "ajax";
}
}
页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(function(){
$("#myButton").click(function(){
var mytext = $("#mytext").val();
$.ajax({
url:"test/ajax.do",
type:"post",
dataType:"text",
data:{
name:mytext
},
success:function(responseText){
alert(responseText);
},
error:function(){
alert("system error");
}
});
});
});
</script>
</head>
<body>
<input type="text" id="mytext">
<input type="button" id="myButton" value="click">
</body>
</html>
SpringMVC的重定向:
同一Controller中的重定向:
package com.rl.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.rl.model.Person;
@Controller//Controller注解
@RequestMapping("/test")//防止出现相同方法名的情况
public class TestController {
/**
* 跳转表单
* @return
*/
@RequestMapping("/toForm.do")
public String toForm() {
return "form";
}
/**
* 同一Controller之内的重定向
*/
@RequestMapping("/redirectForm.do")
public String redirectForm() {
return "redirect:toForm.do";//路径会更改
}
}
不同Controller之间的重定向:
package com.rl.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.rl.model.Person;
@Controller//Controller注解
@RequestMapping("/test")//防止出现相同方法名的情况
public class TestController {
/**
* 不同Controller之间的重定向
*/
@RequestMapping("/redirectForm1.do")
public String redirectForm1() {
return "redirect:/test1/toForm.do";//test1前面的'/'代表从根目录上的test1/toForm.do
}
}
package com.rl.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller//Controller注解
@RequestMapping("/test1")//防止出现相同方法名的情况
public class Test1Controller {
/**
* 跳转表单
* @return
*/
@RequestMapping("/toForm.do")
public String toForm() {
return "form";
}
}
文件上传:
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">
<!-- 配置注解扫描器 -->
<context:component-scan base-package="com.rl.controller"/>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置前缀 -->
<property name="prefix" value="/WEB-INF/jsp/"></property>
<!-- 配置后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 文件上传
复杂类型的表单视图解析器
-->
<!--
bean的id是multipartResolver,不能随便定义
-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--
以字节为单位
-->
<property name="maxUploadSize" value="1024000"></property>
</bean>
</beans>
页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/jquery.js"></script>
</head>
<body>
<form action="upload/uploadPic.do" method="post" enctype="multipart/form-data">
<input type="file" name="pic">
<input type="submit" value="提交">
</form>
</body>
</html>
package com.rl.controller;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
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;
@Controller
@RequestMapping("/upload")
public class UploadController {
@RequestMapping("/uploadPic.do")
public String uploadPic(HttpServletRequest request) throws Exception {
//转换request
MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
//获得文件
MultipartFile file = mr.getFile("pic");
//获得文件的字节数组
byte[] fbyte = file.getBytes();
//获得当前时间的最小精度,精确到三位毫秒
String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
//再加三位随机数
Random random = new Random();
for(int i = 0; i < 3; i++){
fileName = fileName + random.nextInt(10);
}
//获得文件的原始文件名
String oriFileName = file.getOriginalFilename();
//后缀
String suffix = oriFileName.substring(oriFileName.lastIndexOf("."));
//获得项目的部署路径
String realPath = request.getSession().getServletContext().getRealPath("/");
//组装图片的全路径
String picPath = realPath + "\\upload\\"+fileName+suffix;
//定义输出流
OutputStream out = new FileOutputStream(new File(picPath));
out.write(fbyte);
out.flush();
out.close();
return "success";
}
}
记得实现一定要先建立一个upload文件夹:
拦截器:
配置文件:
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">
<!-- 配置注解扫描器 -->
<context:component-scan base-package="com.rl.controller"/>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置前缀 -->
<property name="prefix" value="/WEB-INF/jsp/"></property>
<!-- 配置后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 文件上传
复杂类型的表单视图解析器
-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--
以字节为单位
-->
<property name="maxUploadSize" value="1024000"></property>
</bean>
<!-- 配置拦截器
mvc:mapping: 配置拦截范围, 跟bean标签有上下的顺序
-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/test/**"/>
<bean class="com.rl.interceptor.MyInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
</beans>
拦截器实现:
package com.rl.interceptor;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class MyInterceptor implements HandlerInterceptor {
/**
* 最终拦截: 在页面生成之后执行
* 可以做页面的一些监控, arg3可以收集一些异常信息
*/
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
System.out.println("执行最终拦截...");
String message = arg3.getMessage();//可以获取一些异常信息
}
/**
* 后置拦截: 在Controller之后执行, 视图解析之前(还没生成页面)
* 可以对未生成的页面做一些修改
*/
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
System.out.println("执行后置拦截...");
Map<String, Object> map = arg3.getModel();
//此时map可以追加一些东西
}
/**
* 前置拦截, 在Controller前执行
* return false表示拦截, true表示放行
* arg2: 当前拦截到的Controller的实例
*/
@Override
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
System.out.println("执行前置拦截...");
return true;
}
}