目錄結構javascript
1、SpringMvc相關知識php
11、SpringMvc的大致認識 ?html
12、什麼是MVC ? 前端
13、SpringMvc內部是怎麼樣工做的?java
2、環境以及第三方技術的說明git
3、咱們進入正題,下邊經過一個個實例來介紹SpringMvc的用法web
3一、重要配置文件的說明ajax
3二、用戶註冊例子spring
3三、主頁的展現shell
3四、登陸例子
3五、文件上傳
3六、表單的服務器端驗證
1、SpringMvc相關知識
11、SpringMvc的大致認識 ?
SpringMvc構建在Spring框架的基礎上,是對Servlet進行封裝(對客戶端的請求以及響應進行很友好的處理),方便咱們開發Java EE程序的MVC框架。
12、什麼是MVC ?
MVC全名是ModelViewController,他是一種軟件設計的理念,即將數據、界面展示、業務邏輯進行分離,其好處是方便一個系統中不一樣開發角色的分工,相互之間沒有太大的耦合,而且各層的代碼也能進行很好的重用。其中:
M是模型Model的縮寫,如對數據的存取;
V是視圖View的縮寫,是對M層提供數據以及展示M層的數據,常見技術包括JSP、Velocity、Tiles、iText和POI ;
C是Controller的縮寫,它的一個重要的職責是將V層的數據獲取到後交給M,最後將M層的數據交給V層 ;
13、SpringMvc內部是怎麼樣工做的?
根據其工做原理,其內部工做流程以下圖:
2、環境以及第三方技術的說明
當前項目是用Maven構建,其版本爲apache-maven-3.0.4,開發工具爲Eclipse,代碼放在開源中國的Git中,當前項目的下載地址爲:https://git.oschina.net/liw/Sports-SpringMvc.git ,其餘環境以及技術說明以下:
第三方技術 |
版本 |
本實例中的做用 |
JDK |
1.7 |
|
Tomcat |
7 |
Web容器 |
Spring |
4.1.4.RELEASE |
Bean IOC |
SpringMvc |
4.1.4.RELEASE |
在MVC框架中處於C層,其做用爲請求的處理以及處理結果的轉發 |
jackson-mapper-asl |
1.9.13 |
Jackson ,一種用於Json處理的第三方技術 |
jackson-annotations |
2.5.0 |
|
jackson-core |
2.5.0 |
|
jackson-databind |
2.5.0 |
|
Jstl |
1.2 |
Jsp頁面數據的展示 |
Servlet-api |
3.1-b05 |
J2EE的基礎 |
hibernate-validator |
5.2.2.Final |
服務器端bean的驗證技術,便可以對錶單進行服務器端驗證 |
Commons-fileupload |
1.2.2 |
文件上傳 |
Commons-io |
2.4 |
|
Commons-lang |
3.4 |
提供字符串、對象、日期、數字等方便處理的幫助類 |
BootStrap |
3.3.5 |
用於頁面展示佈局等 |
Jquery |
1.11.3 |
頁面數據元素的操做 |
3、咱們進入正題,下邊經過一個個實例來介紹SpringMvc的用法
31、幾個配置文件的說明,設計到的配置文件有:spring.xml、spring-mvc.xml、web.xml
spring.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"> <context:component-scan base-package="cn.com.sports.utils"></context:component-scan> </beans>
我將一些工具類放到了cn.com.sports.utils包中,並配置自動掃描這個包下的類,方面在其餘類中使用
spring-mvc.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.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"> <!-- 自動掃描controller包下的全部類,若是@Controller注入爲bean --> <context:component-scan base-package="cn.com.sports.controller" /> <!-- 避免IE執行AJAX時,返回JSON出現下載文件 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- 啓動Spring MVC的註解功能,完成請求和註解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <!-- json轉換器 --> <ref bean="mappingJacksonHttpMessageConverter" /> </list> </property> </bean> <!-- 對模型視圖名稱的解析,即在模型視圖名稱添加先後綴 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/views" /> <property name="suffix" value=".jsp" /> </bean> <!-- 配置多文件上傳 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding"> <value>UTF-8</value> </property> <property name="maxUploadSize"> <!-- 上傳文件大小限制爲31M,31*1024*1024 --> <value>32505856</value> </property> <property name="maxInMemorySize"> <value>4096</value> </property> </bean> <mvc:interceptors> <bean class="cn.com.sports.interceptor.AllInterceptor"></bean> <mvc:interceptor> <mvc:mapping path="/login/otherHandUI.html"/> <bean class="cn.com.sports.interceptor.LoginInterceptor"></bean> </mvc:interceptor> </mvc:interceptors> <mvc:annotation-driven validator="validator"/> <!-- 如下 validator ConversionService 在使用 mvc:annotation-driven 會 自動註冊--> <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/> </bean> </beans>
當前文件的配置文件有如下做用,固然你還能配置其餘的,如下說明只適用於本項目
對bean到Json,以及返回Json到客戶端的配置處理;
配置返回視圖頁面的前綴以及後綴;
配置文件上傳的相關參數;
配置攔截器的相關信息;
配置使用HibernateValidator進行服務器驗證 ;
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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 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"> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml</param-value> </context-param> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 防止spring內存溢出監聽器 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <servlet> <description>spring mvc servlet</description> <servlet-name>rest</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <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>rest</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> <!-- 配置session超時時間,單位分鐘 --> <session-config> <session-timeout>30</session-timeout> </session-config> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <display-name>Sports-SpringMvc</display-name> </web-app>
對web.xml沒什麼多說的,只說明下當前項目中,配置的前端Servlet DispaterServlet只對後綴已.html結尾的URI進行攔截處理
3二、一我的員註冊的例子
首先建立一個bean,名稱爲User.java ,其中包含一些用戶的基本信息,其字段上的直接能夠先不關注
package cn.com.sports.model; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotEmpty; public class User { private String id ; @NotEmpty(message="username不能爲空") private String username ; @NotEmpty(message="密碼不能爲空") private String password ; @Email(message="email字段必須爲Email") private String email ; private String hobby ; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getHobby() { return hobby; } public void setHobby(String hobby) { this.hobby = hobby; } public static void main(String[] args) { } }
建立一個Controller,名稱爲:UserController ,其中包含對用戶的各類操做的Handler
package cn.com.sports.controller; import java.util.List; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validator; import org.apache.commons.lang3.ClassUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import cn.com.sports.model.User; import cn.com.sports.utils.DB; import cn.com.sports.utils.KeyGeneratorImpl; import cn.com.sports.utils.Utils; @Controller @RequestMapping("/user") public class UserController { @Autowired private DB db ; @Autowired Validator validator ; /** * 返回添加人員視圖 * @return */ @RequestMapping("/addUserUI") public String addUI(){ return "/user/addUser"; } /** * 對添加人員進行處理 * @param user * @param modelMap * @return 服務器端定向到展現全部用戶頁面 */ @RequestMapping("/addUser") public String addUser(User user,ModelMap modelMap){ String url = "redirect:/user/showUsers.html" ; //服務器端驗證 String error = validate(user); if(!"".equals(error.toString())){ modelMap.addAttribute("errors", "用戶保存失敗!<br>"+error.toString()); return "/user/addUser"; } KeyGeneratorImpl k = new KeyGeneratorImpl(); try { user.setId(k.getKey()); user.setPassword(Utils.encrypt(user.getPassword())); } catch (Exception e) { e.printStackTrace(); } if(db.getUserByUserOrEmail(user.getUsername()) == null) db.saveOrUpdateUser(user); else{ modelMap.addAttribute("user", user); modelMap.addAttribute("flag", "1"); url = "/user/addUser"; } return url; } /** * 返回全部人員頁面的視圖 * @param modelMap * @return */ @RequestMapping("/showUsers") public String showUsers(ModelMap modelMap){ List<User> users = db.getAllUser(); modelMap.addAttribute("users",users); return "/user/showUsers"; } /** * 經過人員ID刪除人員 * @param modelMap * @param userId * @return */ @RequestMapping("/delUser/{userId}") public ModelAndView showUsers(ModelMap modelMap,@PathVariable String userId){ db.delUser(userId); return new ModelAndView("redirect:/user/showUsers.html"); } /** * 返回編輯頁面視圖 * @param modelMap * @param userId * @return */ @RequestMapping("/editUserUI/{userId}") public String editUserUI(ModelMap modelMap,@PathVariable String userId){ User user = db.getUserById(userId); modelMap.addAttribute("user",user); return "/user/editUser"; } /** * 對編輯人員進行處理 * @param user * @param modelMap * @return */ @RequestMapping("/editUser") public String editUserUI(User user,ModelMap modelMap){ //服務器端驗證 String error = validate(user); if(!"".equals(error.toString())){ modelMap.addAttribute("errors", "修改用戶失敗!<br>"+error.toString()); return "/user/editUser"; } db.saveOrUpdateUser(user); modelMap.addAttribute("flag", "1"); return "/user/editUser"; } public String validate(User user){ Set<ConstraintViolation<User>> violations = validator.validate(user); StringBuffer buf = new StringBuffer(); for(ConstraintViolation<User> violation: violations) { String f = violation.getPropertyPath().toString() ; buf.append(f +":"+ violation.getMessage() +"<br>" ); } return buf.toString(); } }
UserController中的方法不少,這裏咱們先只看addUI() 、 addUser() 、showUsers()這三方法
首先咱們經過標籤@Controller標註當前類爲一個Controller,而且用標籤@RequestMapping進行標註,其值爲"/user" ,說明UserController類中方法在其標籤@RequestMapping值中加上"/user"
其次addUI() 、 addUser() 、showUsers()三方法的標籤@RequestMapping("/addUserUI")、@RequestMapping("/addUser")、@RequestMapping("/showUsers") ,其含義是瀏覽器請求/user/addUserUI.php、/user/addUserHand.php 、/user/showUsers.php後分別請求到的資源
再對UserController中的類DB類進行說明,這裏的Validator類能夠先不看,後邊在進行說明
DB:這裏的DB至關於一個服務器端的臨時數據庫,對用戶的數據以及後邊的文件信息的維護
package cn.com.sports.utils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.springframework.stereotype.Component; import cn.com.sports.model.File; import cn.com.sports.model.User; @Component public class DB { private static Map<String,User> t_user = new HashMap<String,User>(); private static Map<String,File> t_file = new HashMap<String,File>(); public void saveOrUpdateUser(User user){ t_user.put(user.getId(), user); } public void delUser(String id){ t_user.remove(id); } public List<User> getAllUser(){ List<User> users = new ArrayList<User>(); Set<String> keys = t_user.keySet(); for(String key : keys){ users.add(t_user.get(key)); } return users ; } public User getUserById(String id){ return t_user.get(id); } public User getUserByUserOrEmail(String s){ User user = null ; List<User> users = getAllUser(); for(User u : users){ if(s.equals(u.getEmail()) || s.equals(u.getUsername())){ user = u ; break ; } } return user ; } public void saveFile(File file){ t_file.put(file.getId(), file); } public List<File> getAllFile(){ Set<String> files = t_file.keySet(); List<File> flist = new ArrayList<File>(); for(String f : files){ flist.add(t_file.get(f)); } return flist ; } }
說完了Model、Controller,下邊咱們來看下前端的View
addUser.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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=ISO-8859-1"> <%@ include file="/common/taglib.jsp" %> <%@ include file="/common/common.jsp" %> <base href="<%=basePath%>"> <title>添加用戶</title> </head> <body> <div class="container"> <h2 class="bg-info">添加用戶</h2> <c:if test="${flag == 1 }"> <h5 class="bg-danger">添加用戶失敗,Username重複</h5> </c:if> <span style="color: red;"> ${errors } </span> <form action="user/addUser.html" method="post"> <div class="form-group"> <label for="exampleInputEmail1">Username</label> <input type="text" class="form-control" id="exampleInputEmail1" placeholder="Username" name="username" value="${user.username }"> </div> <div class="form-group"> <label for="exampleInputEmail1">Email</label> <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email" name="email" value="${user.email }"> </div> <div class="form-group"> <label for="exampleInputPassword1">Password</label> <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password" name="password" value="${user.password }"> </div> <div class="form-group"> <label for="exampleInputEmail1">Yours Hobby</label> <input type="text" class="form-control" id="exampleInputEmail1" placeholder="hobby" name="hobby" value="${user.hobby }"> </div> <button type="submit" class="btn btn-default">Submit</button> <button type="reset" class="btn btn-default">Reset</button> </form> <br/> <a href="user/showUsers.html" >返回人員列表</a> </div> </body> </html>
用戶信息呈現列表:
showUsers.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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=ISO-8859-1"> <%@ include file="/common/taglib.jsp" %> <%@ include file="/common/common.jsp" %> <title>顯示全部用戶信息</title> <base href="<%=basePath%>"> </head> <body> <div class="container"> <h2 class="bg-info">展現用戶</h2> <table class="table table-bordered table-hover"> <thead> <tr> <th>Username</th> <th>Email</th> <th>Hobby</th> <th>ID</th> <th>Password</th> <th>操做</th> </tr> </thead> <c:forEach items="${users }" var="user"> <tr> <td> ${user.username } </td> <td>${user.email }</td> <td>${user.hobby }</td> <td>${user.id }</td> <td>${user.password }</td> <td><a href="user/delUser/${user.id }.html">刪除</a>|<a href="user/editUserUI/${user.id }.html">編輯</a></td> </tr> </c:forEach> </table> <br> <a href="">返回主頁</a> <a href="user/addUserUI.html">添加用戶</a> </div> </body> </html>
以上就完成了一個M、V、C的過程,經過開源中國的Git地址下載個人代碼,部署上項目,若是部署電腦IP爲127.0.0.1,端口爲8080,Sports-SpringMvc,那麼經過URL http://127.0.0.1:8080/Sports-SpringMvc/user/addUserUI.html 能訪問咱們的人員註冊頁面,效果圖以下:
保存成功後,跳轉到人員列表中,以下圖:
3三、爲了對當前項目有一個很清晰的說明,我簡單作了一個主頁(index.jsp),其代碼和頁面效果以下
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <%@ include file="/common/common.jsp" %> <%@ include file="/common/taglib.jsp" %> <base href="<%=basePath %>"> <script type="text/javascript"> $(document).ready(function(){ $("#logout").click(function(){ logout(); }); function logout(){ $.ajax({ type:"POST", url:"login/logout.html", data:{}, datatype: "text",//"xml", "html", "script", "json", "jsonp", "text". beforeSend:function(){}, //成功返回以後調用的函數 success:function(data){ window.location.reload(); }, //調用執行(success方法)後調用的函數 complete: function(XMLHttpRequest, textStatus){ }, //調用出錯執行的函數 error: function(){ //請求出錯處理 } }); } }); </script> </head> <body> <div class="container"> <h1>SpringMvc的學習</h1> <h4>咱們經過如下幾個場景來一塊兒學習<c:if test="${not empty userName}">,當前學習者:${userName } </c:if></h4> 一、<a href="user/showUsers.html">人員管理</a><br> 二、<a href="login/loginUI.html">人員登陸</a><br> 三、<a href="file/fileUI.html">上傳文件</a><br> 四、<a href="login/otherHandUI.html">其餘資源</a><br> 五、<a href="javascript:void()" id="logout">註銷</a> </div> </body> </html>
經過URL:http://127.0.0.1:8080/Sports-SpringMvc/ 訪問,其效果以下
3四、對功能模塊」其餘資源「的說明,該模塊中,只有當用戶登陸事後,才能顯示」其餘資源「下的內容,這個模塊中對過濾器進行了使用,訪問http://127.0.0.1:8080/Sports-SpringMvc/,點擊其餘資源,就能完成如下描述的操做
相關的代碼片斷:
spring-mvc.xml中的過濾器的代碼片斷,其做用是對URL :http://127.0.0.1:8080/Sports-SpringMvc//login/otherHandUI.html的攔截,若是登陸過,在跳轉到資源頁面,若是未登陸則進行登陸
<mvc:interceptors> <bean class="cn.com.sports.interceptor.AllInterceptor"></bean> <mvc:interceptor> <mvc:mapping path="/login/otherHandUI.html"/> <bean class="cn.com.sports.interceptor.LoginInterceptor"></bean> </mvc:interceptor> </mvc:interceptors>
cn.com.sports.interceptor.LoginInterceptor 類的代碼,判斷Session中是否保存了用戶的一個惟一標識USERID
package cn.com.sports.interceptor; import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import cn.com.sports.controller.LoginController; /** * 只攔截 /login/otherUI.html * @author Liw * */ public class LoginInterceptor implements HandlerInterceptor{ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception arg3) throws Exception { } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView arg3) throws Exception { } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception { Object o = request.getSession().getAttribute(LoginController.USERID); if(o == null){ RequestDispatcher rd = request.getRequestDispatcher("/login/loginUI.html"); rd.forward(request, response); return false ; }else{ return true; } } }
LoginController中的代碼片斷:其做用是返回一個Jsp頁面
/** * 登陸處理 * @param user * @param modelMap * @return 根據驗證結果返回不一樣的視圖 */ @RequestMapping("/otherHandUI") public String otherHandUI(){ return "/login/other"; }
other.jsp頁面代碼內容,不要太在乎該頁面的內容
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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=ISO-8859-1"> <%@ include file="/common/taglib.jsp" %> <%@ include file="/common/common.jsp" %> <base href="<%=basePath%>"> <title>其餘操做</title> </head> <body> <div class="container"> <h2 class="bg-info">其餘操做</h2> 哈哈,你終於註冊、登陸啦!<br><br> <a href="">返回主頁</a> </div> </body> </html>
3五、上傳文件
在瀏覽器中經過 http://127.0.0.1:8080/Sports-SpringMvc/ ,點擊上傳文件,就能完成如下描述的操做
FileController的代碼以下,其做用是對文件的上傳以及文件路徑的保存
package cn.com.sports.controller; import java.io.File; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import cn.com.sports.utils.DB; import cn.com.sports.utils.KeyGeneratorImpl; @Controller @RequestMapping("/file") public class FileController { @Autowired public KeyGeneratorImpl keyGeneratorImpl ; @Autowired public DB db ; /** * 返回文件上傳視圖 * @return */ @RequestMapping("/fileUI") public String uploadUI(ModelMap modelMap){ modelMap.put("files", db.getAllFile()); return "/file/file"; } /** * 處理文件上傳 * @param file * @param request * @param model * @return */ @RequestMapping("upload") public String upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, ModelMap model){ String path = request.getSession().getServletContext().getRealPath("upload"); String fileName = file.getOriginalFilename(); File targetFile = new File(path, fileName); if(!targetFile.exists()){ targetFile.mkdirs(); } try { file.transferTo(targetFile); } catch (Exception e) { e.printStackTrace(); } cn.com.sports.model.File mode = new cn.com.sports.model.File(); try { mode.setId(keyGeneratorImpl.getKey()); mode.setName(fileName); mode.setUrl(request.getContextPath()+"/upload/"+fileName); db.saveFile(mode); } catch (Exception e) { e.printStackTrace(); } model.addAttribute("fileUrl", request.getContextPath()+"/upload/"+fileName); return "redirect:/file/fileUI.html"; } }
spring-mvc.xml的代碼片斷:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding"> <value>UTF-8</value> </property> <property name="maxUploadSize"> <!-- 上傳文件大小限制爲31M,31*1024*1024 --> <value>32505856</value> </property> <property name="maxInMemorySize"> <value>4096</value> </property> </bean>
上傳頁面的代碼以及頁面展示效果:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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=ISO-8859-1"> <%@ include file="/common/taglib.jsp" %> <%@ include file="/common/common.jsp" %> <base href="<%=basePath%>"> <title>上傳文件</title> <script type="text/javascript"> function check(){ if($("#exampleInputFile").val() == ""){ alert('請選擇您要上傳的文件,圖片喲!'); return false ; }else{ return true ; } } </script> </head> <body> <div class="container"> <h2 class="bg-info">上傳文件</h2> <table class="table table-bordered table-hover"> <thead> <tr> <th>ID</th> <th>name</th> <th>文件</th> </tr> </thead> <c:forEach items="${files }" var="file"> <tr> <td> ${file.id} </td> <td>${file.name}</td> <td><a href="${file.url }"><img alt="" src="${file.url }" class="img-circle" height="100px;"></a></td> </tr> </c:forEach> </table> <form action="file/upload.html" enctype="multipart/form-data" method="post" onsubmit="return check()"> <div class="form-group"> <label for="exampleInputFile">File input</label> <input type="file" id="exampleInputFile" name="file" /> <p class="help-block">Example block-level help text here.</p> </div> <button type="submit" class="btn btn-default">Submit</button> <br><br><a href="">返回主頁</a> </form> </div> </body> </html>
其效果以下:
3六、表單服務器端的驗證,拿用戶註冊進行說明:
這個項目中經過HibernateValidator對錶單進行服務器端進行驗證,代碼片斷以下:
spring-mvc.xml
<!-- 如下 validator ConversionService 在使用 mvc:annotation-driven 會 自動註冊--> <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/> </bean>
UserController中的相關代碼片斷:
/** * 對添加人員進行處理 * @param user * @param modelMap * @return 服務器端定向到展現全部用戶頁面 */ @RequestMapping("/addUser") public String addUser(User user,ModelMap modelMap){ String url = "redirect:/user/showUsers.html" ; //服務器端驗證 String error = validate(user); if(!"".equals(error.toString())){ modelMap.addAttribute("errors", "用戶保存失敗!<br>"+error.toString()); return "/user/addUser"; } KeyGeneratorImpl k = new KeyGeneratorImpl(); try { user.setId(k.getKey()); user.setPassword(Utils.encrypt(user.getPassword())); } catch (Exception e) { e.printStackTrace(); } if(db.getUserByUserOrEmail(user.getUsername()) == null) db.saveOrUpdateUser(user); else{ modelMap.addAttribute("user", user); modelMap.addAttribute("flag", "1"); url = "/user/addUser"; } return url; } public String validate(User user){ Set<ConstraintViolation<User>> violations = validator.validate(user); StringBuffer buf = new StringBuffer(); for(ConstraintViolation<User> violation: violations) { String f = violation.getPropertyPath().toString() ; buf.append(f +":"+ violation.getMessage() +"<br>" ); } return buf.toString(); }
添加頁面的效果:
但願以上博文對初學者有幫助,具體詳細代碼能夠到https://git.oschina.net/liw/Sports-SpringMvc.git中下載,編寫博文不免有不詳細或者理解有誤,若有但願指出,並能相互學習。