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>");
}