Spring a un puissant intégré StringUtils classe
Avis le tableau suivant contenant un ensemble de
String [] idArray = new String [] {"0", "1", "2", "0", "5", "2"}
de id et que vous voulez supprimer les références en double. Just do it
idArray = StringUtils.removeDuplicateStrings(idArray);
Maintenant, idArray contiendra {"0", "1", "2", "5"}.
Et bien plus encore.
Est-il possible d'utiliser une classe Controller sans les déclarer dans le fichier de contexte de l'application Web?
Oui, il suffit de mettre @component dans sa déclaration (@Controller ne fonctionne pas comme prévu)
package br.com.spring.view.controller
@Component
public class PlayerController extends MultiActionController {
private Service service;
@Autowired
public PlayerController(InternalPathMethodNameResolver ipmnr, Service service) {
this.service = service;
setMethodNameResolver(ipmnr);
}
// mapped to /player/add
public ModelAndView add(...) {}
// mapped to /player/remove
public ModelAndView remove(...) {}
// mapped to /player/list
public ModelAndView list(...) {}
}
donc dans le fichier de contexte d'application web mis les éléments suivants
<beans ...>
<context:component-scan base-package="br.com.spring.view"/>
<context:annotation-config/>
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
<property name="order" value="0"/>
<property name="caseSensitive" value="true"/>
</bean>
<bean class="org.springframework.web.servlet.mvc.multiaction.InternalPathMethodNameResolver"/>
</beans>
Rien d'autre
Validation dans les formes dynamiques?
Utilisez les éléments suivants
public class Team {
private List<Player> playerList;
}
donc dans l'équipe validateur mis
@Component
public class TeamValidator implements Validator {
private PlayerValidator playerValidator;
@Autowired
public TeamValidator(PlayerValidator playerValidator) {
this.playerValidator = playerValidator;
}
public boolean supports(Class clazz) {
return clazz.isAssignableFrom(Team.class);
}
public void validate(Object command, Errors errors) {
Team team = (Team) command;
// do Team validation
int index = 0;
for(Player player: team.getPlayerList()) {
// Notice code just bellow
errors.pushNestedPath("playerList[" + index++ + "]");
ValidationUtils.invokeValidator(playerValidator, player, errors);
errors.popNestedPath();
}
}
}
héritage dans les formulaires Web?
Utilisez ServlerRequestDataBinder avec le formulaire caché drapeau
public class Command {
private Parent parent;
}
public class Child extends Parent { ... }
public class AnotherChild extends Parent { ... }
Et dans votre contrôleur procédez comme suit
public class MyController extends MultiActionController {
public ModelAndView action(HttpServletRequest request, HttpServletResponse response, Object command) {
Command command = (Command) command;
// hidden form flag
String parentChildType = ServletRequestUtils.getRequiredStringParameter(request, "parentChildType");
// getApplicationContext().getBean(parentChildType) retrieves a Parent object from a application context file
ServletRequestDataBinder binder =
new ServletRequestDataBinder(getApplicationContext().getBean(parentChildType));
// populates Parent child object
binder.bind(request);
command.setParent((Parent) binder.getTarget());
}
Spring a une classe intégrée du scanner ClassPathScanningCandidateComponentProvider. Vous pouvez l'utiliser pour trouver des annotations, par exemple.
ClassPathScanningCandidateComponentProvider scanner =
new ClassPathScanningCandidateComponentProvider(<DO_YOU_WANT_TO_USE_DEFAULT_FILTER>);
scanner.addIncludeFilter(new AnnotationTypeFilter(<TYPE_YOUR_ANNOTATION_HERE>.class));
for (BeanDefinition bd : scanner.findCandidateComponents(<TYPE_YOUR_BASE_PACKAGE_HERE>))
System.out.println(bd.getBeanClassName());
Spring a une classe org.springframework.util.FileCopyUtils utile. Vous pouvez copier un fichier téléchargé à l'aide
public ModelAndView action(...) throws Exception {
Command command = (Command) command;
MultiPartFile uploadedFile = command.getFile();
FileCopyUtils.copy(uploadedFile.getBytes(), new File("destination"));
Si vous utilisez un contrôleur à base d'annotation (Spring 2.5+) OU MVC contrôleur de printemps simple, vous pouvez utiliser un WebBindingInitializer pour enregistrer les éditeurs de propriétés globales. Quelque chose comme
public class GlobalBindingInitializer implements WebBindingInitializer {
public void initBinder(WebDataBinder binder, WebRequest request) {
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("dd/MM/yyyy", true);
}
}
Donc, dans votre application web fichier de contexte, déclare
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="webBindingInitializer">
<bean class="GlobalBindingInitializer"/>
</property>
</bean>
De cette façon, un contrôleur à base d'annotation peut utiliser un éditeur de propriété déclaré dans GlobalBindingInitializer.
Et ainsi de suite ...
choses utiles, ce. Le code qui exécute le travail est 'SimpleApplicationEventMulticaster', qui peut éventuellement utiliser un pool de threads pour distribuer les événements de manière asynchrone. Pour ma part, je m'ennuie à écrire un code pour le faire. – skaffman