Java web开发中经常用到的一些方法:

import java.io.BufferedReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle; import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession; import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;import org.springframework.web.util.WebUtils; import com.alibaba.fastjson.JSON; /**
* Web层辅助类*/
public final class WebUtil {

private WebUtil() {
} private static Logger logger = LogManager.getLogger();
public static final String CURRENT_USER = "CURRENT_USER"; /**
* 获取指定Cookie的值
*
* @param cookies
* cookie集合
* @param cookieName
* cookie名字
* @param defaultValue
* 缺省值
* @return
*/
public static final String getCookieValue(HttpServletRequest request, String cookieName, String defaultValue) {
Cookie cookie = WebUtils.getCookie(request, cookieName);
if (cookie == null) {
return defaultValue;
}
return cookie.getValue();
} /** 保存当前用户 */
public static final void saveCurrentUser(Object user) {
setSession(CURRENT_USER, user);
} /** 保存当前用户 */
public static final void saveCurrentUser(HttpServletRequest request, Object user) {
setSession(request, CURRENT_USER, user);
} /** 获取当前用户 */
public static final Long getCurrentUser() {
Subject currentUser = SecurityUtils.getSubject();
if (null != currentUser) {
try {
Session session = currentUser.getSession();
if (null != session) {
return (Long) session.getAttribute(CURRENT_USER);
}
} catch (InvalidSessionException e) {
logger.error(e);
}
}
return null;
} /** 获取当前用户 */
public static final Object getCurrentUser(HttpServletRequest request) {
try {
HttpSession session = request.getSession();
if (null != session) {
return session.getAttribute(CURRENT_USER);
}
} catch (InvalidSessionException e) {
logger.error(e);
}
return null;
} /**
* 将一些数据放到ShiroSession中,以便于其它地方使用
*
* @see 比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取到
*/
public static final void setSession(Object key, Object value) {
Subject currentUser = SecurityUtils.getSubject();
if (null != currentUser) {
Session session = currentUser.getSession();
if (null != session) {
session.setAttribute(key, value);
}
}
} /**
* 将一些数据放到ShiroSession中,以便于其它地方使用
*
* @see 比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取到
*/
public static final void setSession(HttpServletRequest request, String key, Object value) {
HttpSession session = request.getSession();
if (null != session) {
session.setAttribute(key, value);
}
} /** 移除当前用户 */
public static final void removeCurrentUser(HttpServletRequest request) {
request.getSession().removeAttribute(CURRENT_USER);
} /**
* 获得国际化信息
*
* @param key
* 键
* @param request
* @return
*/
public static final String getApplicationResource(String key, HttpServletRequest request) {
ResourceBundle resourceBundle = ResourceBundle.getBundle("ApplicationResources", request.getLocale());
return resourceBundle.getString(key);
} /**
* 获得参数Map
*
* @param request
* @return
*/
public static final Map<String, Object> getParameterMap(HttpServletRequest request) {
return WebUtils.getParametersStartingWith(request, null);
} @SuppressWarnings("unchecked")
public static Map<String, Object> getParameter(HttpServletRequest request) {
String str, wholeStr = "";
try {
BufferedReader br = request.getReader();
while ((str = br.readLine()) != null) {
wholeStr += str;
}
if (StringUtils.isNotBlank(wholeStr)) {
return JSON.parseObject(wholeStr, Map.class);
}
} catch (Exception e) {
logger.error("", e);
}
return getParameterMap(request);
} public static <T> T getParameter(HttpServletRequest request, Class<T> cls) {
String str, wholeStr = "";
try {
BufferedReader br = request.getReader();
while ((str = br.readLine()) != null) {
wholeStr += str;
}
if (StringUtils.isNotBlank(wholeStr)) {
return JSON.parseObject(wholeStr, cls);
}
} catch (Exception e) {
logger.error("", e);
}
return Request2ModelUtil.covert(cls, request);
} @SuppressWarnings("unchecked")
public static <T> List<T> getParameters(HttpServletRequest request, Class<T> cls) {
String str, wholeStr = "";
try {
BufferedReader br = request.getReader();
while ((str = br.readLine()) != null) {
wholeStr += str;
}
if (StringUtils.isNotBlank(wholeStr)) {
return JSON.parseObject(wholeStr, List.class);
}
} catch (Exception e) {
logger.error("", e);
}
return Request2ListUtil.covert(cls, request);
} /** 获取客户端IP */
public static final String getHost(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if (ip != null && ip.indexOf(",") > 0) {
// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
ip = ip.substring(0, ip.indexOf(","));
}
if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
}
if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
ip = inet.getHostAddress();
} catch (UnknownHostException e) {
logger.error(e);
}
}
return ip;
}
}

