Spring Mvc——Controller中常规方法示例
2016-03-23 08:50
507 查看
一,简单无参数地址访问
首先来看下类标记:/** * Created by LiuHuiChao on 2016/3/21. */ @Controller @RequestMapping("/hello") public class HelloMvcController {
简单进行类中方法的访问:
/*简单访问示例*/ @RequestMapping("/mvc") public String helloMvc() { return "home"; }
二,使用Servlet api方式获取参数
/* request方式获取参数 */ @RequestMapping("/views3") public String viewCourse3(HttpServletRequest request) { Integer courseId = Integer.valueOf(request.getParameter("courseId")); System.out.println(courseId); return "home"; }
三,通过方法参数方式获取
/* 本方法处理 /hello/view?courseId=123 */ @RequestMapping(value = "/views", method = RequestMethod.GET) public String viewCourse(@RequestParam("courseId") Integer courseId) { System.out.println(courseId); return "home"; }
四,restful 风格URL参数获取
/* restful 风格URL示例 */ /* 本方法处理 /hello/view/{courseId} */ @RequestMapping(value = "/views/{courseId}", method = RequestMethod.GET) public String viewCourse2(@PathVariable("courseId") Integer courseId, Map<String, Object> model) { System.out.println("restful风格URL示例测试---" + courseId); // model.put("course",courseId); return "home"; }
五,重定向操作
/*重定向操作*/ @RequestMapping(value = "/save", method = RequestMethod.POST) public String doSave(@ModelAttribute Course course) { // 再此处进行save操作 return "redirect:views/" + course.getCourseId();// 重定向 }
六,接收上传的文件
/*上传文件示例*/ @RequestMapping(value="/doUpload",method=RequestMethod.POST) public String doUploadFile(@RequestParam("file") MultipartFile file){ if(!file.isEmpty()){ System.out.println("请在这里写入对文件的操作"); //写入文件等操作。。。。 } return "success"; }
另外,还需要在spring mvc的配置文件中加入:
<!-- 配置上传文件 --> <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>
相关文章推荐
- 举例讲解Java编程中this关键字与super关键字的用法
- Struts2 S2-029远程代码执行漏洞
- java多线程回顾1:线程的概念与创建
- springMVC传递日期类型参数
- <转载> JavaSript模块规范 - AMD规范与CMD规范介绍
- [J2EE]java操作json
- spring初步和struts2整合
- Java命名规范及给自己写的方法添加注解
- Spring源码之bean的加载(五)准备创建bean
- Spring源码之bean的加载(四)获取单例
- Spring源码之bean的加载(三)从bean中获取对象
- Spring源码之bean的加载(二)获取单例bean
- Spring源码之bean的加载(一)
- Java 反射机制理解
- Java NIO和IO的主要区别
- 线程安全的单例模式
- Spring Boot学习笔记
- Java8 Lambda表达式教程
- java基础学习----String
- java-斐波那契数列