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

SpringMVC使用的几个要点

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