path =“userRoles”是多选字段。其中填充了控制器中的“initializeRoles()”方法。我有一个转换器也将角色转换为UserRoles对象。当我在选择所有角色后提交表单时,我只得到第一个选择的一个到转换器类,如下所示。为什么我没有从JSP获取String []?
Converter类中的输出:
1
的字符串
JSP代码:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page isELIgnored="false" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>User Create Form</title>
<link href="<c:url value='/static/css/bootstrap.css' />" rel="stylesheet"></link>
<link href="<c:url value='/static/css/app.css' />" rel="stylesheet"></link>
</head>
<body>
<div class="generic-container">
<%@include file="authheader.jsp" %>
<div class="well lead">User Create Form</div>
<form:form method="POST" modelAttribute="user" class="form-horizontal">
<form:input type="hidden" path="userid" id="userid"/>
<div class="row">
<div class="form-group col-md-12">
<label class="col-md-3 control-lable" for="firstName">First Name</label>
<div class="col-md-7">
<form:input type="text" path="firstName" id="firstName" class="form-control input-sm"/>
<div class="has-error">
<form:errors path="firstName" class="help-inline"/>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="col-md-3 control-lable" for="middleName">Middle Name</label>
<div class="col-md-7">
<form:input type="text" path="middleName" id="middleName" class="form-control input-sm" />
<div class="has-error">
<form:errors path="middleName" class="help-inline"/>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="col-md-3 control-lable" for="lastName">Last Name</label>
<div class="col-md-7">
<form:input type="text" path="lastName" id="lastName" class="form-control input-sm" />
<div class="has-error">
<form:errors path="lastName" class="help-inline"/>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="col-md-3 control-lable" for="username">Username</label>
<div class="col-md-7">
<c:choose>
<c:when test="${edit}">
<form:input type="text" path="username" id="username" class="form-control input-sm" disabled="true"/>
</c:when>
<c:otherwise>
<form:input type="text" path="username" id="username" class="form-control input-sm" />
<div class="has-error">
<form:errors path="username" class="help-inline"/>
</div>
</c:otherwise>
</c:choose>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="col-md-3 control-lable" for="password">Password</label>
<div class="col-md-7">
<form:input type="password" path="password" id="password" class="form-control input-sm" />
<div class="has-error">
<form:errors path="password" class="help-inline"/>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="col-md-3 control-lable" for="email">Email</label>
<div class="col-md-7">
<form:input type="text" path="email" id="email" class="form-control input-sm" />
<div class="has-error">
<form:errors path="email" class="help-inline"/>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="col-md-3 control-lable" for="userRoles">Roles</label>
<div class="col-md-7">
<form:select path="userRoles" items="${roles}" multiple="true" itemValue="roleid" itemLabel="roleName" class="form-control input-sm" />
<div class="has-error">
<form:errors path="userRoles" class="help-inline"/>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-actions floatRight">
<c:choose>
<c:when test="${edit}">
<input type="submit" value="Update" class="btn btn-primary btn-sm"/> or <a href="<c:url value='/list' />">Cancel</a>
</c:when>
<c:otherwise>
<input type="submit" value="Register" class="btn btn-primary btn-sm"/> or <a href="<c:url value='/list' />">Cancel</a>
</c:otherwise>
</c:choose>
</div>
</div>
</form:form>
</div>
</body>
</html>
控制器代码:
package com.rsa.tools.springmvc.web.controller;
import java.util.List;
import java.util.Locale;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.rsa.tools.springmvc.model.User;
import com.rsa.tools.springmvc.model.UserRoles;
import com.rsa.tools.springmvc.service.UserManagementService;
@Controller
@RequestMapping("/users")
public class UserController {
@Autowired
UserManagementService umService;
@Autowired
MessageSource messageSource;
@RequestMapping(value="/list", method=RequestMethod.GET)
public String listUsers(ModelMap model) {
List<User> users = umService.getAllUsersOrderedByUsername();
model.addAttribute("users", users);
return "userslist";
}
@RequestMapping(value = { "/newuser" }, method = RequestMethod.GET)
public String newUser(ModelMap model) {
User user = new User();
model.addAttribute("user", user);
model.addAttribute("edit", false);
return "registration";
}
@RequestMapping(value = { "/newuser" }, method = RequestMethod.POST)
public String saveUser(@Valid User user, BindingResult result, ModelMap model) {
System.out.println(user);
System.out.println(result.getAllErrors());
if (result.hasErrors()) {
return "registration";
}
if(!umService.isUsernameUnique(user.getUsername())) {
FieldError usernameError = new FieldError("user","username",messageSource.getMessage("non.unique.username", new String[]{user.getUsername()}, Locale.getDefault()));
result.addError(usernameError);
return "registration";
}
umService.addUser(user);
model.addAttribute("success", "User " + user.getFirstName() + " "+ user.getLastName() + " registered successfully");
//return "success";
return "registrationsuccess";
}
@RequestMapping(value = { "/edit-user-{username}" }, method = RequestMethod.GET)
public String editUser(@PathVariable String username, ModelMap model) {
User user = umService.findByUsername(username);
model.addAttribute("user", user);
model.addAttribute("edit", true);
return "registration";
}
@RequestMapping(value = { "/edit-user-{username}" }, method = RequestMethod.POST)
public String updateUser(@Valid User user, BindingResult result, ModelMap model, @PathVariable String username) {
if (result.hasErrors()) {
return "registration";
}
umService.editUser(user);
model.addAttribute("success", "User " + user.getFirstName() + " "+ user.getLastName() + " updated successfully");
return "registrationsuccess";
}
@RequestMapping(value = { "/delete-user-{username}" }, method = RequestMethod.GET)
public String deleteUser(@PathVariable String username) {
umService.deleteUser(username);
return "redirect:/list";
}
@ModelAttribute("roles")
public List<UserRoles> initializeRoles() {
return umService.getAllUserRoles();
}
}
转换器代码:
package com.rsa.tools.springmvc.configuration.web.converter;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import com.rsa.tools.springmvc.dao.UserDao;
import com.rsa.tools.springmvc.model.UserRoles;
@Component
public class UserRolesConverter implements Converter<Object, List<UserRoles>> {
@Autowired
UserDao userDao;
@Override
public List<UserRoles> convert(Object roles) {
List<UserRoles> userRoles = new ArrayList<UserRoles>();
System.out.println(roles);
if (roles instanceof String) {
System.out.println("string");
String sRoles = (String)roles;
UserRoles ur = userDao.findByRoleid(Long.parseLong(sRoles));
userRoles.add(ur);
} else if (roles instanceof String[]) {
System.out.println("string[]");
for (String role : (String[])roles) {
UserRoles ur = userDao.findByRoleid(Long.parseLong(role));
userRoles.add(ur);
}
}
return userRoles;
}
}
网络配置:
package com.rsa.tools.springmvc.configuration.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.format.FormatterRegistry;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import com.rsa.tools.springmvc.configuration.web.converter.UserRolesConverter;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.rsa.tools.springmvc.web.controller", "com.rsa.tools.springmvc.configuration.web.converter" })
public class ApplicationWebConfiguration extends WebMvcConfigurerAdapter {
@Autowired
UserRolesConverter userRolesConverter;
@Bean
public InternalResourceViewResolver resolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setViewClass(JstlView.class);
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource source = new ResourceBundleMessageSource();
source.setBasename("messages");
return source;
}
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(userRolesConverter);
}
@Override
public Validator getValidator() {
LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
validator.setValidationMessageSource(messageSource());
return validator;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
}
}
答案 0 :(得分:0)
为String []添加了一个转换器类。然后我开始获取在UI中选择的多个值。为什么我要编写两个Converter类。有没有办法将两个类合并。
drop view if exists sometable_with_value_units;
create view sometable_with_value_units as
select id,
SUBSTRING_INDEX(SUBSTRING_INDEX(Length, ' ', 1), ' ', -1) as value,
SUBSTRING_INDEX(SUBSTRING_INDEX(Length, ' ', 2), ' ', -1) as units
from sometable;
select id,
case units
when 'yards' then value * 3
when 'yard' then value * 3
when 'feet' then value
when 'foot' then value
end as feet
from sometable_with_value_units;