com.ruoyi.common.utils.ServletUtils Java Examples

The following examples show how to use com.ruoyi.common.utils.ServletUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RepeatSubmitInterceptor.java    From RuoYi-Vue with MIT License 6 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
{
    if (handler instanceof HandlerMethod)
    {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class);
        if (annotation != null)
        {
            if (this.isRepeatSubmit(request))
            {
                AjaxResult ajaxResult = AjaxResult.error("不允许重复提交,请稍后再试");
                ServletUtils.renderString(response, JSONObject.toJSONString(ajaxResult));
                return false;
            }
        }
        return true;
    }
    else
    {
        return super.preHandle(request, response, handler);
    }
}
 
Example #2
Source File: DataScopeAspect.java    From RuoYi-Vue with MIT License 6 votes vote down vote up
protected void handleDataScope(final JoinPoint joinPoint)
{
    // 获得注解
    DataScope controllerDataScope = getAnnotationLog(joinPoint);
    if (controllerDataScope == null)
    {
        return;
    }
    // 获取当前的用户
    LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
    SysUser currentUser = loginUser.getUser();
    if (currentUser != null)
    {
        // 如果是超级管理员,则不过滤数据
        if (!currentUser.isAdmin())
        {
            dataScopeFilter(joinPoint, currentUser, controllerDataScope.deptAlias(),
                    controllerDataScope.userAlias());
        }
    }
}
 
Example #3
Source File: LogoutSuccessHandlerImpl.java    From RuoYi-Vue with MIT License 6 votes vote down vote up
/**
 * 退出处理
 * 
 * @return
 */
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
        throws IOException, ServletException
{
    LoginUser loginUser = tokenService.getLoginUser(request);
    if (StringUtils.isNotNull(loginUser))
    {
        String userName = loginUser.getUsername();
        // 删除用户缓存记录
        tokenService.delLoginUser(loginUser.getToken());
        // 记录用户退出日志
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, "退出成功"));
    }
    ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(HttpStatus.SUCCESS, "退出成功")));
}
 
Example #4
Source File: SysLoginController.java    From RuoYi-Vue with MIT License 6 votes vote down vote up
/**
 * 获取用户信息
 * 
 * @return 用户信息
 */
@GetMapping("getInfo")
public AjaxResult getInfo()
{
    LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
    SysUser user = loginUser.getUser();
    // 角色集合
    Set<String> roles = permissionService.getRolePermission(user);
    // 权限集合
    Set<String> permissions = permissionService.getMenuPermission(user);
    AjaxResult ajax = AjaxResult.success();
    ajax.put("user", user);
    ajax.put("roles", roles);
    ajax.put("permissions", permissions);
    return ajax;
}
 
Example #5
Source File: SysProfileController.java    From RuoYi-Vue with MIT License 6 votes vote down vote up
/**
 * 重置密码
 */
@Log(title = "个人信息", businessType = BusinessType.UPDATE)
@PutMapping("/updatePwd")
public AjaxResult updatePwd(String oldPassword, String newPassword)
{
    LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
    String userName = loginUser.getUsername();
    String password = loginUser.getPassword();
    if (!SecurityUtils.matchesPassword(oldPassword, password))
    {
        return AjaxResult.error("修改密码失败,旧密码错误");
    }
    if (SecurityUtils.matchesPassword(newPassword, password))
    {
        return AjaxResult.error("新密码不能与旧密码相同");
    }
    if (userService.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword)) > 0)
    {
        // 更新缓存用户密码
        loginUser.getUser().setPassword(SecurityUtils.encryptPassword(newPassword));
        tokenService.setLoginUser(loginUser);
        return AjaxResult.success();
    }
    return AjaxResult.error("修改密码异常,请联系管理员");
}
 
Example #6
Source File: SysProfileController.java    From RuoYi-Vue with MIT License 6 votes vote down vote up
/**
 * 修改用户
 */
