springmvc笔记(基本配置,核心文件,路径,参数,文件上传,json整合)
首先导入jar包
大家注意一下我的springmvc,jackson,common-up的jar包版本.其他版本有可能出现不兼容.
src文件:
webroot目录:
web.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <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"> 3 <display-name>springmvc7</display-name> 4 <welcome-file-list> 5 <welcome-file>index.jsp</welcome-file> 6 </welcome-file-list> 7 <servlet> 8 <servlet-name>mvc-dispatcher</servlet-name> 9 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 10 <!-- DispatcherServlet对应的上下文配置,默认/WEB-INF/$servlet-name$-servlet.xml 11 下面配置spring-mvc的核心配置文件 12 --> 13 <init-param> 14 <param-name>contextConfigLocation</param-name> 15 <param-value>/WEB-INF/configs/spring/mvc-dispatcher-servlet.xml</param-value> 16 </init-param> 17 <load-on-startup>1</load-on-startup> 18 </servlet> 19 <servlet-mapping> 20 <servlet-name>mvc-dispatcher</servlet-name> 21 <!-- mvc-dispatcher 拦截所有的请求 --> 22 <url-pattern>/</url-pattern> 23 </servlet-mapping> 24 25 26 </web-app>
mvc-dispatcher-servlet.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:p="http://www.springframework.org/schema/p" 5 xmlns:context="http://www.springframework.org/schema/context" 6 xmlns:mvc="http://www.springframework.org/schema/mvc" 7 xmlns:tx="http://www.springframework.org/schema/tx" 8 xmlns:aop="http://www.springframework.org/schema/aop" 9 xsi:schemaLocation=" 10 http://www.springframework.org/schema/beans 11 http://www.springframework.org/schema/beans/spring-beans.xsd 12 http://www.springframework.org/schema/context 13 http://www.springframework.org/schema/context/spring-context.xsd 14 http://www.springframework.org/schema/mvc 15 http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 16 http://www.springframework.org/schema/tx 17 http://www.springframework.org/schema/tx/spring-tx.xsd 18 http://www.springframework.org/schema/aop 19 http://www.springframework.org/schema/aop/spring-aop.xsd"> 20 21 <!-- 激活 22 @Required 23 @Autowired,jsr250's 24 @PostConstruct, 25 @PreDestroy and @ Resource等标注 26 --> 27 <context:annotation-config /> 28 <!-- 29 DispatcherServlet上下文,只搜索@Controller标注的类,不搜索其他标注的类 30 --> 31 <context:component-scan base-package="com.gys.mvcdemo"> 32 <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> 33 </context:component-scan> 34 35 <!-- 36 37 HandlerMapping无需配置,Spring MVC可以默认启动 38 --> 39 <!-- 40 扩充了注解驱动,可以将请求参数绑定到控制器参数 41 启用基于annotation的handlerMapping. 42 --> 43 <mvc:annotation-driven /> 44 45 <!-- 46 静态资源处理,css,js,imgs 47 --> 48 <mvc:resources location="/resources/" mapping="/resources/**"/> 49 50 51 <!-- 视图解析器 --> 52 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 53 <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> 54 <property name="prefix" value="/WEB-INF/jsps/" /> 55 <property name="suffix" value=".jsp" /> 56 </bean> 57 58 <!-- 配置上传文件代码,导入commons-fileupload-1.2.2.jar,commons-io-2.4.jar 59 200*1024*1024即200M resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常 60 --> 61 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 62 <!-- 上传的最大限制 --> 63 <property name="maxUploadSize" value="209715200" /> 64 <!-- 默认编码 --> 65 <property name="defaultEncoding" value="UTF-8" /> 66 <!-- 上传文件的解析 --> 67 <property name="resolveLazily" value="true" /> 68 </bean> 69 70 <!-- 整合json,导入jackson-core-asl-1.1.2.jar,jackson-mapper-asl-1.1.2.jar 71 配置ViewResolver. 72 可以用多个ViewResolver.使用order属性排序.InternalResourceViewResolver放在最后 73 --> 74 <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> 75 <property name="order" value="1" /> 76 <property name="mediaTypes"> 77 <map> 78 <entry key="json" value="application/json" /> 79 <entry key="xml" value="application/xml" /> 80 <entry key="htm" value="text/html" /> 81 </map> 82 </property> 83 <property name="defaultViews"> 84 <list> 85 <!-- JSON View --> 86 <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"></bean> 87 </list> 88 </property> 89 <property name="ignoreAcceptHeader" value="true" /> 90 </bean> 91 </beans>
上传文件的页面:
file.jsp:
1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 8 <html> 9 <head> 10 <base href="<%=basePath%>"> 11 12 <title>上传页面</title> 13 14 </head> 15 16 <body> 17 <h1>上传附件</h1> 18 <form method="post" action="<%=path %>/courses/doUpload" enctype="multipart/form-data"> 19 <input type="file" name="file" /><br/> 20 <input type="submit" value="上传" /> 21 </form> 22 23 </body> 24 </html>
Course.java
1 package com.gys.mvcdemo.model; 2 3 public class Course { 4 //课程IDd 5 private Integer courseId; 6 //课程名称 7 private String title; 8 //图片路径 9 private String imgPath; 10 //学习人数 11 private Integer learningNum; 12 //课程时长 13 private Long duration; 14 //课程难度 15 private Integer level; 16 //课程描述 17 private String levelDesc; 18 //课程介绍 19 private String descr; 20 public Integer getCourseId() { 21 return courseId; 22 } 23 public void setCourseId(Integer courseId) { 24 this.courseId = courseId; 25 } 26 public String getTitle() { 27 return title; 28 } 29 public void setTitle(String title) { 30 this.title = title; 31 } 32 public String getImgPath() { 33 return imgPath; 34 } 35 public void setImgPath(String imgPath) { 36 this.imgPath = imgPath; 37 } 38 public Integer getLearningNum() { 39 return learningNum; 40 } 41 public void setLearningNum(Integer learningNum) { 42 this.learningNum = learningNum; 43 } 44 public Long getDuration() { 45 return duration; 46 } 47 public void setDuration(Long duration) { 48 this.duration = duration; 49 } 50 public Integer getLevel() { 51 return level; 52 } 53 public void setLevel(Integer level) { 54 this.level = level; 55 } 56 public String getLevelDesc() { 57 return levelDesc; 58 } 59 public void setLevelDesc(String levelDesc) { 60 this.levelDesc = levelDesc; 61 } 62 public String getDescr() { 63 return descr; 64 } 65 public void setDescr(String descr) { 66 this.descr = descr; 67 } 68 69 70 71 72 }
CourseServiceImpl.java
1 package com.gys.mvcdemo.service.impl; 2 3 import org.springframework.stereotype.Service; 4 5 import com.gys.mvcdemo.model.Course; 6 import com.gys.mvcdemo.service.CourseService; 7 8 @Service("courseService") 9 public class CourseServiceImpl implements CourseService{ 10 11 @Override 12 public Course getCoursebyId(Integer courseId) { 13 Course course=new Course(); 14 course.setCourseId(courseId); 15 course.setTitle("深入浅出Java多线程"); 16 course.setImgPath("1.jpg"); 17 course.setLearningNum(123465); 18 course.setLevel(2); 19 course.setLevelDesc("中级"); 20 course.setDuration(7200L); 21 course.setDescr("多线程是日常开发中的常用知识..........."); 22 return course; 23 } 24 }
CourseService.java
1 package com.gys.mvcdemo.service; 2 3 import com.gys.mvcdemo.model.Course; 4 5 public interface CourseService { 6 Course getCoursebyId(Integer courseId); 7 }
CourseController.java
1 package com.gys.mvcdemo.controller; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.util.Map; 6 7 import javax.annotation.Resource; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 11 import org.apache.commons.io.FileUtils; 12 import org.springframework.beans.factory.annotation.Autowired; 13 import org.springframework.http.HttpStatus; 14 import org.springframework.http.ResponseEntity; 15 import org.springframework.stereotype.Controller; 16 import org.springframework.ui.Model; 17 import org.springframework.web.bind.annotation.PathVariable; 18 import org.springframework.web.bind.annotation.RequestMapping; 19 import org.springframework.web.bind.annotation.RequestMethod; 20 import org.springframework.web.bind.annotation.RequestParam; 21 import org.springframework.web.bind.annotation.ResponseBody; 22 import org.springframework.web.multipart.MultipartFile; 23 24 import com.gys.mvcdemo.model.Course; 25 import com.gys.mvcdemo.service.CourseService; 26 27 @Controller 28 @RequestMapping("/courses") 29 public class CourseController { 30 31 private CourseService courseService; 32 33 @Autowired 34 public void setCourseService(CourseService courseService) { 35 this.courseService = courseService; 36 } 37 38 /** 39 * 路径一 40 * /courses/vies?courseId=123 41 * @param model 42 * @param courseId 43 * @return 44 */ 45 @RequestMapping(value="/view",method=RequestMethod.GET) 46 public String viewCourse(Model model,@RequestParam("courseId") Integer courseId){ 47 Course course=courseService.getCoursebyId(courseId); 48 model.addAttribute(course); 49 return "course_overview"; 50 } 51 /** 52 * 路径二 53 * courses/view2/{courseId} 54 * @param courseId 55 * @param model 56 * @return 57 */ 58 @RequestMapping(value="/view2/{courseId}",method=RequestMethod.GET) 59 public String viewCourse2(@PathVariable("courseId") Integer courseId,Map<String, Object> model){ 60 Course course=courseService.getCoursebyId(courseId); 61 model.put("course",course); 62 return "course_overview"; 63 } 64 65 /** 66 * 路径三 67 * courses/view3?courseId=3 68 * @param request 69 * @param response 70 * @return 71 */ 72 @RequestMapping("view3") 73 public String viewCourse3(HttpServletRequest request,HttpServletResponse response){ 74 Integer courseId=Integer.valueOf(request.getParameter("courseId")); 75 Course course=courseService.getCoursebyId(courseId); 76 request.setAttribute("course", course); 77 return "course_overview"; 78 } 79 /** 80 * 路径四 81 * courses/admin?add 82 * @return 83 */ 84 @RequestMapping(value="/admin",method=RequestMethod.GET,params="add") 85 public String createCourse(){ 86 87 return "course_admin/edit"; 88 } 89 /** 90 * 服务器内部跳转 91 * @param course 92 * @return 93 */ 94 @RequestMapping(value="/save",method=RequestMethod.POST) 95 public String doSave(Course course){ 96 course.setCourseId(123); 97 //跳转 98 return "redirect:view2/"+course.getCourseId(); 99 } 100 /** 101 * 上传页面 102 * @return 103 */ 104 @RequestMapping(value="/upload",method=RequestMethod.GET) 105 public String showUploadPage(){ 106 return "course_admin/file"; 107 } 108 /** 109 * 上传文件 110 * @param file 111 * @return 112 * @throws IOException 113 */ 114 @RequestMapping(value="/doUpload",method=RequestMethod.POST) 115 public String doUploadFile(@RequestParam("file") MultipartFile file) throws IOException{ 116 if(!file.isEmpty()){ 117 System.out.println("提示:"+file.getOriginalFilename()); 118 FileUtils.copyInputStreamToFile(file.getInputStream(), new File("d:\\upload\\",System.currentTimeMillis()+file.getOriginalFilename())); 119 } 120 return "success"; 121 } 122 /** 123 * 向前台返回json1 124 * @param courseId 125 * @return 126 */ 127 @RequestMapping(value="/{courseId}",method=RequestMethod.GET) 128 public @ResponseBody Course getCoruseInJson(@PathVariable("courseId") Integer courseId){ 129 return courseService.getCoursebyId(courseId); 130 } 131 /** 132 * 向前台返回json2 133 * @param courseId 134 * @return 135 */ 136 @RequestMapping(value="/jsontype/{courseId}",method=RequestMethod.GET) 137 public ResponseEntity<Course> getCoruseInJson2(@PathVariable("courseId") Integer courseId){ 138 Course course=courseService.getCoursebyId(courseId); 139 return new ResponseEntity<Course>(course,HttpStatus.OK); 140 } 141 142 }
完了!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!