springmvc笔记(基本配置,核心文件,路径,参数,文件上传,json整合)

时间:2022-04-27 08:50:12

首先导入jar包

springmvc笔记(基本配置,核心文件,路径,参数,文件上传,json整合)

大家注意一下我的springmvc,jackson,common-up的jar包版本.其他版本有可能出现不兼容.

src文件:

springmvc笔记(基本配置,核心文件,路径,参数,文件上传,json整合)

webroot目录:

springmvc笔记(基本配置,核心文件,路径,参数,文件上传,json整合)

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_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>springmvc7</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- DispatcherServlet对应的上下文配置,默认/WEB-INF/$servlet-name$-servlet.xml
下面配置spring-mvc的核心配置文件
-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/configs/spring/mvc-dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<!-- mvc-dispatcher 拦截所有的请求 -->
<url-pattern>/</url-pattern>
</servlet-mapping> </web-app>
mvc-dispatcher-servlet.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 激活
@Required
@Autowired,jsr250's
@PostConstruct,
@PreDestroy and @ Resource等标注
-->
<context:annotation-config />
<!--
DispatcherServlet上下文,只搜索@Controller标注的类,不搜索其他标注的类
-->
<context:component-scan base-package="com.gys.mvcdemo">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan> <!-- HandlerMapping无需配置,Spring MVC可以默认启动
-->
<!--
扩充了注解驱动,可以将请求参数绑定到控制器参数
启用基于annotation的handlerMapping.
-->
<mvc:annotation-driven /> <!--
静态资源处理,css,js,imgs
-->
<mvc:resources location="/resources/" mapping="/resources/**"/> <!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsps/" />
<property name="suffix" value=".jsp" />
</bean> <!-- 配置上传文件代码,导入commons-fileupload-1.2.2.jar,commons-io-2.4.jar
200*1024*1024即200M resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常
-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传的最大限制 -->
<property name="maxUploadSize" value="209715200" />
<!-- 默认编码 -->
<property name="defaultEncoding" value="UTF-8" />
<!-- 上传文件的解析 -->
<property name="resolveLazily" value="true" />
</bean> <!-- 整合json,导入jackson-core-asl-1.1.2.jar,jackson-mapper-asl-1.1.2.jar
配置ViewResolver.
可以用多个ViewResolver.使用order属性排序.InternalResourceViewResolver放在最后
-->
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1" />
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
<entry key="htm" value="text/html" />
</map>
</property>
<property name="defaultViews">
<list>
<!-- JSON View -->
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"></bean>
</list>
</property>
<property name="ignoreAcceptHeader" value="true" />
</bean>
</beans>

上传文件的页面:

file.jsp:

 <%@ page language="java" import="java.util.*" 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">
<html>
<head>
<base href="<%=basePath%>"> <title>上传页面</title> </head> <body>
<h1>上传附件</h1>
<form method="post" action="<%=path %>/courses/doUpload" enctype="multipart/form-data">
<input type="file" name="file" /><br/>
<input type="submit" value="上传" />
</form> </body>
</html>