@Log(title = "个人信息", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult updateProfile(@RequestBody SysUser user)
{
    if (userService.updateUserProfile(user) > 0)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 更新缓存用户信息
        loginUser.getUser().setNickName(user.getNickName());
        loginUser.getUser().setPhonenumber(user.getPhonenumber());
        loginUser.getUser().setEmail(user.getEmail());
        loginUser.getUser().setSex(user.getSex());
        tokenService.setLoginUser(loginUser);
        return AjaxResult.success();
    }
    return AjaxResult.error("修改个人信息异常,请联系管理员");
}
 
Example #7
Source File: PermissionService.java    From RuoYi-Vue with MIT License 6 votes vote down vote up
/**
 * 验证用户是否具有以下任意一个权限
 *
 * @param permissions 以 PERMISSION_NAMES_DELIMETER 为分隔符的权限列表
 * @return 用户是否具有以下任意一个权限
 */
public boolean hasAnyPermi(String permissions)
{
    if (StringUtils.isEmpty(permissions))
    {
        return false;
    }
    LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
    if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getPermissions()))
    {
        return false;
    }
    Set<String> authorities = loginUser.getPermissions();
    for (String permission : permissions.split(PERMISSION_DELIMETER))
    {
        if (permission != null && hasPermissions(authorities, permission))
        {
            return true;
        }
    }
    return false;
}
 
Example #8
Source File: PermissionService.java    From RuoYi-Vue with MIT License 6 votes vote down vote up
/**
 * 判断用户是否拥有某个角色
 * 
 * @param role 角色字符串
 * @return 用户是否具备某角色
 */
public boolean hasRole(String role)
{
    if (StringUtils.isEmpty(role))
    {
        return false;
    }
    LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
    if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getUser().getRoles()))
    {
        return false;
    }
    for (SysRole sysRole : loginUser.getUser().getRoles())
    {
        String roleKey = sysRole.getRoleKey();
        if (SUPER_ADMIN.contains(roleKey) || roleKey.contains(StringUtils.trim(role)))
        {
            return true;
        }
    }
    return false;
}
 
Example #9
Source File: PermissionService.java    From RuoYi-Vue with MIT License 6 votes vote down vote up
/**
 * 验证用户是否具有以下任意一个角色
 *
 * @param roles 以 ROLE_NAMES_DELIMETER 为分隔符的角色列表
 * @return 用户是否具有以下任意一个角色
 */
public boolean hasAnyRoles(String roles)
{
    if (StringUtils.isEmpty(roles))
    {
        return false;
    }
    LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
    if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getUser().getRoles()))
    {
        return false;
    }
    for (String role : roles.split(ROLE_DELIMETER))
    {
        if (hasRole(role))
        {
            return true;
        }
    }
    return false;
}
 
Example #10
Source File: OnlineSessionFactory.java    From supplierShop with MIT License 6 votes vote down vote up
@Override
public Session createSession(SessionContext initData)
{
    OnlineSession session = new OnlineSession();
    if (initData != null && initData instanceof WebSessionContext)
    {
        WebSessionContext sessionContext = (WebSessionContext) initData;
        HttpServletRequest request = (HttpServletRequest) sessionContext.getServletRequest();
        if (request != null)
        {
            UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
            // 获取客户端操作系统
            String os = userAgent.getOperatingSystem().getName();
            // 获取客户端浏览器
            String browser = userAgent.getBrowser().getName();
            session.setHost(IpUtils.getIpAddr(request));
            session.setBrowser(browser);
            session.setOs(os);
        }
    }
    return session;
}
 
Example #11
Source File: OnlineSessionFactory.java    From RuoYi with Apache License 2.0 6 votes vote down vote up
@Override
public Session createSession(SessionContext initData) {
    OnlineSession session = new OnlineSession();
    if (initData instanceof WebSessionContext) {
        WebSessionContext sessionContext = (WebSessionContext) initData;
        HttpServletRequest request = (HttpServletRequest) sessionContext.getServletRequest();
        if (request != null) {
            UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
            // 获取客户端操作系统
            String os = userAgent.getOperatingSystem().getName();
            // 获取客户端浏览器
            String browser = userAgent.getBrowser().getName();
            session.setHost(IpUtils.getIpAddr(request));
            session.setBrowser(browser);
            session.setOs(os);
        }
    }
    return session;
}
 
