I have a simple spring controller which takes a @ModelAtrribute object and registers an employee. If it is a success, I forward it to a success, else an error page, and I am doing this via a boolean return value from @Service and Dao.


@RequestMapping(value = "/register", method = RequestMethod.POST)
public ModelAndView registerEmployee(@ModelAttribute LoginModel loginModel){
    LOGGER.info(" REGISTER Controller [{}] ",loginModel.toString());
    ModelAndView model = new ModelAndView();
      model.addObject("errorMessage", "Unable to register user, Please try again");
      return model;
    model.addObject("employee", loginModel);
    return model;


public boolean registerEmployeeByAdmin(LoginModel loginModel){
    LOGGER.info("Saving Employee login info ",loginModel.toString());       
    boolean registered = registerDao.registerEmployeeByAdmin(loginModel);

    return registered;   //the value returned


public boolean registerEmployeeByAdmin(LoginModel loginModel) {
    boolean registered = false;
    String addEmployeeQuery = "insert into employee_login (loginid,password_hash,user_created_date,"
            + "email) values (?,?,?,?);";
    try (Connection conn = Database.getConnection(env);
            PreparedStatement pstmt = conn.prepareStatement(addEmployeeQuery);) {

        if (conn != null) {
            pstmt.setInt(1, loginModel.getUserid());
            pstmt.setString(2, EmployeeHelper.getHashFromPassword(loginModel.getPassword_hash()));
            pstmt.setTimestamp(3, new java.sql.Timestamp(System.currentTimeMillis()));
            pstmt.setString(4, loginModel.getEmail());
            int rows = pstmt.executeUpdate();
            if (rows > 0)
                registered = true;
    } catch (SQLException | NoSuchAlgorithmException e) {
        LOGGER.error("Error while adding user [{}] with error [{}]", loginModel.toString(), e);

    return registered;

Is this the right way or can there be another way which is neat and clean?


There is another much simpler clean way.

Use ControllerAdvice and throw error from Service Layer itself. Build your common error response there. Yeah it is global exception handling.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.