1. java打開html文件
你的意思是用java代碼模擬訪問一個html網頁? 可以用URLConnection
URL url = new URL("你的html文件的http地址");
URLConnection URLconnection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) URLconnection;
InputStream urlStream = httpConnection.getInputStream();
另外如果html里有js的話 是不能模擬訪問js的
2. 如何在java中顯示html的內容
不知兄台是不是說的這種格式的,寫一個java文件(servlet),運行後輸出一個網頁,下面是一個登錄界面,你只需要創建一個servlet,然後將其中的doget換成如下代碼,將dopost改成doget();即可運行。望採納!
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String cookieName = "userName";
String cookiePwd = "pwd";
Cookie[] cookies = request.getCookies();
String userName = "";
String pwd = "";
boolean isChecked = false;
//如果cookie數組不為null,說明曾經設置過,也就是曾經登錄過,那麼取出上次登錄的用戶名和密碼;
if (cookies != null)
{
for (int i=0; i<cookies.length; i++)
{
Cookie cookie = cookies[i] ;
if (cookieName.equals(cookie.getName()))
{
userName = cookie.getValue() ;
}
if (cookiePwd.equals(cookie.getName()))
{
pwd = cookie.getValue() ;
}
if ("Check".equals(cookie.getName()))
{
isChecked = cookie.getValue().equals("yes")? true : false ;
}
}
}
response.setContentType("text/html;charset=GBK");
request.setCharacterEncoding("gbk") ;
PrintWriter out = response.getWriter() ;
String docType = "<DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">" ;
String title = "ServletLoginDemo";
out.println(docType + "<html> " + "<head>"
+"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gbk\">"
+ "<style type=\"text/css\">"
+ ".textsize {width: 150px ; background: #B1DC87}"
+ "</style>"
+ "<title>" + title
+ "</title></head> " + "<body bgcolor=\"#FDF5E6\"> "
+ "<br />"
+ "<br />"
+ "<center> " + "<h1>Cookie登陸Demo</h1> "
+ "<hr />"
+ "<form action=\"CookieTest\" method=\"post\">"
+ (userName == null ? "用戶名:<input class=\"textsize\" type=\"text\" name=\"UserName\" width=\"20\"></input><br />" : "用戶名:<input class=\"textsize\" type=\"text\" name=\"UserName\" width=\"20\" value=" + userName +"></input><br />")
+ (pwd == null ? "密碼:<input class=\"textsize\" type=\"password\" name=\"Password\"></input><br />" : "密碼:<input class=\"textsize\" type=\"password\" name=\"Password\" value=" + pwd +"></input><br />")
+ (isChecked ? "<input type=\"checkbox\" name=\"Check\" checked=\"true\">記住密碼</input>" : "<input type=\"checkbox\" name=\"Check\">記住密碼</input>")
+ "<center><input type=\"submit\" value=\"登陸\"></center>"
+ "</form>"
+"</center></body></html>");
}