Example #12
Source File: RepeatSubmitInterceptor.java    From supplierShop with MIT License 6 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
{
    if (handler instanceof HandlerMethod)
    {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class);
        if (annotation != null)
        {
            if (this.isRepeatSubmit(request))
            {
                AjaxResult ajaxResult = AjaxResult.error("不允许重复提交,请稍后再试");
                ServletUtils.renderString(response, JSON.marshal(ajaxResult));
                return false;
            }
        }
        return true;
    }
    else
    {
        return super.preHandle(request, response, handler);
    }
}
 
Example #13
Source File: GlobalExceptionHandler.java    From supplierShop with MIT License 6 votes vote down vote up
/**
 * 业务异常
 */
@ExceptionHandler(BusinessException.class)
public Object businessException(HttpServletRequest request, BusinessException e)
{
    log.error(e.getMessage(), e);
    if (ServletUtils.isAjaxRequest(request))
    {
        return AjaxResult.error(e.getMessage());
    }
    else
    {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("errorMessage", e.getMessage());
        modelAndView.setViewName("error/business");
        return modelAndView;
    }
}
 
Example #14
Source File: GlobalExceptionHandler.java    From supplierShop with MIT License 6 votes vote down vote up
/**
 * 权限校验失败 如果请求为ajax返回json,普通请求跳转页面
 */
@ExceptionHandler(AuthorizationException.class)
public Object handleAuthorizationException(HttpServletRequest request, AuthorizationException e)
{
    log.error(e.getMessage(), e);
    if (ServletUtils.isAjaxRequest(request))
    {
        return AjaxResult.error(PermissionUtils.getMsg(e.getMessage()));
    }
    else
    {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("error/unauth");
        return modelAndView;
    }
}
 
Example #15
Source File: TableSupport.java    From RuoYi with Apache License 2.0 5 votes vote down vote up
/**
 * 封装分页对象
 */
public static PageDomain getPageDomain() {
    PageDomain pageDomain = new PageDomain();
    pageDomain.setPageNum(ServletUtils.getParameterToInt(Constants.PAGE_NUM));
    pageDomain.setPageSize(ServletUtils.getParameterToInt(Constants.PAGE_SIZE));
    pageDomain.setOrderByColumn(ServletUtils.getParameter(Constants.ORDER_BY_COLUMN));
    pageDomain.setIsAsc(ServletUtils.getParameter(Constants.IS_ASC));
    return pageDomain;
}
 
Example #16
Source File: GlobalExceptionHandler.java    From RuoYi with Apache License 2.0 5 votes vote down vote up
/**
 * 业务异常
 */
@ExceptionHandler(BusinessException.class)
public Object businessException(HttpServletRequest request, BusinessException e) {
    log.error(e.getMessage(), e);
    if (ServletUtils.isAjaxRequest(request)){
        return AjaxResult.error(e.getMessage());
    }else{
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("errorMessage", e.getMessage());
        modelAndView.setViewName("error/business");
        return modelAndView;
    }
}
 
Example #17
Source File: GlobalExceptionHandler.java    From RuoYi with Apache License 2.0 5 votes vote down vote up
/**
 * 权限校验失败 如果请求为ajax返回json,普通请求跳转页面
 */
@ExceptionHandler(AuthorizationException.class)
public Object handleAuthorizationException(HttpServletRequest request, AuthorizationException e) {
    log.error(e.getMessage(), e);
    if (ServletUtils.isAjaxRequest(request)) {
        return AjaxResult.error(PermissionUtils.getMsg(e.getMessage()));
    } else {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("error/unauth");
        return modelAndView;
    }
}
 
Example #18
Source File: LogAspect.java    From RuoYi-Vue with MIT License 5 votes vote down vote up
/**
 * 获取请求的参数,放到log中
 * 
 * @param operLog 操作日志
 * @throws Exception 异常
 */
