Spring 3 MVC and spring security obtain the spring security username and role in the method, and bind the String to the Date type when submitting the form.
1. Get the spring security username and role in the Method
Private UserDetails getUserDetail (){
Return (UserDetails) SecurityContextHolder. getContext ()
. GetAuthentication ()
. GetPrincipal (); www.2cto.com
}
Private User getUser (){
String userName = getUserDetail (). getUsername ();
Return service. findUserByLogName (userName );
}
Private String getRoles (){
Collection <? Extends GrantedAuthority> auths = getUserDetail (). getAuthorities ();
String result = "";
Object [] ats = auths. toArray ();
For (int I = 0; I <ats. length; I ++ ){
GrantedAuthority o = (GrantedAuthority) ats [I];
Result = result + o. getAuthority ();
If (I! = Ats. length-1 ){
Result + = ",";
}
}
Return result;
}
2. Bind String to Date type when submitting form
@ InitBinder
// The parameter can also be of the ServletRequestDataBinder type.
Public void initBinder (WebDataBinder binder) throws Exception {
// Register the custom property Editor
// 1. Date
DateFormat df = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss ");
CustomDateEditor dateEditor = new CustomDateEditor (df, true );
// Indicates that if the command object has a Date attribute, type conversion is performed using this Attribute Editor.
Binder. registerCustomEditor (Date. class, dateEditor );
// Custom phone number Editor (same as [4.16.1, data type conversion)
// Binder. registerCustomEditor (PhoneNumberModel. class, new PhoneNumberEditor ());
}