Course.java

 package com.gys.mvcdemo.model;

 public class Course {
//课程IDd
private Integer courseId;
//课程名称
private String title;
//图片路径
private String imgPath;
//学习人数
private Integer learningNum;
//课程时长
private Long duration;
//课程难度
private Integer level;
//课程描述
private String levelDesc;
//课程介绍
private String descr;
public Integer getCourseId() {
return courseId;
}
public void setCourseId(Integer courseId) {
this.courseId = courseId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getImgPath() {
return imgPath;
}
public void setImgPath(String imgPath) {
this.imgPath = imgPath;
}
public Integer getLearningNum() {
return learningNum;
}
public void setLearningNum(Integer learningNum) {
this.learningNum = learningNum;
}
public Long getDuration() {
return duration;
}
public void setDuration(Long duration) {
this.duration = duration;
}
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
public String getLevelDesc() {
return levelDesc;
}
public void setLevelDesc(String levelDesc) {
this.levelDesc = levelDesc;
}
public String getDescr() {
return descr;
}
public void setDescr(String descr) {
this.descr = descr;
} }

CourseServiceImpl.java

 package com.gys.mvcdemo.service.impl;

 import org.springframework.stereotype.Service;

 import com.gys.mvcdemo.model.Course;
import com.gys.mvcdemo.service.CourseService; @Service("courseService")
public class CourseServiceImpl implements CourseService{ @Override
public Course getCoursebyId(Integer courseId) {
Course course=new Course();
course.setCourseId(courseId);
course.setTitle("深入浅出Java多线程");
course.setImgPath("1.jpg");
course.setLearningNum(123465);
course.setLevel(2);
course.setLevelDesc("中级");
course.setDuration(7200L);
course.setDescr("多线程是日常开发中的常用知识...........");
return course;
}
}

CourseService.java

 package com.gys.mvcdemo.service;

 import com.gys.mvcdemo.model.Course;

 public interface CourseService {
Course getCoursebyId(Integer courseId);
}

CourseController.java

 package com.gys.mvcdemo.controller;

 import java.io.File;
import java.io.IOException;
import java.util.Map; import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile; import com.gys.mvcdemo.model.Course;
import com.gys.mvcdemo.service.CourseService; @Controller
@RequestMapping("/courses")
public class CourseController { private CourseService courseService; @Autowired
public void setCourseService(CourseService courseService) {
this.courseService = courseService;
} /**
* 路径一
* /courses/vies?courseId=123
* @param model
* @param courseId
* @return
*/
@RequestMapping(value="/view",method=RequestMethod.GET)
public String viewCourse(Model model,@RequestParam("courseId") Integer courseId){
Course course=courseService.getCoursebyId(courseId);
model.addAttribute(course);
return "course_overview";
}
/**
* 路径二
* courses/view2/{courseId}
* @param courseId
* @param model
* @return
*/
@RequestMapping(value="/view2/{courseId}",method=RequestMethod.GET)
public String viewCourse2(@PathVariable("courseId") Integer courseId,Map<String, Object> model){
Course course=courseService.getCoursebyId(courseId);
model.put("course",course);
return "course_overview";
} /**
* 路径三
* courses/view3?courseId=3
* @param request
* @param response
* @return
*/
@RequestMapping("view3")
public String viewCourse3(HttpServletRequest request,HttpServletResponse response){
Integer courseId=Integer.valueOf(request.getParameter("courseId"));
Course course=courseService.getCoursebyId(courseId);
request.setAttribute("course", course);
return "course_overview";
}
/**
* 路径四
* courses/admin?add
* @return
*/
@RequestMapping(value="/admin",method=RequestMethod.GET,params="add")
public String createCourse(){ return "course_admin/edit";
}
/**
* 服务器内部跳转
* @param course
* @return
*/
@RequestMapping(value="/save",method=RequestMethod.POST)
public String doSave(Course course){
course.setCourseId(123);
//跳转
return "redirect:view2/"+course.getCourseId();
}
/**
* 上传页面
* @return
*/
@RequestMapping(value="/upload",method=RequestMethod.GET)
public String showUploadPage(){
return "course_admin/file";
}
/**
* 上传文件
* @param file
* @return
* @throws IOException
*/
@RequestMapping(value="/doUpload",method=RequestMethod.POST)
public String doUploadFile(@RequestParam("file") MultipartFile file) throws IOException{
if(!file.isEmpty()){
System.out.println("提示:"+file.getOriginalFilename());
FileUtils.copyInputStreamToFile(file.getInputStream(), new File("d:\\upload\\",System.currentTimeMillis()+file.getOriginalFilename()));
}
return "success";
}
/**
* 向前台返回json1
* @param courseId
* @return
*/
@RequestMapping(value="/{courseId}",method=RequestMethod.GET)
public @ResponseBody Course getCoruseInJson(@PathVariable("courseId") Integer courseId){
return courseService.getCoursebyId(courseId);
}
/**
* 向前台返回json2
* @param courseId
* @return
*/
@RequestMapping(value="/jsontype/{courseId}",method=RequestMethod.GET)
public ResponseEntity<Course> getCoruseInJson2(@PathVariable("courseId") Integer courseId){
Course course=courseService.getCoursebyId(courseId);
return new ResponseEntity<Course>(course,HttpStatus.OK);
} }

完了!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!