要获取服务器地址,有几种情况可以考虑:
获取请求的完整URL
Struts2可以通过HttpServletRequest
的getRequestURL
方法获取当前请求URL,包括协议,主机名,端口和路径。在Action类中可以这样获取:
import javax.servlet.http.HttpServletRequest;
import com.opensymphony.xwork2.ActionSupport;
public class DemoAction extends ActionSupport {
private HttpServletRequest request;
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
public String execute() throws Exception {
StringBuffer url = request.getRequestURL();
System.out.println("URL: " + url.toString());
return SUCCESS;
}
}
获取服务器的主机名和端口号
如果只需要获取服务器的主机名和端口号,可以使用HttpServletRequest
的getServerName
和getServerPort
方法。在Action类中可以这样获取:
import javax.servlet.http.HttpServletRequest;
import com.opensymphony.xwork2.ActionSupport;
public class DemoAction extends ActionSupport {
private HttpServletRequest request;
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
public String execute() throws Exception {
String serverName = request.getServerName();
int serverPort = request.getServerPort();
System.out.println("Server name: " + serverName + ", port: " + serverPort);
return SUCCESS;
}
}
示例1:
URL: http://localhost:8080/myapp/index.jsp
输出:
URL: http://localhost:8080/myapp/index.jsp
示例2:
假设本地服务器的IP地址是192.168.1.100,端口是8888,部署的应用程序名称是myapp,那么URL应该是:
http://192.168.1.100:8888/myapp/index.jsp
输出:
URL: http://192.168.1.100:8888/myapp/index.jsp
Server name: 192.168.1.100, port: 8888
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:JAVA+Struts2获取服务器地址的方法 - Python技术站