Java Code Examples for com.ruoyi.common.utils.ServletUtils

The following examples show how to use com.ruoyi.common.utils.ServletUtils. These examples are extracted from open source projects. 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 Project: supplierShop   Source File: GlobalExceptionHandler.java    License: 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 2
Source Project: supplierShop   Source File: GlobalExceptionHandler.java    License: 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 3
Source Project: supplierShop   Source File: RepeatSubmitInterceptor.java    License: 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 4
Source Project: supplierShop   Source File: OnlineSessionFactory.java    License: 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 5
Source Project: RuoYi-Vue   Source File: SysProfileController.java    License: 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 6
Source Project: RuoYi-Vue   Source File: SysProfileController.java    License: 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 7
Source Project: RuoYi-Vue   Source File: SysLoginController.java    License: 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 8
Source Project: RuoYi-Vue   Source File: DataScopeAspect.java    License: 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 9
Source Project: RuoYi-Vue   Source File: LogoutSuccessHandlerImpl.java    License: 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 10
Source Project: RuoYi-Vue   Source File: PermissionService.java    License: 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 11
Source Project: RuoYi-Vue   Source File: PermissionService.java    License: 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 12
Source Project: RuoYi-Vue   Source File: PermissionService.java    License: 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 13
Source Project: RuoYi-Vue   Source File: RepeatSubmitInterceptor.java    License: 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 14
Source Project: RuoYi   Source File: OnlineSessionFactory.java    License: 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 15
Source Project: supplierShop   Source File: LogAspect.java    License: 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 16
Source Project: supplierShop   Source File: KickoutSessionFilter.java    License: MIT License 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, objectMapper.writeValueAsString(ajaxResult));
    }
    else
    {
        WebUtils.issueRedirect(request, response, kickoutUrl);
    }
    return false;
}
 
Example 17
Source Project: supplierShop   Source File: TableSupport.java    License: MIT License 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 18
Source Project: supplierShop   Source File: SysLoginController.java    License: MIT License 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 19
Source Project: RuoYi-Vue   Source File: SysMenuController.java    License: MIT License 5 votes vote down vote up
/**
 * 获取菜单列表
 */
@PreAuthorize("@ss.hasPermi('system:menu:list')")
@GetMapping("/list")
public AjaxResult list(SysMenu menu)
{
    LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
    Long userId = loginUser.getUser().getUserId();
    List<SysMenu> menus = menuService.selectMenuList(menu, userId);
    return AjaxResult.success(menus);
}
 
Example 20
Source Project: RuoYi-Vue   Source File: SysMenuController.java    License: MIT License 5 votes vote down vote up
/**
 * 获取菜单下拉树列表
 */
@GetMapping("/treeselect")
public AjaxResult treeselect(SysMenu menu)
{
    LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
    Long userId = loginUser.getUser().getUserId();
    List<SysMenu> menus = menuService.selectMenuList(menu, userId);
    return AjaxResult.success(menuService.buildMenuTreeSelect(menus));
}
 
Example 21
Source Project: RuoYi-Vue   Source File: SysMenuController.java    License: 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;
}
 
Example 22
Source Project: RuoYi-Vue   Source File: SysUserController.java    License: 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 23
Source Project: RuoYi-Vue   Source File: SysProfileController.java    License: 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 24
Source Project: RuoYi-Vue   Source File: SysLoginController.java    License: 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 25
Source Project: RuoYi-Vue   Source File: LogAspect.java    License: 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 26
Source Project: RuoYi-Vue   Source File: TableSupport.java    License: 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 27
Source Project: RuoYi-Vue   Source File: AuthenticationEntryPointImpl.java    License: 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 28
Source Project: RuoYi-Vue   Source File: TokenService.java    License: 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 29
Source Project: RuoYi-Vue   Source File: PermissionService.java    License: 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 30
Source Project: RuoYi   Source File: GlobalExceptionHandler.java    License: 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;
    }
}