private void setRequestValue(JoinPoint joinPoint, SysOperLog operLog) throws Exception
{
    String requestMethod = operLog.getRequestMethod();
    if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod))
    {
        String params = argsArrayToString(joinPoint.getArgs());
        operLog.setOperParam(StringUtils.substring(params, 0, 2000));
    }
    else
    {
        Map<?, ?> paramsMap = (Map<?, ?>) ServletUtils.getRequest().getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
        operLog.setOperParam(StringUtils.substring(paramsMap.toString(), 0, 2000));
    }
}
 
Example #19
Source File: AsyncFactory.java    From RuoYi with Apache License 2.0 5 votes vote down vote up
/**
 * 记录登陆信息
 *
 * @param username 用户名
 * @param status   状态
 * @param message  消息
 * @param args     列表
 * @return 任务task
 */
public static TimerTask recordLogininfor(final String username, final String status, final String message, final Object... args) {
    final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
    final String ip = ShiroUtils.getIp();
    return new TimerTask() {
        @Override
        public void run() {
            // 打印信息到日志
            String address = AddressUtils.getRealAddressByIp(ip);
            String s = LogUtils.getBlock(ip) +
                    address +
                    LogUtils.getBlock(username) +
                    LogUtils.getBlock(status) +
                    LogUtils.getBlock(message);
            sys_user_logger.info(s, args);
            // 获取客户端操作系统
            String os = userAgent.getOperatingSystem().getName();
            // 获取客户端浏览器
            String browser = userAgent.getBrowser().getName();
            // 封装对象
            SysLogininfor logininfor = new SysLogininfor();
            logininfor.setLoginName(username);
            logininfor.setIpaddr(ip);
            logininfor.setLoginLocation(address);
            logininfor.setBrowser(browser);
            logininfor.setOs(os);
            logininfor.setMsg(message);
            // 日志状态
            if (Constants.LOGIN_SUCCESS.equals(status) || Constants.LOGOUT.equals(status)) {
                logininfor.setStatus(Constants.SUCCESS);
            } else if (Constants.LOGIN_FAIL.equals(status)) {
                logininfor.setStatus(Constants.FAIL);
            }
            // 插入数据
            SpringUtils.getBean(SysLogininforServiceImpl.class).insertLogininfor(logininfor);
        }
    };
}
 
Example #20
Source File: KickoutSessionFilter.java    From RuoYi with Apache License 2.0 5 votes vote down vote up
private boolean isAjaxResponse(ServletRequest request, ServletResponse response) throws IOException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    if (ServletUtils.isAjaxRequest(req)) {
        AjaxResult ajaxResult = AjaxResult.error("您已在别处登录,请您修改密码或重新登录");
        ServletUtils.renderString(res, JSONUtil.toJsonStr(ajaxResult));
    } else {
        WebUtils.issueRedirect(request, response, kickoutUrl);
    }
    return false;
}
 
Example #21
Source File: PermissionService.java    From RuoYi-Vue with MIT License 5 votes vote down vote up
/**
 * 验证用户是否具备某权限
 * 
 * @param permission 权限字符串
 * @return 用户是否具备某权限
 */
public boolean hasPermi(String permission)
{
    if (StringUtils.isEmpty(permission))
    {
        return false;
    }
    LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
    if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getPermissions()))
    {
        return false;
    }
    return hasPermissions(loginUser.getPermissions(), permission);
}
 
Example #22
Source File: TokenService.java    From RuoYi-Vue with MIT License 5 votes vote down vote up
/**
 * 设置用户代理信息
 * 
 * @param loginUser 登录信息
 */
public void setUserAgent(LoginUser loginUser)
{
    UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
    String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
    loginUser.setIpaddr(ip);
    loginUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
    loginUser.setBrowser(userAgent.getBrowser().getName());
    loginUser.setOs(userAgent.getOperatingSystem().getName());
}
 
