从零开始--第一个Jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.util.Date,java.text.*" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
Date nowday=new Date();//获得当前日期
int hour=nowday.getHours();//获得日期中的小时
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//定义日期格式
String time=format.format(nowday);//将指定日期格式化为“yyyy-MM-dd HH:mm:ss”形式
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>第一个jsp应用</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	
  </head>
  
  <body>
    <center>
    <img src="#" id="img">
    <script language="javascript">
	var img=document.getElementById("img");
	
	img.onclick=function(){
		alert("你点击了图片");
	}
	</script>
    	<table border="1" width="300">
    		<tr height="30" id="text"><td align="center">温馨提示!</td></tr>
    		<tr heiight="80"><td align="center">现在时间为:<%=time %></td></tr>
    		<!-- 以下为嵌入到HTML中的Java代码,用来生成动态的内容 -->
    		<%
    		if(hour>=24&&hour<5)out.print("现在是凌晨!时间还早,再睡会吧~");
    		else if(hour>=5&&hour<10)out.print("早上好!新的一天即将开始,您准备好了吗?");
    		else if(hour>=10&&hour<13)out.print("午休时间,正午好时光!");
    		else if(hour>=13&&hour<18)out.print("下午继续工作吧");
    		else if (hour>=18&&hour<21)out.print("晚上好!有自由时间!");
    		else if(hour>=21&&hour<24)out.print("已经是深夜,注意休息~");
    		 %>
    	</table>
    	
    </center>
  </body>
</html>

上面的代码中使用了jsp+html+javascript实现了一个简单的页面效果,如图所示:


其中新手需要注意的几点是:

1、在学Java开发的时候,导入包的方式是直接在上面写import java.**.**获得的,而在jsp程序设计中,需要用<% page import="java.util.Date,java.text.*"%>的方式获得,并且只需要写一个import即可,可在双引号中写入多个包名。

2、插入Java代码时需要使用<%的标志。

3、在html代码中使用Java变量需要用<%=变量名%>的方式来获得。

4、在jsp程序设计中,在使用JavaScript时,通过language属性指定使用的脚本语言,例如:<script language="javascript"></script>,而想要从外部链接JavaScript时,则只需在<script>中添加src属性即可。

5、在JavaScript中,函数名区分大小写,而在分配事件处理程序时,事件处理程序名称必须小写,才能正确相应事件。

6、JavaScript如果调用了html中的元素,则需要将JavaScript放在元素之后,放在之前验证无效。

猜你喜欢

转载自blog.csdn.net/gemini_xujian/article/details/79574853