SpringMVC框架簡介①
首先, 建專案之後引包:
連結: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;
}
}
相關文章
- SpringMVC框架簡介②SpringMVC框架
- SpringMVC簡介SpringMVC
- springmvc簡介和快速搭建SpringMVC
- SpringMvc的簡單介紹SpringMVC
- SpringMVC表單標籤簡介SpringMVC
- Scrapy框架簡介框架
- HTML 框架簡介HTML框架
- Flask 框架簡介Flask框架
- Django框架簡介Django框架
- graphicsview框架簡介View框架
- 【SpringMVC】RESTFul簡介以及案例實現SpringMVCREST
- Hibernate框架簡介⑤框架
- Hibernate框架簡介④框架
- Hibernate框架簡介③框架
- Hibernate框架簡介②框架
- Hibernate框架簡介①框架
- Spring框架簡介⑩Spring框架
- Spring框架簡介⑨Spring框架
- Spring框架簡介⑧Spring框架
- [轉]SSH框架簡介框架
- Spring框架簡介⑦Spring框架
- Spring框架簡介⑥Spring框架
- Spring框架簡介⑤Spring框架
- Spring框架簡介④Spring框架
- Spring框架簡介③Spring框架
- Spring框架簡介②Spring框架
- Spring框架簡介①Spring框架
- [原]ZolltyMVC框架簡介MVC框架
- 【SSH】--SSH框架簡介框架
- 自己手寫一個SpringMVC框架(簡化)SpringMVC框架
- 【SpringMVC】SpringMVC搭建框架SpringMVC框架
- wsgiref模組、web框架、django框架簡介Web框架Django
- spring框架——Spring框架簡介Spring框架
- Flutter路由框架Fluro簡介Flutter路由框架
- uni-app 框架簡介APP框架
- 關於Struts框架簡介框架
- Java集合框架系列教程一:集合框架簡介Java框架
- OSX 攻擊框架Empyre簡介框架