这是我的方法
public synchronized void updateCompanyByNameandUrl(String companyName, String companyUrl)
{
PreparedStatement ps = null;
PreparedStatement ps1 = null;
Connection con = null;
Connection globalconnection = null;
String updateCompanyquery = "update `anjo_company_master` set URL = ? where COMPANY_NAME=?";
String updateGlobalCompQuery= "update `anjo_company_master_global` set URL = ?, USER_IP = ? where COMPANY_NAME=?";
try
{
***InetAddress localhost = InetAddress.getLocalHost();
String userIp = localhost.getHostAddress().trim();***
con = SQLHikariConnectionFactory.getInstance().getConnection();
ps = con.prepareStatement(updateCompanyquery);
ps.setString(1, companyUrl.trim());
ps.setString(2, companyName.trim());
ps.executeUpdate();
//Updating companyUrl in Global Master also
globalconnection = connFactory.getGlobalCompanyConnection();
ps1 = globalconnection.prepareStatement(updateGlobalCompQuery);
ps1.setString(1, companyUrl.trim());
ps1.setString(2, userIp.trim());
ps1.setString(3, companyName.trim());
ps1.executeUpdate();
}
catch(Exception e)
{
e.printStackTrace();
LOG.info(e.getMessage(), e);
}
finally
{
try {
if (con != null)
con.close();
if (ps != null)
ps.close();
}
catch (Exception e2)
{
e2.printStackTrace();
}
}
}
这里因为
InetAddress localhost = InetAddress.getLocalHost();
String userIp = localhost.getHostAddress().trim();
我没有得到用户IP 我得到了服务器IP
但我得到的是服务器 IP 而不是客户端 IP 谁能帮我?
请在调用DAO方法之前将HttpServletRequest
对象设置为DAO类。
Use the below code.
Class Test extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Client IP " + request.getHeader("X-Forwarded-For"));
TestDAO dao = TestDAOImpl();
dao.setHttpServletRequest(request);
dao.xxxxx(xx,xx)\call your method like this
}
}
Class TestDAOImpl implements TestDAO {
private HttpServletRequest request;
public void setHttpServletRequest(HttpServletRequest request) {
this.request = request;
}
//write your method here.
public <?> doSomthing(){
String clientIP= this.request.getHeader("X-Forwarded-For");
//d
}
}