最近使用Spring MVC的多,发下在Spring MVC下如何方便的使用下拉列表吧,其实还有其他好多功能,不过我就不一一说明了,大家到直接查看官方手册就能明白:
下面是我的Controller类:
然后页面代码:
完整例子,看附件,使用Maven管理依赖
下面是我的Controller类:
package com.vito16.mvc1.controller;
import java.util.ArrayList;
import java.util.List;
import javax.validation.Valid;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.vito16.mvc1.model.User;
/**
* @author Vito16 zhouwentao16@gmail.com
* @date 2013-7-8
*
*/
@Controller
@RequestMapping("/user")
public class UserController {
private static final Log logger = LogFactory.getLog(UserController.class);
@RequestMapping(method = RequestMethod.GET)
public String index() {
return "user/index";
}
@RequestMapping("/list")
public ModelAndView listUser(ModelAndView model) {
List<User> userList = new ArrayList<User>();
User user1 = new User();
user1.setUsername("测试用户1");
user1.setPassword("123");
user1.setId(1);
userList.add(user1);
User user2 = new User();
user2.setUsername("测试用户2");
user2.setPassword("123");
user2.setId(2);
userList.add(user2);
User user3 = new User();
user3.setUsername("测试用户3");
user3.setPassword("12333");
user3.setId(3);
userList.add(user3);
User user = new User(2,null,null);
model.addObject(userList).addObject(user);
return model;
}
@RequestMapping("/new")
public User newUser() {
User user = new User();
user.setUsername("请填写用户名");
user.setPassword("");
return user;
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String add(@Valid User user, BindingResult result) {
if (result.hasErrors()) {
logger.error("Java Bean 没有通过验证");
for (ObjectError or : result.getAllErrors()) {
logger.warn("验证类型:" + or.getCode() + " \t错误消息:"
+ or.getDefaultMessage());
}
return "user/new";
}
logger.info("后台成功添加用户:" + user);
return "redirect:/user";
}
}
然后页面代码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%
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>
用户列表
<form:select path="user.id" items="${userList}" itemLabel="username"
itemValue="id"></form:select>
</body>
</html>
完整例子,看附件,使用Maven管理依赖