Example #23
Source File: AuthenticationEntryPointImpl.java    From RuoYi-Vue with MIT License 5 votes vote down vote up
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
        throws IOException
{
    int code = HttpStatus.UNAUTHORIZED;
    String msg = StringUtils.format("请求访问:{},认证失败,无法访问系统资源", request.getRequestURI());
    ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, msg)));
}
 
Example #24
Source File: TableSupport.java    From RuoYi-Vue with MIT License 5 votes vote down vote up
/**
 * 封装分页对象
 */
public static PageDomain getPageDomain()
{
    PageDomain pageDomain = new PageDomain();
    pageDomain.setPageNum(ServletUtils.getParameterToInt(PAGE_NUM));
    pageDomain.setPageSize(ServletUtils.getParameterToInt(PAGE_SIZE));
    pageDomain.setOrderByColumn(ServletUtils.getParameter(ORDER_BY_COLUMN));
    pageDomain.setIsAsc(ServletUtils.getParameter(IS_ASC));
    return pageDomain;
}
 
Example #25
Source File: SysLoginController.java    From RuoYi with Apache License 2.0 5 votes vote down vote up
@GetMapping("/login")
public String login(HttpServletRequest request, HttpServletResponse response) {
    // 如果是Ajax请求,返回Json字符串。
    if (ServletUtils.isAjaxRequest(request)) {
        return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"未登录或登录超时。请重新登录\"}");
    }

    return "login";
}
 
Example #26
Source File: LogAspect.java    From supplierShop with MIT License 5 votes vote down vote up
/**
 * 获取请求的参数,放到log中
 * 
 * @param operLog 操作日志
 * @throws Exception 异常
 */
private void setRequestValue(SysOperLog operLog) throws Exception
{
    Map<String, String[]> map = ServletUtils.getRequest().getParameterMap();
    String params = JSON.marshal(map);
    operLog.setOperParam(StringUtils.substring(params, 0, 2000));
}
 
Example #27
Source File: SysLoginController.java    From RuoYi-Vue with MIT License 5 votes vote down vote up
/**
 * 获取路由信息
 * 
 * @return 路由信息
 */
@GetMapping("getRouters")
public AjaxResult getRouters()
{
    LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
    // 用户信息
    SysUser user = loginUser.getUser();
    List<SysMenu> menus = menuService.selectMenuTreeByUserId(user.getUserId());
    return AjaxResult.success(menuService.buildMenus(menus));
}
 
Example #28
Source File: SysProfileController.java    From RuoYi-Vue with MIT License 5 votes vote down vote up
/**
 * 个人信息
 */
@GetMapping
public AjaxResult profile()
{
    LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
    SysUser user = loginUser.getUser();
    AjaxResult ajax = AjaxResult.success(user);
    ajax.put("roleGroup", userService.selectUserRoleGroup(loginUser.getUsername()));
    ajax.put("postGroup", userService.selectUserPostGroup(loginUser.getUsername()));
    return ajax;
}
 
Example #29
Source File: SysUserController.java    From RuoYi-Vue with MIT License 5 votes vote down vote up
@Log(title = "用户管理", businessType = BusinessType.IMPORT)
@PreAuthorize("@ss.hasPermi('system:user:import')")
@PostMapping("/importData")
public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
{
    ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
    List<SysUser> userList = util.importExcel(file.getInputStream());
    LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
    String operName = loginUser.getUsername();
    String message = userService.importUser(userList, updateSupport, operName);
    return AjaxResult.success(message);
}
 
Example #30
Source File: SysMenuController.java    From RuoYi-Vue with MIT License 5 votes vote down vote up
/**
 * 加载对应角色菜单列表树
 */
@GetMapping(value = "/roleMenuTreeselect/{roleId}")
public AjaxResult roleMenuTreeselect(@PathVariable("roleId") Long roleId)
{
    LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
    List<SysMenu> menus = menuService.selectMenuList(loginUser.getUser().getUserId());
    AjaxResult ajax = AjaxResult.success();
    ajax.put("checkedKeys", menuService.selectMenuListByRoleId(roleId));
    ajax.put("menus", menuService.buildMenuTreeSelect(menus));
    return ajax;
}