Web层辅助工具类的更多相关文章

  1. Java.控制层.响应工具类.

    Java.控制层.响应工具类. package cn.com.spdbccc.cds.index.web.base; public class ApiResponse { private int co ...

  2. 类型转换辅助工具类TypeCaseHelper

    package org.sakaiproject.util; import java.math.BigDecimal; import java.sql.Date; import java.sql.Ti ...

  3. spring -mvc service层调用工具类配置

    在service层时调用工具类时服务返回工具类对象为空 在此工具类上加上@Component注解就可以了 @Component:把普通pojo实例化到spring容器中,相当于配置文件中的 <b ...

  4. java在文本处理中的相关辅助工具类

    1,java分词 package com.bobo.util; import ICTCLAS.I3S.AC.ICTCLAS50; public class Cutwords { public stat ...

  5. JUC——线程同步辅助工具类(Semaphore,CountDownLatch,CyclicBarrier)

    锁的机制从整体的运行转态来讲核心就是:阻塞,解除阻塞,但是如果仅仅是这点功能,那么JUC并不能称为一个优秀的线程开发框架,然而是因为在juc里面提供了大量方便的同步工具辅助类. Semaphore信号 ...

  6. JUC——线程同步辅助工具类(Exchanger,CompletableFuture)

    Exchanger交换空间 如果现在有两个线程,一个线程负责生产数据,另外一个线程负责消费数据,那么这个两个线程之间一定会存在一个公共的区域,那么这个区域的实现在JUC包之中称为Exchanger. ...

  7. 好用的Cache辅助工具类

    话不多说,直接上代码 using System; using System.Collections.Generic; using System.Linq; using System.Text; usi ...

  8. 制作ado开发辅助工具类SqlHelper

    public static class SqlHelper { //通过配置文件获取连接字符创 private static readonly string constr = Configuratio ...

  9. JAVA结合 JSON Web Token(JWT) 工具类

    引入java-jwt-3.3.0.jar .  jjwt-0.9.0.jar .jackson-all-1.7.6.jar 或者maven <!-- https://mvnrepository. ...

随机推荐

  1. 【BZOJ】3538: [Usaco2014 Open]Dueling GPS(spfa)

    http://www.lydsy.com/JudgeOnline/problem.php?id=3538 题意不要理解错QAQ,是说当前边(u,v)且u到n的最短距离中包含这条边,那么这条边就不警告. ...

  2. 多线程之使用读写锁ReentrantReadWriteLock实现缓存系统

    简单地缓存系统:当有线程来取数据时.假设该数据存在我的内存中.我就返回数据.假设不存在我的缓存系统中,那么就去查数据库.返回数据的同一时候保存在我的缓存中. 当中涉及到读写问题:当多个线程运行读操作时 ...

  3. java字符编码(转)

    转载:http://blog.csdn.net/peach99999/article/details/7231247 深入讨论java乱码问题 几种常见的编码格式 为什么要编码 不知道大家有没有想过一 ...

  4. CSS样式设置

    转载来自:http://www.imooc.com/article/2067水平居中设置-行内元素 水平居中 如果被设置元素为文本.图片等行内元素时,水平居中是通过给父元素设置 text-align: ...

  5. K-Means算法Demo

    简介:本Demo是参照这个网站上的Demo自己用Java实现的.将Java打包为Jar,再将Jar转为exe,源代码及程序Demo下载请点我. K-Means算法简介 我尽量用通俗易懂但不规范的语言来 ...

  6. ReSharper 配置及用法(ZHUANG)

    1:安装后,Resharper会用他自己的英文智能提示,替换掉 vs2010的智能提示,所以我们要换回到vs2010的智能提示 2:快捷键.是使用vs2010的快捷键还是使用 Resharper的快捷 ...

  7. ROS导航之参数配置和自适应蒙特卡罗定位

    我们的机器人使用两种导航算法在地图中移动:全局导航(global)和局部导航(local).这些导航算法通过代价地图来处理地图中的各种信息,导航stack使用两种costmaps http://www ...

  8. Django 找不到模版报错" django.template.exceptions.TemplateDoesNotExist: index.html"

    解决办法:在setting.py的TEMPLATES‘DIRS'[]加入模版路径 os.path.join(BASE_DIR, 'templates') TEMPLATES = [ { 'BACKEN ...

  9. Fragment切换页面

    <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=&quo ...

  10. python技巧之下划线(一)

    1.python的moudles文件中__all__作用 Python的moudle是很重要的一个概念,我看到好多人写的moudle里都有一个__init__.py文件.有的__init__.py中是 ...