经过前面的学习,我们已经初步掌握了spring的用法,搭建简单的spring环境已经没问题了。在上一篇教程当中(搭建SpringMVC框架,实现简单登陆功能 ),我们已经能够使用spring mvc实现简单的登陆了。
这次我们尝试用『注解』的方式完成以下功能:
1、开发登陆功能(登陆成功跳转到登陆成功页面,失败给出相应的错误提示)
2、在登陆成功页面实现文件上传,并保存到指定目录下。
工具准备
1:MyEclipse 10 + Jdk6.0 及以上
2:所需Jar包
大致步骤
1.创建动态WEB项目
2.添加jar
3.添加注解和文件上传相关的配置
4.实现登陆功能
5.实现文件上传功能
配置
1、使用Eclipse创建web项目SpringMVCDemo2

2、添加所需的jar
下载前面提供的jar并导入到项目当中

3、配置web.xml
配置spring拦截的请求
配置乱码解决方案
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
| <?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"> <display-name>SpringMVCDemo2LoginAndFile</display-name>
<servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>WEB-INF/config/applicationContext*.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping>
<!-- 乱码解决 --> <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>
</web-app> ```
4、创建Spring配置文件applicationContext.xml,放到WEB-INF/config/目录下
使用注解方式配置
multipartResolver: 文件上传配置
``` bash <?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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd ">
<!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射,解决@ResponseBody乱码问题, 需要在annotation-driven之前,否则乱码问题同样无法解决 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> </list> </property> </bean>
<!-- 向 spring 容器中注册 DefaultAnnotationHandlerMapping。 向 spring 容器中注册 AnnotationMethodHandlerAdapter。 配置一些 messageconverter。 解决了 @Controller 注解的使用前提配置,即 HandlerMapping 能够知道谁来处理请求。 --> <mvc:annotation-driven /> <context:component-scan base-package="com.xhay1122.controller" /> <!-- 支持上传文件 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans> ```
5、业务逻辑控制器
*登陆:LoginController.java* ``` bash package com.xhay1122.controller;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView;
@Controller @RequestMapping("/loginController") public class LoginController{
@RequestMapping(value={"/login"}) public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { //获取表单提交数据 String userName = request.getParameter("userName"); String userPwd = request.getParameter("userPwd"); //创建模型视图对象用来返回 ModelAndView mav = new ModelAndView(); if("admin".equals(userName) && "admin".equals(userPwd)){ System.out.println("登陆成功"); //将页面需要使用的数据保存 //设置视图名称 mav.setViewName("redirect:/index.jsp"); } else{ System.out.println("登陆失败"); mav.addObject("error", "用户名或密码错误"); mav.setViewName("/login"); }
return mav; } }
```
*补充:*
Spring用ModelAndView实现forward、redirect。
forward是服务器内部重定向,程序收到请求后重新定向到另一个程序,客户端并不知道。浏览器地址栏的URL并不会改变。
redirect则是服务器收到请求后发送一个HTTP状态头给客户,让客户将再请求一次,这里多了两次网络通信的来往。浏览器地址栏的URL会改变。
若用Servlet的api,是如下的方式来实现
forward: request.getRequestDispatcher(“/somePage.jsp”).forwardrequest, response);
redirect: response.sendRedirect(“/somePage.jsp”);
spring web framework利用ModelAndView也能实现forward、redirect
``` bash forward: return ModelAndView(“forward:/somePage”); redirect: return ModelAndView(“redirect:/somePage”);
|
文件控制器:FileController.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| package com.xhay1122.controller;
import java.io.File;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest;
@Controller @RequestMapping("/fileController") public class FileController {
@RequestMapping(value = "/upload") @ResponseBody public String upload(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception { MultipartHttpServletRequest mhsr = (MultipartHttpServletRequest) arg0; //转换请求为文件上传请求 MultipartFile file = mhsr.getFile("upload"); System.out.println(file.getContentType());//文件类型 System.out.println(file.getSize()); // 获取文件大小 System.out.println(file.getOriginalFilename()); // 获取文件名称 if (!file.isEmpty()) {// 判断文件是否存在 String path ="I:\\worktools\\tomcat7\\webapps\\"+file.getOriginalFilename(); File localFile = new File(path); try { file.transferTo(localFile);//保存文件 } catch (Exception e) { e.printStackTrace(); return "文件上传失败!!!"; } } return "文件上传成功!!!"; } }
|
6、JSP页面
登陆界面:login.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| <%@ 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"> <title>用户登录</title> </head> <body> ${error } <form action="loginController/login.do" method="post"> 用户名:<input type="text" name="userName" /><br /> 密 码:<input type="password" name="userPwd" /><br /> <input type="submit" value="登陆" /> <input type="reset" value="重置" /> </form> </body> </html>
|
文件上传:index.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <%@ 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=UTF-8"> <title>上传文件</title> </head> <body> <form action="fileController/upload.do" method="post" enctype="multipart/form-data"> 选择文件:<input type="file" name="upload" /><br /> <input type="submit" value="上传" /> <input type="reset" value="重置" /> </form> </body> </html>
|
效果截图


下载完整源代码
推荐资料
1、 Spring MVC 中的基于注解的 Controller
2、 SpringMVC 基于注解的Controller @RequestMapping