根據使用者型別跳轉頁面(基於mybatis)

staticleoWay發表於2020-12-04

基於mybatis,springboot,mysql實現根據使用者型別進行跳轉

通過獲取id的方式匹配角色名稱實現跳轉
注:這個功能使用spring-security或shiro其實更加容易實現

- 資料庫
設計兩個表,約束role表id為外來鍵,即account表的role_id
account表:
account表
role表:
role表

  • mapper層
@Repository
@Mapper
@Component
public interface AccountMapper {
    @Select("select role from role where id=#{id}")
    public String getAccountRoleById(@Param("id") Integer id);
;
}
  • service層
@Service
public class AccountService {

    @Autowired
    public AccountMapper accountMapper;
    public String getUserRoleById(Integer id){
        return accountMapper.getAccountRoleById(id);
    }
}
  • controller層
    這裡的pagejump是登入頁面跳轉的操作,若實現需在實際的login(登入)的controller內加上 return “pagejump”.
    此外這塊程式碼實際上在我之前的登入檢測寫過,附上loginController
@Controller
public class LoginController {
    @Autowired
    public LoginService loginService;
    @RequestMapping(value = "login",method = {RequestMethod.POST,RequestMethod.GET})
    public String login(){
        return "login";
    }
    @RequestMapping(value = "/loginPage",method = {RequestMethod.POST,RequestMethod.GET})
    public String login(HttpServletRequest request, HttpSession session,Map<String,Object> map,Model model)
    {
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        Account tname = loginService.login(name, password);
        session.setAttribute("tname", tname);
        if (tname == null) {
            map.put("msg", "請輸入正確的賬號和密碼");
            return "login";
        } else
        return "redirect:/pagejump";
    }

    }
@Controller

public class PageJumpController {
    @Autowired
   AccountService accountService;
    @RequestMapping(value = "/pagejump", method = {RequestMethod.POST,RequestMethod.GET})
    public String pagejump(HttpServletRequest request,HttpSession session){
        Account object = (Account) session.getAttribute("tname");
        Account loginUser = object;
        Integer id = loginUser.getRole_id();
        String role = accountService.getUserRoleById(id);
        {
            if (role.equals("sysmanager")) {
                return "redirect:/system";
            }
            if (role.equals("newsmanager")) {
                return "redirect:/news";
            }
            return "redirect:/index";
        }
    }

}
  • 實體層就不進行贅述了,生成相應getter,setter方法即可

寫在最後:對於登入驗證,許可權管理這些使用spring-security還是較為實用的,當然此方法也可以實現簡單的role角色判斷進入不同頁面,作為初學者的手寫思考。有什麼不對的地方希望大佬多多指點。

相關文章