1、SpringMVC基本配置
1)引入spring Jar包
2)配置web.xm文件,加载SpringMVC配置
<?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>springmvc</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <!-- Spring MVC配置 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 可以自定义springMVC-servlet.xml(默认名称)配置文件的位置和名称,默认为WEB-INF目录下,名称为[<servlet-name>]-servlet.xml,如spring-servlet.xml --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/classpath:config/spring-servlet.xml</param-value> </init-param> <!-- 启动的时候加载servlet --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 配置编码格式 --> <filter> <filter-name>SetCharacterEncoding</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>SetCharacterEncoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- Spring配置 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 指定Spring Bean的配置文件所在目录。默认配置在WEB-INF目录下 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:config/applicationContext.xml</param-value> </context-param> </web-app>
3)配置spring-servlet.xml文件,加载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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:security="http://www.springframework.org/schema/security" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 启用springmvc注解 --> <mvc:annotation-driven /> <!-- 设置使用注解的类所在的jar包 --> <context:component-scan base-package="com.shma.springmvc.controller" /> <!-- 静态资源的访问 --> <mvc:resources location="/resources/img/" mapping="/resources/img/**"/> <mvc:resources location="/resources/js/" mapping="/resources/js/**"/> <mvc:resources location="/resources/css/" mapping="/resources/css/**"/> <!-- 配置视图对转向页面的路径解析,prefix:前缀, suffix:后缀 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 上传文件的解析器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="utf-8"/> <property name="maxUploadSize" value="10485760000"/> <property name="maxInMemorySize" value="40960"/> </bean> </beans>
2、http请求中的中文乱码问题处理
1)客户端JS代码,将字符串进行url编码
var username = encodeURI($("#username").val()); var password = encodeURI($("#password").val());
2)服务器端,用URLDecoder.decode进行解码
String username = URLDecoder.decode(user.getUsername(), "UTF-8"); String password = URLDecoder.decode(user.getPassword(), "UTF-8");
3、SpringMVC注解含义
@Controller:控制器
@RequestMapping(value="user", method=RequestMethod.POST):设置请求的路径和方法
@ResponseBody:设置返回格式为json
@RequestParam("username") String userName:请求参数设置
4、SpringMVC上传文件
Spring通过对Servlet API的HttpServletRequest接口进行扩展,使其能够很好地处理文件上传。扩展后的接口名为org.springframework.web.multipart.MultipartHttpServletRequest
interface MultipartHttpServletRequest extends HttpServletRequest { public MultipartFile getFile(String name); public Map getFileMap(); public Iterator getFileNames(); }
1)引入:Commons-FileupLoad.jar和Commons-IO.jar包
2)配置文件解析器
<!-- 上传文件配置 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="utf-8" /> <property name="maxUploadSize" value="10485760000" /> <property name="maxInMemorySize" value="40960" /> </bean>
3)前端页面
<form action="../file/upload.do" method="post" enctype="multipart/form-data"> <input name="file" type="file" /> <input type="submit" value="提交" /> </form>
4)后台代码
a)自定义读取文件流方法
@RequestMapping(value="upload", method=RequestMethod.POST) public String upload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest req) { String fileName = file.getOriginalFilename(); System.out.println("您上传的文件名称为:" + fileName); if(!StringUtils.isEmpty(fileName)) { File nFile = new File("D:/file/" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + fileName); if(!nFile.exists()) { FileOutputStream fos = null; InputStream in = null; try { nFile.createNewFile(); fos = new FileOutputStream(nFile); in = file.getInputStream(); int b = -1; while((b = in.read()) != -1) { fos.write(b); } fos.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { in.close(); fos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } return "success"; }
b)springmvc自带的上传文件方法(推荐使用)
@RequestMapping(value="uploadfile", method=RequestMethod.POST) public String uploadForSpringMVC(HttpServletResponse resp, HttpServletRequest req) { CommonsMultipartResolver multReslover = new CommonsMultipartResolver(req.getServletContext()); if(multReslover.isMultipart(req)) { MultipartHttpServletRequest multServletReq = (MultipartHttpServletRequest)req; Iterator<String> files = multServletReq.getFileNames(); while(files.hasNext()) { try { MultipartFile multiFile = multServletReq.getFile(files.next()); File nFile = new File("D:/file/" + new SimpleDateFormat("yyyyMMddHHssmm").format(new Date()) + "_" + multiFile.getOriginalFilename()); if(!nFile.exists()) { nFile.createNewFile(); } multiFile.transferTo(nFile); } catch(IOException e) { e.printStackTrace(); } } } return "success"; }