您的位置:首页 > 编程语言 > Java开发

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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: