Posted in 面试题 onOctober 17, 2014
Servlet可以使用getRemoteAddr()和getRemoteHost()来得到客户端的IP地址和host, 代码如下所示:
public String ServletRequest.getRemoteAddr()
public Stirng ServletRequest.getRemoteHost()
用这些方法来访问客户端有所限制,如下代码实现了对客户端配置进行检查并把相关消息发送到客户端的功能:
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DemoExportRestriction extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException{
res.setContentType("text/plain");
PrintWriter out= res.getWriter();
//得到客户端的hostname
String remoteHost = req.getRemoteHost();
//查看客户端是否允许这样的操作
if(!isHostAllowed(remoteHost)){
out.println("Access ");
} else{
out.println("access granted");
}
}
private boolean isHostAllowed(String host) {
return(host.endsWith(".com"))||
(host.indexOf(.)==-1);//没有域名 ok
}
}
public String ServletRequest.getRemoteAddr()
public Stirng ServletRequest.getRemoteHost()
用这些方法来访问客户端有所限制,如下代码实现了对客户端配置进行检查并把相关消息发送到客户端的功能:
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DemoExportRestriction extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException{
res.setContentType("text/plain");
PrintWriter out= res.getWriter();
//得到客户端的hostname
String remoteHost = req.getRemoteHost();
//查看客户端是否允许这样的操作
if(!isHostAllowed(remoteHost)){
out.println("Access ");
} else{
out.println("access granted");
}
}
private boolean isHostAllowed(String host) {
return(host.endsWith(".com"))||
(host.indexOf(.)==-1);//没有域名 ok
}
}
Servlet如何得到客户端机器的信息
声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Tags in this post...
Reply on: @reply_date@
@reply_contents@