SpringMVC使用的几个要点
1.使用 @RequestParam("username") 来对应参数名的时候,这个参数必须要传入,否则会报错。没加@RequestParam则可传可不传
@RequestMapping("/index")
public String index(@RequestParam("username") String username, String password) {
System.out.println(username);
System.out.println(password);
return "test/index";
}
2.向页面传值,可以用Map也可以用Model,通常都用Model
@RequestMapping("/index2")
public String index2(String username, Map<String, Object> context) {
System.out.println(username);
context.put("username", username);
return "test/index";
}
@RequestMapping("/index3")
public String index3(String username, Model model) {
// System.out.println("id:" + id);
System.out.println(username);
model.addAttribute("username", "username");
// 只有一个参数,默认key就是小写的对象名称
model.addAttribute(new Article());
return "test/index";
}
页面:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>test ${username }
${article.id }
</body>
</html>
3. method = RequestMethod.GET 代表get方式访问
@RequestMapping(value = "/index4", method = RequestMethod.GET)
public String index4(String username, Model model) {
// System.out.println("id:" + id);
System.out.println(username);
model.addAttribute("username", "username");
// 只有一个参数,默认key就是小写的对象名称
model.addAttribute(new Article());
return "test/index";
}
4. 通过url传值用 @PathVariable @RequestMapping value可以直接支持多级目录的路径,不像asp.net mvc需要在global.asax中设置路由
// www.url.com/test/p1 读取url的地址作为参数
@RequestMapping(value = "/{username}", method = RequestMethod.GET)
public String show(@PathVariable String username) {
System.out.println(username);
return "test/index";
} // www.url.com/test/p1 读取url的地址作为参数
@RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
public String show2(@PathVariable String id) {
System.out.println("show2 " + id);
return "test/index";
} @RequestMapping(value = "/update/detail/{id}", method = RequestMethod.GET)
public String show3(@PathVariable String id) {
System.out.println("show3 " + id);
return "test/index";
}
5. (1) 可以通过 bean-validator.jar 对springMVC 做服务端校验,校验时@Validated Menu menu, BindingResult br 参数必须写在一起
@NotEmpty(message="菜单名单不能为空")
public String getMenuname() {
return menuname;
}
(2) springMVC上传文件需要使用commons-io-2.2.jar、commons-fileupload-1.3.1.jar两个jar包
配置文件中需要加入bean代码
<!-- 设置multipartResolver才能完成文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 限制文件最大值为5M -->
<property name="maxUploadSize" value="5000000"></property>
</bean>
@RequestMapping(value = "/menuadd", method = RequestMethod.POST)
public String menuadd(@Validated Menu menu, BindingResult br,@RequestParam("attachs") MultipartFile[] attachs, HttpServletRequest req) throws IOException {// 紧跟Validated写验证结果类
System.out.println(menu.getMenuid() + " " + menu.getMenuname());
if (br.hasErrors()) {
System.out.println("验证不通过");
return "redirect:/test/menuadd";// 客户端跳转
}
for (MultipartFile attach : attachs) {
if (attach.isEmpty())
continue; System.out.println(attach.getName() + "," + attach.getOriginalFilename() + "," + attach.getContentType());
String path = req.getSession().getServletContext().getRealPath("/WEB-INF/resources/upload");
System.out.println(path);
File file = new File(path + "/" + attach.getOriginalFilename());
FileUtils.copyInputStreamToFile(attach.getInputStream(), file);
} return "redirect:/test/index2";// 客户端跳转
}
页面:
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="UTF-8"%>
<%@taglib prefix="sf" uri="http://www.springframework.org/tags/form"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body> <sf:form method="post" modelAttribute="menu" enctype="multipart/form-data">
menuid:<input type="text" name="menuid"><br/>
menuname:<input type="text" name="menuname"><br>
<sf:errors path="menuname"></sf:errors><br/>
file1:<input type="file" name="attachs"><br/>
file2:<input type="file" name="attachs"><br/>
file3:<input type="file" name="attachs"><br/>
<input type="submit" value="提交">
</sf:form> </body>
</html>
6.跳转页面可以使用 return "redirect:/test/index2"; // 客户端跳转
7. 返回json数据 加@ResponseBody 并且直接return对象
params="jj" 代表如果传了jj参数就可以映射到这个方法执行,可以根据params参数执行不同的方法
@RequestMapping(value = "/update/detail/{id}", method = RequestMethod.GET,params="jj")
@ResponseBody
public Menu show4(@PathVariable String id) {
System.out.println("show4 " + id);
Menu menu = new Menu(12l, "menuName");
return menu;
}
8. produces解决返回中文到客户端乱码的问题
/**
* 启用活动
*/
@RequestMapping(value = "use/{id}", produces = "text/html;charset=UTF-8")
@ResponseBody
public String use(@PathVariable("id") long id) {
InfoWeixinGoldEggActivity info = service.queryById(id);
if (info.getStatus()) {
return "活动已经是启用状态";
}
info.setStatus(true);
service.updateStatus(info);
return "success";
}
SpringMVC使用的几个要点的更多相关文章
- SpringMVC基本使用
springMVC是一个MVC框架,他控制着请求相应的整个流程,从请求一进入到应用服务器到相应离开,都离不开mvc框架 请求在应用服务器中 先说说请求相应在应用服务器的整个过程 DisptacherS ...
- Java Web编程技术学习要点及方向
学习编程技术要点及方向亮点: 传统学习编程技术落后,应跟著潮流,要对业务聚焦处理.要Jar, 不要War:以小为主,以简为宝,集堆而成.去繁取简 Spring Boot,明日之春(future of ...
- SpringMVC源码剖析(四)- DispatcherServlet请求转发的实现
SpringMVC完成初始化流程之后,就进入Servlet标准生命周期的第二个阶段,即“service”阶段.在“service”阶段中,每一次Http请求到来,容器都会启动一个请求线程,通过serv ...
- springmvc学习笔记--ueditor和springmvc的集成
前言: 在web开发中, 富文本的编辑器真心很重要. 有电商店铺的打理, 新闻稿/博客文章/论坛帖子的编辑等等, 这种所见即所的编辑方式, 大大方便了非技术人员从事互利网相关的工作. 因为手头有个小项 ...
- 【maven + hibernate(注解) +spring +springMVC】 使用maven搭建项目
研究,百度,查资料+好友帮助,使用MyEcplise2015工具,通过maven搭建hibernate+springMVC+spring的项目,数据库采用MySql5.5 不过使用的版本会在项目搭建过 ...
- idea使用maven搭建springmvc
最近学着搭建springmvc,写此博客记录一下 idea版本:2016.3.1maven: apache-maven-3.3.9tomcat:apache-tomcat-8.5.8 1.New Pr ...
- SpringMVC深入探究(1)——DispatcherServlet与初始化主线
在上一篇文章中,我们给出了构成SpringMVC应用程序的三要素以及三要素的设计过程.让我们来归纳一下整个设计过程中的一些要点: SpringMVC将Http处理流程抽象为一个又一个处理单元 Spri ...
- 浅谈SpringMVC(一)
一.SpringMVC引言 Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面.Spring 框架提供了构建 Web 应用程序的全功能 MV ...
- 蓝缘管理系统第二个版本号开源了。springMVC+springSecurity3.x+Mybaits3.x 系统
蓝缘管理系统第二个版本号开源了 继于 http://blog.csdn.net/mmm333zzz/article/details/16863543 版本号一.版本号二 对springMVC+spri ...
随机推荐
- linux动态时钟探索
在早期的linux内核版本的时间概念都是由周期时钟提供的.虽然比较有效,但是,对于关注能耗电量的系统上,就不能满足长时间休眠的需求,因为周期系统要求必须在一定的频率下,周期性的处于活动状态.因此,li ...
- Cocos2d-x win7 + vs2010 配置图文详解
Cocos2d-x win7 + vs2010 配置图文详解 下载最新版的cocos2d-x.打开浏览器,输入cocos2d-x.org,然后选择Download,本教程写作时最新版本为cocos2d ...
- HttpClient方式模拟http请求设置头
关于HttpClient方式模拟http请求,请求头以及其他参数的设置. 本文就暂时不给栗子了,当作简版参考手册吧. 发送请求是设置请求头:header HttpClient httpClient = ...
- 从AutoCAD和.NET开始
引自并参考Kean's blog:http://through-the-interface.typepad.com/through_the_interface/2006/07/getting_star ...
- keras 入门之 regression
本实验分三步: 1. 建立数据集 2. 建立网络并训练 3. 可视化 import numpy as np from keras.models import Sequential from keras ...
- Java中的List操作
1. 数组转List String[] arr={"1","2","3"}; List<String> list = Array ...
- YII2的增删改查
insert into table (field1,field2)values('1','2');delete from table where condition update table s ...
- ayase系列
[冒个泡]技能视觉效果の自定义 by ayase [11-09 V2.4]任务数量转换属性点的lua脚本 [335]瞎倒腾的item.dbc生成工具..
- How To: Samba4 AD PDC + Windows XP, Vista and 7
dnsmasq If you've been struggling with Samba3 domain controllers and NT4 style domains working with ...
- 转义字符(\)对JavaScript中JSON.parse的影响概述
JSON是一个提供了stringify和parse方法的内置对象,前者用于将js对象转化为符合json标准的字符串,后者将符合json标准的字符串转化为js对象,本文为大家介绍下转义字符对JSON.p ...