我正在尝试在Spring启动和角度JS中创建一个应用程序,我们有管理员用户帐户创建和管理员可以添加多个商店,最终用户可以通过点击他们的地址找到最近的商店< / p>
问题是,管理控制台正在按预期工作,但现在管理员用户无法提交POST调用以添加商店地址
必须在映射中的任何地方犯错 - 任何帮助/指针都会真正帮助
第一个控制器 SuperAdminAppController
@Controller
@RequestMapping("/")
@SessionAttributes("roles")
public class SuperAdminAppController {
@Autowired
SuperAdminUserService superAdminUserService;
@Autowired
SuperAdminUserProfileService userProfileService;
@Autowired
MessageSource messageSource;
@Autowired
PersistentTokenBasedRememberMeServices
persistentTokenBasedRememberMeServices;
@Autowired
AuthenticationTrustResolver authenticationTrustResolver;
/**
* This method will list all existing users.
*/
@RequestMapping(value = { "/", "/list" }, method = RequestMethod.GET)
public String listUsers(ModelMap model) {
List<SuperAdminUser> users = superAdminUserService.findAllUsers();
model.addAttribute("users", users);
model.addAttribute("loggedinuser", getPrincipal());
return "userslist";
}
/**
* This method will provide the medium to add a new user.
*/
@RequestMapping(value = { "/newuser" }, method = RequestMethod.GET)
public String newUser(ModelMap model) {
SuperAdminUser user = new SuperAdminUser();
model.addAttribute("user", user);
model.addAttribute("edit", false);
model.addAttribute("loggedinuser", getPrincipal());
return "registration";
}
/**
* This method will be called on form submission, handling POST request for
* saving user in database. It also validates the user input
*/
@RequestMapping(value = { "/newuser" }, method = RequestMethod.POST)
public String saveUser(@Valid SuperAdminUser user, BindingResult result,
ModelMap model) {
if (result.hasErrors()) {
return "registration";
}
/*
* Preferred way to achieve uniqueness of field [sso] should be implementing custom @Unique annotation
* and applying it on field [sso] of Model class [User].
*
* Below mentioned peace of code [if block] is to demonstrate that you can fill custom errors outside the validation
* framework as well while still using internationalized messages.
*
*/
if(!superAdminUserService.isUserSSOUnique(user.getId(), user.getSsoId())){
FieldError ssoError =new FieldError("user","ssoId",messageSource.getMessage("non.unique.ssoId", new String[]{user.getSsoId()}, Locale.getDefault()));
result.addError(ssoError);
return "registration";
}
superAdminUserService.saveUser(user);
model.addAttribute("success", "User " + user.getFirstName() + " "+ user.getLastName() + " registered successfully");
model.addAttribute("loggedinuser", getPrincipal());
//return "success";
return "registrationsuccess";
}
/**
* This method will provide the medium to update an existing user.
*/
@RequestMapping(value = { "/edit-user-{ssoId}" }, method = RequestMethod.GET)
public String editUser(@PathVariable String ssoId, ModelMap model) {
SuperAdminUser user = superAdminUserService.findBySSO(ssoId);
model.addAttribute("user", user);
model.addAttribute("edit", true);
model.addAttribute("loggedinuser", getPrincipal());
return "registration";
}
/**
* This method will be called on form submission, handling POST request for
* updating user in database. It also validates the user input
*/
@RequestMapping(value = { "/edit-user-{ssoId}" }, method = RequestMethod.POST)
public String updateUser(@Valid SuperAdminUser user, BindingResult result,
ModelMap model, @PathVariable String ssoId) {
if (result.hasErrors()) {
return "registration";
}
/*//Uncomment below 'if block' if you WANT TO ALLOW UPDATING SSO_ID in UI which is a unique key to a User.
if(!userService.isUserSSOUnique(user.getId(), user.getSsoId())){
FieldError ssoError =new FieldError("user","ssoId",messageSource.getMessage("non.unique.ssoId", new String[]{user.getSsoId()}, Locale.getDefault()));
result.addError(ssoError);
return "registration";
}*/
superAdminUserService.updateUser(user);
model.addAttribute("success", "User " + user.getFirstName() + " "+ user.getLastName() + " updated successfully");
model.addAttribute("loggedinuser", getPrincipal());
return "registrationsuccess";
}
/**
* This method will delete an user by it's SSOID value.
*/
@RequestMapping(value = { "/delete-user-{ssoId}" }, method = RequestMethod.GET)
public String deleteUser(@PathVariable String ssoId) {
superAdminUserService.deleteUserBySSO(ssoId);
return "redirect:/list";
}
/**
* This method will provide UserProfile list to views
*/
@ModelAttribute("roles")
public List<SuperAdminUserProfile> initializeProfiles() {
return userProfileService.findAll();
}
/**
* This method handles Access-Denied redirect.
*/
@RequestMapping(value = "/Access_Denied", method = RequestMethod.GET)
public String accessDeniedPage(ModelMap model) {
model.addAttribute("loggedinuser", getPrincipal());
return "accessDenied";
}
/**
* This method handles login GET requests.
* If users is already logged-in and tries to goto login page again, will be redirected to list page.
*/
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginPage() {
if (isCurrentAuthenticationAnonymous()) {
return "login";
} else {
return "redirect:/list";
}
}
/**
* This method handles logout requests.
* Toggle the handlers if you are RememberMe functionality is useless in your app.
*/
@RequestMapping(value="/logout", method = RequestMethod.GET)
public String logoutPage (HttpServletRequest request, HttpServletResponse response){
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null){
//new SecurityContextLogoutHandler().logout(request, response, auth);
persistentTokenBasedRememberMeServices.logout(request, response, auth);
SecurityContextHolder.getContext().setAuthentication(null);
}
return "redirect:/login?logout";
}
/**
* This method returns the principal[user-name] of logged-in user.
*/
private String getPrincipal(){
String userName = null;
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
userName = ((UserDetails)principal).getUsername();
} else {
userName = principal.toString();
}
return userName;
}
/**
* This method returns true if users is already authenticated [logged-in], else false.
*/
private boolean isCurrentAuthenticationAnonymous() {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authenticationTrustResolver.isAnonymous(authentication);
}
}
第二个控制器 - RestApiController
@RestController
@RequestMapping("/api")
public class RestApiController {
public static final Logger logger =
LoggerFactory.getLogger(RestApiController.class);
@Autowired
UserService userService; // Service which will do all data
// retrieval/manipulation work
// -------------------Retrieve All
// Users---------------------------------------------
@RequestMapping(value = "/user/", method = RequestMethod.GET)
public ResponseEntity<List<User>> listAllUsers() {
List<User> users = userService.findAllUsers();
if (users.isEmpty()) {
return new ResponseEntity(HttpStatus.NO_CONTENT);
// You many decide to return HttpStatus.NOT_FOUND
}
return new ResponseEntity<List<User>>(users, HttpStatus.OK);
}
// -------------------Retrieve Single
// User------------------------------------------
@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
public ResponseEntity<?> getUser(@PathVariable("id") long id) {
logger.info("Fetching User with id {}", id);
User user = userService.findById(id);
if (user == null) {
logger.error("User with id {} not found.", id);
return new ResponseEntity(new CustomErrorType("User with id " + id +
" not found"), HttpStatus.NOT_FOUND);
}
return new ResponseEntity<User>(user, HttpStatus.OK);
}
// -------------------Create a
// User-------------------------------------------
/*@RequestMapping(value = "/{pathURL}", method = RequestMethod.POST)
public String post(@ModelAttribute("AppUser") AppUser appUser, ModelMap
modelMap,@PathVariable String pathURL)
@RequestMapping(value = "/{pathURL}", method = RequestMethod.GET)
public String get(ModelMap modelMap,@PathVariable String pathURL)*/
@RequestMapping(value = "/user/", method = RequestMethod.POST)
public ResponseEntity<?> createUser(@RequestBody User user,
UriComponentsBuilder ucBuilder) {
logger.info("Creating User : {}", user);
if (userService.isUserExist(user)) {
logger.error("Unable to create. A User with name {} already exist",
user.getName());
return new ResponseEntity(
new CustomErrorType("Unable to create. A User with name " +
user.getName() + " already exist."),
HttpStatus.CONFLICT);
}
userService.saveUser(user);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/api/user/{id}").
buildAndExpand(user.getId()).toUri());
return new ResponseEntity<String>(headers, HttpStatus.CREATED);
}
// ------------------- Update a User
// ------------------------------------------------
@RequestMapping(value = "/user/{id}", method = RequestMethod.PUT)
public ResponseEntity<?> updateUser(@PathVariable("id") long id, @RequestBody User user) {
logger.info("Updating User with id {}", id);
User currentUser = userService.findById(id);
if (currentUser == null) {
logger.error("Unable to update. User with id {} not found.", id);
return new ResponseEntity(new CustomErrorType("Unable to upate. User with id " + id + " not found."),
HttpStatus.NOT_FOUND);
}
currentUser.setName(user.getName());
currentUser.setPnumber(user.getPnumber());
currentUser.setAddress(user.getAddress());
currentUser.setLat(getLat(user.getAddress().toString()));
currentUser.setLon(getLon(user.getAddress().toString()));
currentUser.setWork_price(user.getWork_price());
currentUser.setLocation(user.getLocation());
currentUser.setComment(user.getComment());
currentUser.setPreference(user.getPreference());
userService.updateUser(currentUser);
return new ResponseEntity<User>(currentUser, HttpStatus.OK);
}
// ------------------- Delete a
// User-----------------------------------------
@RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
public ResponseEntity<?> deleteUser(@PathVariable("id") long id) {
logger.info("Fetching & Deleting User with id {}", id);
User user = userService.findById(id);
if (user == null) {
logger.error("Unable to delete. User with id {} not found.", id);
return new ResponseEntity(new CustomErrorType("Unable to delete. User with id " + id + " not found."),
HttpStatus.NOT_FOUND);
}
userService.deleteUserById(id);
return new ResponseEntity<User>(HttpStatus.NO_CONTENT);
}
// ------------------- Delete All Users-----------------------------
@RequestMapping(value = "/user/", method = RequestMethod.DELETE)
public ResponseEntity<User> deleteAllUsers() {
logger.info("Deleting All Users");
userService.deleteAllUsers();
return new ResponseEntity<User>(HttpStatus.NO_CONTENT);
}
public String getLat(String add){
Location loc = new Location();
try {
return loc.getLat(add);
} catch (Exception e) {
}
return null;
}
public String getLon(String add){
Location loc = new Location();
try {
return loc.getLon(add);
} catch (Exception e) {
}
return null;
}
}
我的日志
2017-08-25 15:17:36.393 INFO 10268 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2017-08-25 15:17:37.941 INFO 10268 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/index]}" onto java.lang.String com.sezlon.maintenance.services.global.controller.AppController.home(org.springframework.ui.ModelMap)
2017-08-25 15:17:37.943 INFO 10268 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/partials/{page}]}" onto java.lang.String com.sezlon.maintenance.services.global.controller.AppController.partialHandler(java.lang.String)
2017-08-25 15:17:37.954 INFO 10268 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/api/user/{id}],methods=[DELETE]}" onto public org.springframework.http.ResponseEntity<?> com.sezlon.maintenance.services.global.controller.RestApiController.deleteUser(long)
2017-08-25 15:17:37.955 INFO 10268 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/api/user/],methods=[GET]}" onto public org.springframework.http.ResponseEntity<java.util.List<com.sezlon.maintenance.services.global.model.User>> com.sezlon.maintenance.services.global.controller.RestApiController.listAllUsers()
2017-08-25 15:17:37.955 INFO 10268 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/api/user/],methods=[DELETE]}" onto public org.springframework.http.ResponseEntity<com.sezlon.maintenance.services.global.model.User> com.sezlon.maintenance.services.global.controller.RestApiController.deleteAllUsers()
2017-08-25 15:17:37.955 INFO 10268 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/api/user/{id}],methods=[GET]}" onto public org.springframework.http.ResponseEntity<?> com.sezlon.maintenance.services.global.controller.RestApiController.getUser(long)
2017-08-25 15:17:37.955 INFO 10268 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/api/user/],methods=[POST]}" onto public org.springframework.http.ResponseEntity<?> com.sezlon.maintenance.services.global.controller.RestApiController.createUser(com.sezlon.maintenance.services.global.model.User,org.springframework.web.util.UriComponentsBuilder)
2017-08-25 15:17:37.955 INFO 10268 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/api/user/{id}],methods=[PUT]}" onto public org.springframework.http.ResponseEntity<?> com.sezlon.maintenance.services.global.controller.RestApiController.updateUser(long,com.sezlon.maintenance.services.global.model.User)
2017-08-25 15:17:37.961 INFO 10268 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/delete-user-{ssoId}],methods=[GET]}" onto public java.lang.String com.sezlon.maintenance.services.global.controller.SuperAdminAppController.deleteUser(java.lang.String)
2017-08-25 15:17:37.961 INFO 10268 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/newuser],methods=[POST]}" onto public java.lang.String com.sezlon.maintenance.services.global.controller.SuperAdminAppController.saveUser(com.sezlon.maintenance.services.global.admin.model.SuperAdminUser,org.springframework.validation.BindingResult,org.springframework.ui.ModelMap)
2017-08-25 15:17:37.962 INFO 10268 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/edit-user-{ssoId}],methods=[POST]}" onto public java.lang.String com.sezlon.maintenance.services.global.controller.SuperAdminAppController.updateUser(com.sezlon.maintenance.services.global.admin.model.SuperAdminUser,org.springframework.validation.BindingResult,org.springframework.ui.ModelMap,java.lang.String)
2017-08-25 15:17:37.962 INFO 10268 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/edit-user-{ssoId}],methods=[GET]}" onto public java.lang.String com.sezlon.maintenance.services.global.controller.SuperAdminAppController.editUser(java.lang.String,org.springframework.ui.ModelMap)
2017-08-25 15:17:37.962 INFO 10268 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/newuser],methods=[GET]}" onto public java.lang.String com.sezlon.maintenance.services.global.controller.SuperAdminAppController.newUser(org.springframework.ui.ModelMap)
2017-08-25 15:17:37.962 INFO 10268 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/Access_Denied],methods=[GET]}" onto public java.lang.String com.sezlon.maintenance.services.global.controller.SuperAdminAppController.accessDeniedPage(org.springframework.ui.ModelMap)
2017-08-25 15:17:37.962 INFO 10268 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/ || /list],methods=[GET]}" onto public java.lang.String com.sezlon.maintenance.services.global.controller.SuperAdminAppController.listUsers(org.springframework.ui.ModelMap)
2017-08-25 15:17:37.962 INFO 10268 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/login],methods=[GET]}" onto public java.lang.String com.sezlon.maintenance.services.global.controller.SuperAdminAppController.loginPage()
2017-08-25 15:17:37.962 INFO 10268 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/logout],methods=[GET]}" onto public java.lang.String com.sezlon.maintenance.services.global.controller.SuperAdminAppController.logoutPage(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-08-25 15:17:37.967 INFO 10268 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-08-25 15:17:37.968 INFO 10268 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-08-25 15:17:38.019 INFO 10268 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/static/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-08-25 15:17:38.269 INFO 10268 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@244038d0: startup date [Fri Aug 25 15:17:22 PDT 2017]; root of context hierarchy