自学内容网 自学内容网

Java中使用HttpServletRequest获取ip和端口-详解

目录

1.简单例子

2.详细使用例子---Java项目

2.1.Controller层

2.2service层

2.2.1接口

2.2.2serviceImpl实现类

3.IpUtils工具类


1.简单例子

也可以直接用

public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
       String ServerName = request.getServerName();//返回服务器的主机名
       String ServerPort = request.getServerPort();//返回服务器的端口号
 
       String uri = request.getRequestURI();//返回请求行中的资源名称
       String url = request.getRequestURL().toString();//获得客户端发送请求的完整url
       String ip = request.getRemoteAddr();//返回发出请求的IP地址
       String params = request.getQueryString();//返回请求行中的参数部分
       String host=request.getRemoteHost();//返回发出请求的客户机的主机名
       int port =request.getRemotePort();//返回发出请求的客户机的端口号
 
       System.out.println(ServerName);
       System.out.println(ServerPort);
       
       System.out.println(ip);
       System.out.println(url);
       System.out.println(uri);
       System.out.println(params);
       System.out.println(host);
       System.out.println(port);
}

2.详细使用例子---Java项目

真正用到在serviceImpl实现类中

2.1.Controller层

@RestController
@RequestMapping("/api")
public class DataReportController {

private final DataReportService dataReportService;
private final BusinessMsgCodeProperties props;
@Autowired
public DataReportController(DataReportService dataReportService, BusinessMsgCodeProperties props){
    this.dataReportService = dataReportService;
    this.props = props;
}

/**
 * 数据上报接⼝
 */
@PostMapping("/dataReport")//这个接口既传文件参数又传实体实参,request不是参数,前端不传后端可自行获取
public Resource<String> dataReport(@RequestPart(value = "file", required = true) MultipartFile file, @RequestPart  @Validated DataReportInDto dto, HttpServletRequest request){
    String code = dataReportService.dataReport(file,dto,request);
    return new Resource<>(props.getProcessStatus(code));       //Resource为自行封装的返回类型,可以用不用
}

}

2.2service层

2.2.1接口

public interface DataReportService extends IService<ReportData> {

    /**
     * 数据上报接⼝
     */
String dataReport(MultipartFile file, DataReportInDto dto, HttpServletRequest request);
}

2.2.2serviceImpl实现类

@Service
@Slf4j
public class DataReportServiceImpl extends ServiceImpl<DataReportMapper, ReportData> implements DataReportService {

private final DataReportMapper dataReportMapper;
@Autowired
public DataReportServiceImpl(DataReportMapper dataReportMapper){
    this.dataReportMapper = dataReportMapper;
}


@Override
public String dataReport(MultipartFile file, DataReportInDto dto, HttpServletRequest request) {
    //一、获取调用者的ip+port
    String ip = "";
    String port = "";
    String loginName = "";
    try {
        ip = IpUtils.getRemoteHost(request);     //自己封装一个工具类(对特殊情况做了一定处理)
        String ip1 =  request.getRemoteAddr();   //直接获取
        port = String.valueOf(request.getRemotePort());
        System.out.println("远程端的ip1:"+ip1);
        System.out.println("远程的端口:"+ip);
        System.out.println("远程端口:"+port);
        log.info("获取调用者ip:"+ip+" ,"+"port:"+port);
    } catch (Exception e) {
        e.printStackTrace();
        log.info("获取调用者ip+port失败");
    }
return "COMMON_ERROR";
}

}

3.IpUtils工具类

直接整个粘贴就能用

package com.nengyy.speed_rest_server.utils;        //所在包

import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;

public class IpUtils {
    public static String getRemoteHost(HttpServletRequest request){
        String ip = request.getHeader("x-forwarded-for");
        if(StringUtils.isNoneBlank(ip) && !"unknown".equalsIgnoreCase(ip)){
            int idx = ip.indexOf(",");
            if(idx != -1){
                ip = ip.substring(0, idx);
            }
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getRemoteAddr();
        }
        return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
    }
}


原文地址:https://blog.csdn.net/m0_71202849/article/details/135386224

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!