JSP基本语法
编写一个JSP页面,在该页面中显示当前时间
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import="java.util.*"%>
<%@ page import="java.text.SimpleDateFormat"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>一个简单的JSP页面——显示系统时间</title>
</head>
<body>
<%Date date=new Date();SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String today=df.format(date);
%>当前时间:<%=today %></body>
</html>
应用include指令包含网站Banner和版权信息栏
<%@ page pageEncoding="GB18030"%>
<img src="images/banner.JPG">
<%@ page pageEncoding="GB18030"%>
<%
String copyright=" ALL Copyright ©2009 有限公司";
%>
<table width="778" height="61" border="0" cellpadding="0"
cellspacing="0" background="images/copyright.JPG"><tr><td> <%=copyright %></td></tr>
</table>
<%@ page language="java" contentType="text/html; charset=GB18030"pageEncoding="GB18030"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>使用文件包含include指令</title>
</head>
<body style="margin:0px;">
<%@ include file="top.jsp"%>
<table width="781" height="279" border="0" cellpadding="0" cellspacing="0" background="images/center.JPG"><tr><td> </td></tr>
</table>
<%@ include file="copyright.jsp"%>
</body>
</html>
应用<jsp:include>标识包含网站Banner和版权信息栏
<%@ page language="java" contentType="text/html; charset=GB18030"pageEncoding="GB18030"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>使用文件包含include指令</title>
</head>
<body style="margin:0px;">
<%@ include file="top.jsp"%>
<table width="781" height="279" border="0" cellpadding="0" cellspacing="0" background="images/center.JPG"><tr><td> </td></tr>
</table>
<%@ jsp:include page="copyright.jsp"%>
</body>
</html>
应用<jsp:forward>标识将页面转发到用户登录页面
<%@ page language="java" contentType="text/html; charset=GB18030"pageEncoding="GB18030"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>中转页</title>
</head>
<body>
<jsp:forward page="login.jsp"/>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=GB18030"pageEncoding="GB18030"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>用户登录</title>
</head>
<body>
<form name="form1" method="post" action="">
用户名: <input name="name" type="text" id="name" style="width: 120px"><br>
密 码: <input name="pwd" type="password" id="pwd" style="width: 120px"> <br>
<br>
<input type="submit" name="Submit" value="提交">
</form>
</body>
</html>
JSP内置对象
使用request对象获取请求参数值
<%@ page language="java" contentType="text/html; charset=GB18030"pageEncoding="GB18030"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>使用request对象获取请求参数值</title>
</head>
<body>
<a href="deal.jsp?id=1&user=">处理页</a>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=GB18030"pageEncoding="GB18030"%>
<%String id=request.getParameter("id");String user=request.getParameter("user");String pwd=request.getParameter("pwd");
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>处理页</title>
</head>
<body>
id 参数的值为:<%=id %><br>
user 参数的值为:<%=user %><br>
pwd 参数的值为:<%=pwd %>
</body>
</html>
使用request对象的色图Attribute()方法保存request范围内的变量,并应用request对象的getAttribute()方法读取request范围内的变量
<%@ page language="java" contentType="text/html; charset=GB18030"pageEncoding="GB18030"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title here</title>
</head>
<body>
<%
try{//捕获异常信息int money=100;int number=0;request.setAttribute("result",money/number);//保存执行结果
}catch(Exception e){request.setAttribute("result","很抱歉,页面产生错误!");//保存错误提示信息
}
%>
<jsp:forward page="deal.jsp"/>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=GB18030"pageEncoding="GB18030"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>处理页</title>
</head>
<body>
<%String message=request.getAttribute("result").toString(); %>
<%=message %>
</body>
</html>
通过cookie保存并读取用户登录信息
<%@ page language="java" contentType="text/html; charset=utf-8"pageEncoding="utf-8"%>
<%@ page import="java.net.URLDecoder" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>通过cookie保存并读取用户登录信息</title>
</head>
<body>
<%Cookie[ ] cookies = request.getCookies();//从request中获得Cookie对象的集合String user = ""; //登录用户String date = ""; //注册的时间if (cookies != null) {for (int i = 0; i < cookies.length; i++) { //遍历cookie对象的集合if (cookies[i].getName().equals("mrCookie")) {//如果cookie对象的名称为mrCookieuser = URLDecoder.decode(cookies[i].getValue().split("#")[0]);//获取用户名date = cookies[i].getValue().split("#")[1];//获取注册时间}}}if ("".equals(user) && "".equals(date)) {//如果没有注册
%>游客您好,欢迎您初次光临!<form action="deal.jsp" method="post">请输入姓名:<input name="user" type="text" value=""><input type="submit" value="确定"></form>
<%} else {//已经注册
%>欢迎[<b><%=user %></b>]再次光临<br>您注册的时间是:<%=date %>
<%}
%>
</body>
</html>
<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=utf-8"pageEncoding="utf-8"%>
<%@ page import="java.net.URLEncoder" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>写入cookie</title>
</head>
<body>
<%request.setCharacterEncoding("utf-8");String user = URLEncoder.encode(request.getParameter("user"), "utf-8"); //获取用户名Cookie cookie = new Cookie("mrCookie", user+"#"+new Date().toLocaleString());cookie.setMaxAge(60 * 60 * 24 * 30); //设置cookie有效期30天response.addCookie(cookie); //保存cookie%>
<script type="text/javascript">window.location.href = "index.jsp"
</script>
</body>
</html>
使用request对象的相关方法获取客户端信息
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>使用request对象的相关方法获取客户端信息</title>
</head>
<body>
<br>客户提交信息的方式:<%=request.getMethod()%>
<br>使用的协议:<%=request.getProtocol()%>
<br>获取发出请求字符串的客户端地址:<%=request.getRequestURI()%>
<br>获取发出请求字符串的客户端地址:<%=request.getRequestURL()%>
<br>获取提交数据的客户端IP地址:<%=request.getRemoteAddr()%>
<br>获取服务器端口号:<%=request.getServerPort()%>
<br>获取服务器的名称:<%=request.getServerName()%>
<br>获取客户端的主机名:<%=request.getRemoteHost()%>
<br>获取客户端所请求的脚本文件的文件路径:<%=request.getServletPath()%>
<br>获得Http协议定义的文件头信息Host的值:<%=request.getHeader("host")%>
<br>获得Http协议定义的文件头信息User-Agent的值:<%=request.getHeader("user-agent")%>
<br>获得Http协议定义的文件头信息accept-language的值:<%=request.getHeader("accept-language")%>
<br>获得请求文件的绝对路径:<%=request.getRealPath("index.jsp")%>
</body>
</html>
通过sendRedirect()方法重定向页面到用户登录页面
<%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>首页</title>
</head>
<body>
<%response.sendRedirect("login.jsp"); %>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=GB18030"pageEncoding="GB18030"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>用户登录页面</title>
</head>
<body>
<form name="form1" method="post" action="">
用户名: <input name="name" type="text" id="name" style="width: 120px"><br>
密 码: <input name="pwd" type="password" id="pwd" style="width: 120px"> <br>
<br>
<input type="submit" name="Submit" value="提交">
</form>
</body>
</html>
在index.jsp页面中,提供用户输入用户名文本框;在session.jsp页面中,将用户输入的用户名保存在session对象中,用户在该页面中可以添加最喜欢去的地方,在result.jsp页面中,显示用户输入的用户名与最想去的地方
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><base href="<%=basePath%>"><title>My JSP 'index.jsp' starting page</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="css/style.css"></head><body><form id="form1" name="form1" method="post" action="session.jsp"><div align="center"><table width="23%" border="0"><tr><td width="36%"><div align="center">您的名字是:</div></td><td width="64%"><label><div align="center"><input type="text" name="name" /></div></label></td></tr><tr><td colspan="2"><label><div align="center"><input type="submit" name="Submit" value="提交" /></div></label></td></tr></table>
</div>
</form></body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><base href="<%=basePath%>"><title>My JSP 'result.jsp' starting page</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="css/style.css"></head><body><div align="center"><%String name = (String)session.getAttribute("name"); //获取保存在session范围内的对象String solution = request.getParameter("address"); //获取用户输入的最想去的地方%>
<form id="form1" name="form1" method="post" action=""><table width="28%" border="0"><tr><td colspan="2"><div align="center"><strong>显示答案</strong></div> </td></tr><tr><td width="49%"><div align="left">您的名字是:</div></td><td width="51%"><label><div align="left"><%=name%></div> <!-- 将用户输入的用户名在页面中显示 --></label></td></tr><tr><td><label><div align="left">您最喜欢去的地方是:</div></label></td><td><div align="left"><%=solution%></div></td> <!-- 将用户输入的最想去的地方在页面中显示 --></tr></table>
</form><p> </p >
</div></body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><base href="<%=basePath%>"><title>My JSP 'session.jsp' starting page</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="css/style.css"></head><body><%String name = request.getParameter("name"); //获取用户填写的用户名session.setAttribute("name",name); //将用户名保存在session对象中%><div align="center"><form id="form1" name="form1" method="post" action="result.jsp"><table width="28%" border="0"><tr><td>您的名字是:</td><td><%=name%></td></tr><tr><td>您最喜欢去的地方是:</td><td><label><input type="text" name="address" /></label></td></tr><tr><td colspan="2"><label><div align="center"><input type="submit" name="Submit" value="提交" /></div></label></td></tr></table></form><p> </p >
</div></body>
</html>
在page指令中指定errorPage属性值为error.jsp,即指定显示异常信息页面,然后定义保存单价的request范围内的变量,并赋值为非数值型,最后获取变量并转换为float型
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" errorPage="error.jsp"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>使用exception对象获取异常信息</title>
</head>
<body>
<%
request.setAttribute("price","12.5元");//保存单价到request范围内的变量price中
float price=Float.parseFloat(request.getAttribute("price").toString()); //获取单价,并转换为float型
%>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8" isErrorPage="true"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>错误提示页</title>
</head>
<body>
错误提示为:<%=exception.getMessage() %>
</body>
</html>
JavaBean技术
通过非可视化的JavaBean,封装邮箱地址对象,通过JSP页面调用该对象来验证邮箱地址是否合法
package com.mingri;import java.io.Serializable;
/*** 邮件对象JavaBean* @author Li YongQiang*/
public class Email implements Serializable {// serialVersionUID 值private static final long serialVersionUID = 1L;// Email地址private String mailAdd;// 是否是一个标准的Email地址private boolean eamil;/*** 默认无参的构造方法*/public Email() {}/*** 构造方法* @param mailAdd Email地址*/public Email(String mailAdd) {this.mailAdd = mailAdd;}/*** 是否是一个标准的Email地址* @return 布尔值*/public boolean isEamil() {// 正则表达式,定义邮箱格式String regex = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"; // matches()方法可判断字符串是否与正则表达式匹配if (mailAdd.matches(regex)) { // eamil为真eamil = true;}// 返回eamilreturn eamil;}public String getMailAdd() {return mailAdd;}public void setMailAdd(String mailAdd) {this.mailAdd = mailAdd;}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body><form action="result.jsp" method="post"><table align="center" width="300" border="1" height="150"><tr><td colspan="2" align="center"><b>邮箱认证系统</b></td></tr><tr><td align="right">邮箱地址:</td><td><input type="text" name="mailAdd"/></td></tr><tr><td colspan="2" align="center"><input type="submit" /></td></tr></table></form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><%@page import="com.mingri.Email"%><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body><div align="center"><%// 获取邮箱地址String mailAdd = request.getParameter("mailAdd");// 实例化Email,并对mailAdd赋值Email email = new Email(mailAdd);// 判断是否是标准的邮箱地址if(email.isEamil()){out.print(mailAdd + " <br>是一个标准的邮箱地址!<br>");}else{out.print(mailAdd + " <br>不是一个标准的邮箱地址!<br>");}%>返回</div>
</body>
</html>
在JSP页面中显示JavaBean属性信息
package com.mingri;/*** 商品对象* @author Li YongQiang*/
public class Produce {// 商品名称private String name = "电吉他";// 商品价格private double price = 1880.5;// 数量private int count = 100;// 出厂地址private String factoryAdd = "吉林省长春市xxx琴行";public String getName() {return name;}public double getPrice() {return price;}public int getCount() {return count;}public String getFactoryAdd() {return factoryAdd;}
}
<%@ page language="java" contentType="text/html; charset=GB18030"pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title here</title>
</head>
<body><jsp:useBean id="produce" class="com.mingri.Produce"></jsp:useBean><div><ul><li>商品名称:<jsp:getProperty property="name" name="produce"/></li><li>价格:<jsp:getProperty property="price" name="produce"/></li><li>数量:<jsp:getProperty property="count" name="produce"/></li><li>厂址:<jsp:getProperty property="factoryAdd" name="produce"/></li></ul></div>
</body>
</html>
在类中提供属性及与属性相对应的get()方法与set()方法,在JSP页面中对JavaBean属性赋值并获取输出
package com.mingri;public class Produce {// 商品名称private String name ;// 商品价格private double price ;// 数量private int count ;// 出厂地址private String factoryAdd ;public String getName() {return name;}public void setName(String name) {this.name = name;}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;}public int getCount() {return count;}public void setCount(int count) {this.count = count;}public String getFactoryAdd() {return factoryAdd;}public void setFactoryAdd(String factoryAdd) {this.factoryAdd = factoryAdd;}
}
<%@ page language="java" contentType="text/html; charset=GB18030"pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title here</title>
</head>
<body><jsp:useBean id="produce" class="com.mingri.Produce"></jsp:useBean><jsp:setProperty property="name" name="produce" value="洗衣机"/><jsp:setProperty property="price" name="produce" value="8888.88"/><jsp:setProperty property="count" name="produce" value="88"/><jsp:setProperty property="factoryAdd" name="produce" value="广东省xxx公司"/><div><ul><li>商品名称:<jsp:getProperty property="name" name="produce"/></li><li>价格:<jsp:getProperty property="price" name="produce"/></li><li>数量:<jsp:getProperty property="count" name="produce"/></li><li>厂址:<jsp:getProperty property="factoryAdd" name="produce"/></li></ul></div>
</body>
</html>
实现档案管理系统,在其中录入用户信息功能,主要通过在JSP页面中应用JavaBean进行实现
package com.mingri;/*** 用户信息* @author Li YongQiang*/
public class Person {// 姓名private String name;// 年龄private int age;// 性别private String sex;// 住址private String add;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public String getAdd() {return add;}public void setAdd(String add) {this.add = add;}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body><form action="reg.jsp" method="post"><table align="center" width="400" height="200" border="1"><tr><td align="center" colspan="2" height="40"><b>添加用户信息</b></td></tr><tr><td align="right">姓 名:</td><td><input type="text" name="name"></td></tr><tr><td align="right">年 龄:</td><td><input type="text" name="age"></td></tr><tr><td align="right">性 别:</td><td><input type="text" name="sex"></td></tr><tr><td align="right">住 址:</td><td><input type="text" name="add"></td></tr><tr><td align="center" colspan="2"><input type="submit" value="添 加"></td></tr></table></form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body><%request.setCharacterEncoding("UTF-8");%><jsp:useBean id="person" class="com.mingri.Person" scope="page"><jsp:setProperty name="person" property="*"/></jsp:useBean><table align="center" width="400"><tr><td align="right">姓 名:</td><td><jsp:getProperty property="name" name="person"/></td></tr><tr><td align="right">年 龄:</td><td><jsp:getProperty property="age" name="person"/></td></tr><tr><td align="right">性 别:</td><td><jsp:getProperty property="sex" name="person"/></td></tr><tr><td align="right">住 址:</td><td><jsp:getProperty property="add" name="person"/></td></tr></table>
</body>
</html>
通过编写对字符转码的JavaBean,来解决在新闻发布会系统中,发布中文信息的乱码现象
package com.mingri;public class News {// 标题private String title;// 内容private String content;public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}
}
package com.mingri;import java.io.UnsupportedEncodingException;public class CharactorEncoding {/*** 构造方法*/public CharactorEncoding(){}/*** 对字符进行转码处理* @param str 要转码的字符串* @return 编码后的字符串*/public String toString(String str){// 转换字符String text = "";// 判断要转码的字符串是否有效if(str != null && !"".equals(str)){try {// 将字符串进行编码处理text = new String(str.getBytes("iso8859-1"),"GB18030");} catch (UnsupportedEncodingException e) {e.printStackTrace();}}// 返回后的字符串return text;}
}
<%@ page language="java" contentType="text/html; charset=GB18030"pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>XX新闻发布系统</title>
</head>
<body><form action="release.jsp" method="post"><table align="center" width="450" height="260" border="1"><tr><td align="center" colspan="2" height="40" ><b>新闻发布</b></td></tr><tr><td align="right">标 题:</td><td><input type="text" name="title" size="30"></td></tr><tr><td align="right">内 容:</td><td><textarea name="content" rows="8" cols="40"></textarea></td></tr><tr><td align="center" colspan="2"><input type="submit" value="发 布"></td></tr></table></form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=GB18030"pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>发布结果</title>
<style type="text/css">#container{width: 450px;border: solid 1px;padding: 20px;}#title{font-size: 16px;font-weight: bold;color: #3399FF;}#content{font-size: 12px;text-align: left;}
</style>
</head>
<body><jsp:useBean id="news" class="com.mingri.News"></jsp:useBean><jsp:useBean id="encoding" class="com.mingri.CharactorEncoding"></jsp:useBean><jsp:setProperty property="*" name="news"/><div align="center"><div id="container"><div id="title"><%= encoding.toString(news.getTitle())%></div><hr><div id="content"><%= encoding.toString(news.getContent())%></div></div></div>
</body>
</html>
创建获取当前时间的JavaBean对象,该对象既可以获取当日期,同时也可以获取今天是星期几
package com.mingri;import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/*** 获取当前时间的JavaBean* @author Li YongQiang* */
public class DateBean {// 日期及时间private String dateTime;// 星期private String week;// Calendar对象private Calendar calendar = Calendar.getInstance();/*** 获取当前日期及时间* @return 日期及时间的字符串*/public String getDateTime() {// 获取当前时间Date currDate = Calendar.getInstance().getTime();// 实例化SimpleDateFormatSimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH点mm分ss秒");// 格式化日期时间dateTime = sdf.format(currDate);// 返回日期及时间的字符串return dateTime;}/*** 获取星期几* @return 返回星期字符串*/public String getWeek() {// 定义数组String[] weeks = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };// 获取一星期的某天int index = calendar.get(Calendar.DAY_OF_WEEK);// 获取星期几week = weeks[index - 1];// 返回星期字符串return week;}
}
<%@ page language="java" contentType="text/html; charset=GB18030"pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>电子时钟</title>
<style type="text/css">#clock{width:420px;height:80px;background:#E0E0E0;font-size: 25px;font-weight: bold;border: solid 5px orange;padding: 20px;}#week{padding-top:15px;color: #0080FF;}
</style>
<meta http-equiv="Refresh" content="1">
</head>
<body><jsp:useBean id="date" class="com.mingri.DateBean" scope="application"></jsp:useBean><div align="center"><div id="clock"><div id="time"><jsp:getProperty property="dateTime" name="date"/></div><div id="week"><jsp:getProperty property="week" name="date"/></div></div></div>
</body>
</html>
创建将字符串转换成数组的JavaBean,实现对“问卷调查”表单中复选框的数值的处理
package com.mingri;import java.io.Serializable;public class Paper implements Serializable {private static final long serialVersionUID = 1L;// 编程语言private String[] languages;// 掌握技术private String[] technics;// 部分private String[] parts;public Paper(){}public String[] getLanguages() {return languages;}public void setLanguages(String[] languages) {this.languages = languages;}public String[] getTechnics() {return technics;}public void setTechnics(String[] technics) {this.technics = technics;}public String[] getParts() {return parts;}public void setParts(String[] parts) {this.parts = parts;}
}
package com.mingri;public class Convert {/*** 将数组转换成为字符串* @param arr 数组* @return 字符串*/public String arr2Str(String[] arr){// 实例化StringBufferStringBuffer sb = new StringBuffer();// 判断arr是否为有效数组if(arr != null && arr.length > 0){// 遍历数组for (String s : arr) {// 将字符串追加到StringBuffer中sb.append(s);// 将字符串追加到StringBuffer中sb.append(",");}// 判断字符串长度是否有效if(sb.length() > 0){// 截取字符sb = sb.deleteCharAt(sb.length() - 1);}}// 返回字符串return sb.toString();}
}
<%@ page language="java" contentType="text/html; charset=GB18030"pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>调查问卷</title>
</head><body><form action="reg.jsp" method="post"><div><h1>调查问卷</h1><hr/><ul><li>你经常用哪些编程语言开发程序:</li><li><input type="checkbox" name="languages" value="JAVA">JAVA<input type="checkbox" name="languages" value="PHP">PHP<input type="checkbox" name="languages" value=".NET">.NET<input type="checkbox" name="languages" value="VC++">VC++</li></ul><ul><li>你目前所掌握的技术:</li><li><input type="checkbox" name="technics" value="HTML">HTML<input type="checkbox" name="technics" value="JAVA BEAN">JAVA BEAN<input type="checkbox" name="technics" value="JSP">JSP<input type="checkbox" name="technics" value="SERVLET">SERVLET</li></ul><ul><li>在学习中哪一部分感觉有困难:</li><li><input type="checkbox" name="parts" value="JSP">JSP<input type="checkbox" name="parts" value="STRUTS">STRUTS</li></ul> <input type="submit" value="提 交"></div></form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=GB18030"pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>调查结果</title>
</head><body><jsp:useBean id="paper" class="com.mingri.Paper"></jsp:useBean><jsp:useBean id="convert" class="com.mingri.Convert"></jsp:useBean><jsp:setProperty property="*" name="paper"/><div><h1>调查结果</h1><hr/><ul><li>你经常使用的编程语言:<%= convert.arr2Str(paper.getLanguages()) %> 。</li><li>你目前所掌握的技术:<%= convert.arr2Str(paper.getTechnics()) %> 。</li><li>在学习中感觉有困难的部分:<%= convert.arr2Str(paper.getParts()) %> 。</li></ul></div>
</body>
</html>
Servlet技术
创建一个名称为TestServlet的Servlet
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestServlet extends HttpServlet {//初始化方法public void init() throws ServletException {}//处理HTTP Get请求public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {}//处理HTTP Post请求public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {}//处理HTTP Put请求public void doPut(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {}//处理HTTP Delete请求public void doDelete(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {}//销毁方法public void destroy() {super.destroy();}
}
创建一个Servlet,实现向客户端输出一个字符串
public class WordServlet implements Servlet {public void destroy() {// TODO Auto-generated method stub}public ServletConfig getServletConfig() {// TODO Auto-generated method stubreturn null;}public String getServletInfo() {// TODO Auto-generated method stubreturn null;}public void init(ServletConfig arg0) throws ServletException {// TODO Auto-generated method stub}public void service(ServletRequest request, ServletResponse response)throws ServletException, IOException {PrintWriter pwt = response.getWriter();pwt.println("mingrisoft");pwt.close();}
}
创建一个简易的Servlet计算器
package com.mingri;import java.io.IOException;
import java.io.PrintWriter;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;public class CalculateServlet extends HttpServlet {private static final long serialVersionUID = 7223778025721767631L;@Overridepublic void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html");response.setCharacterEncoding("GBK");PrintWriter out = response.getWriter();// 获取第一个数字double firstNum = Double.valueOf(request.getParameter("firstNum"));// 获取第一个数字double secondNum = Double.valueOf(request.getParameter("secendNum"));// 获取运算符String operator = request.getParameter("operator");// 计算结果double result = 0;// 判断运算符if("+".equals(operator)){result = firstNum + secondNum;}else if("-".equals(operator)){result = firstNum - secondNum;}else if("*".equals(operator)){result = firstNum * secondNum;}else if("/".equals(operator)){result = firstNum / secondNum;}// 输出计算结果out.print(firstNum + " " + operator + " " + secondNum + " = " + result);out.print("<br>返回");out.flush();out.close();}}
<%@ page language="java" contentType="text/html" pageEncoding="GBK"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><title>简易Servlet计算器</title><!--<link rel="stylesheet" type="text/css" href="styles.css">--><script type="text/javascript">function calc(form){with(form){if(firstNum.value == "" || secendNum.value == ""){alert("请输入数字!");return false;}if(isNaN(firstNum.value) || isNaN(secendNum.value)){alert("数字格式错误!");return false;}if(operator.value == "-1"){alert("请选择运算符!");return false;}}}</script></head><body><form action="CalculateServlet" method="post" onsubmit="return calc(this);"><table align="center" border="0"><tr><th>简易Servlet计算器</th></tr><tr><td><input type="text" name="firstNum"><select name="operator"><option value="-1">运算符</option><option value="+">+</option><option value="-">-</option><option value="*">*</option><option value="/">/</option></select><input type="text" name="secendNum"><input type="submit" value="计算"></td></tr></table></form></body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"><servlet><servlet-name>CalculateServlet</servlet-name><servlet-class>com.mingri.CalculateServlet</servlet-class></servlet><servlet-mapping><servlet-name>CalculateServlet</servlet-name><url-pattern>/CalculateServlet</url-pattern></servlet-mapping><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list>
</web-app>
过滤器和监听器
创建一个过滤器,实现网站访问计数器的功能,并在web.xml文件的配置中,将网站访问量的初始值设置5000
package com.mingri;import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;public class CountFilter implements Filter {// 来访数量private int count;@Overridepublic void init(FilterConfig filterConfig) throws ServletException {// 获取初始化参数String param = filterConfig.getInitParameter("count");// 将字符串转换为intcount = Integer.valueOf(param);}@Overridepublic void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {// 访问数量自增count ++;// 将ServletRequest转换成HttpServletRequestHttpServletRequest req = (HttpServletRequest) request;// 获取ServletContextServletContext context = req.getSession().getServletContext();// 将来访数量值放入到ServletContext中context.setAttribute("count", count);// 向下传递过滤器chain.doFilter(request, response);}@Overridepublic void destroy() {}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>人数统计</title>
</head>
<body><h2>欢迎光临,<br>您是本站的第【 <%=application.getAttribute("count") %>】位访客!</h2>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"id="WebApp_ID" version="2.5"><display-name>10.3</display-name><welcome-file-list><welcome-file>index.html</welcome-file><welcome-file>index.htm</welcome-file><welcome-file>index.jsp</welcome-file><welcome-file>default.html</welcome-file><welcome-file>default.htm</welcome-file><welcome-file>default.jsp</welcome-file></welcome-file-list><!-- 过滤器声明 --><filter><!-- 过滤器的名称 --><filter-name>CountFilter</filter-name><!-- 过滤器的完整类名 --><filter-class>com.mingri.CountFilter</filter-class><!-- 设置初始化参数 --><init-param><!-- 参数名 --><param-name>count</param-name><!-- 参数值 --><param-value>5000</param-value></init-param></filter><!-- 过滤器映射 --><filter-mapping><!-- 过滤器名称 --><filter-name>CountFilter</filter-name><!-- 过滤器URL映射 --><url-pattern>/index.jsp</url-pattern></filter-mapping>
</web-app>
实现图书信息的添加功能,并创建字符编码过滤器,避免中文乱码现象的产生
package com.mingri;import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
// 字符编码过滤器
public class CharactorFilter implements Filter {// 字符编码String encoding = null;@Overridepublic void destroy() {encoding = null;}@Overridepublic void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {// 判断字符编码是否为空if(encoding != null){// 设置request的编码格式request.setCharacterEncoding(encoding);// 设置response字符编码response.setContentType("text/html; charset="+encoding);}// 传递给下一过滤器chain.doFilter(request, response);}@Overridepublic void init(FilterConfig filterConfig) throws ServletException {// 获取初始化参数encoding = filterConfig.getInitParameter("encoding");}}
package com.mingri;import java.io.IOException;
import java.io.PrintWriter;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;/*** 添加图书信息的Servlet*/
public class AddServlet extends HttpServlet {private static final long serialVersionUID = 1L;// 处理GET请求protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}// 处理POST请求protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// 获取 PrintWriterPrintWriter out = response.getWriter();// 获取图书编号String id = request.getParameter("id");// 获取名称String name = request.getParameter("name");// 获取作者String author = request.getParameter("author");// 获取价格String price = request.getParameter("price");// 输出图书信息out.print("<h2>图书信息添加成功</h2><hr>");out.print("图书编号:" + id + "<br>");out.print("图书名称:" + name + "<br>");out.print("作者:" + author + "<br>");out.print("价格:" + price + "<br>");// 刷新流out.flush();// 关闭流out.close();}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>添加图书信息</title>
</head>
<body><form action="AddServlet" method="post"><table align="center" border="1" width="350"><tr><td class="2" align="center" colspan="2"><h2>添加图书信息</h2></td></tr><tr><td align="right">图书编号:</td><td><input type="text" name="id"></td></tr><tr><td align="right">图书名称:</td><td><input type="text" name="name"></td></tr><tr><td align="right">作 者:</td><td><input type="text" name="author"></td></tr><tr><td align="right">价 格:</td><td><input type="text" name="price"></td></tr><tr><td class="2" align="center" colspan="2"><input type="submit" value="添 加"></td></tr></table></form>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"id="WebApp_ID" version="2.5"><display-name>10.3</display-name><welcome-file-list><welcome-file>index.html</welcome-file><welcome-file>index.htm</welcome-file><welcome-file>index.jsp</welcome-file><welcome-file>default.html</welcome-file><welcome-file>default.htm</welcome-file><welcome-file>default.jsp</welcome-file></welcome-file-list><!-- 声明过滤器 -->
<filter><!-- 过滤器名称 --><filter-name>CharactorFilter</filter-name><!-- 过滤器的完整类名 --><filter-class>com.mingri.CharactorFilter</filter-class><!-- 初始化参数 --><init-param><!-- 参数名 --><param-name>encoding</param-name><!-- 参数值 --><param-value>UTF-8</param-value></init-param>
</filter>
<!-- 过滤器映射 -->
<filter-mapping><!-- 过滤器名称 --><filter-name>CharactorFilter</filter-name><!-- URL映射 --><url-pattern>/*</url-pattern>
</filter-mapping><!-- 声明Servlet --><servlet><!-- Servlet名称 --><servlet-name>AddServlet</servlet-name><!-- Servlet完整类名 --><servlet-class>com.mingri.AddServlet</servlet-class></servlet><!-- Servlet映射 --><servlet-mapping><!-- Servlet名称 --><servlet-name>AddServlet</servlet-name><!-- URL映射 --><url-pattern>/AddServlet</url-pattern></servlet-mapping>
</web-app>
应用Servlet监听器统计在线人数
<%@ page contentType="text/html; charset=UTF-8" language="java" import="java.sql.*" errorPage="" %>
<%@ page import="java.util.*"%>
<%@ page import="com.mingri.*"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>使用监听查看在线用户</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
</head>
<%
UserInfoList list=UserInfoList.getInstance();
UserInfoTrace ut=new UserInfoTrace();
String name=request.getParameter("user");
ut.setUser(name);
session.setAttribute("list",ut);
list.addUserInfo(ut.getUser());
session.setMaxInactiveInterval(10);
%>
<body>
<div align="center"><table width="506" height="246" border="0" cellpadding="0" cellspacing="0" background="image/background2.jpg"><tr><td align="center"><br><textarea rows="8" cols="20">
<%
Vector vector=list.getList();
if(vector!=null&&vector.size()>0){
for(int i=0;i<vector.size();i++){out.println(vector.elementAt(i));
}
}
%>
</textarea><br><br>返回</td></tr>
</table>
</div>
</body>
</html>
package com.mingri;import java.util.*;public class UserInfoList {private static UserInfoList user = new UserInfoList();private Vector vector = null;/*利用private调用构造函数,防止被外界产生新的instance对象*/public UserInfoList() {this.vector = new Vector();}/*外界使用的instance对象*/public static UserInfoList getInstance() {return user;}/*增加用户*/public boolean addUserInfo(String user) {if (user != null) {this.vector.add(user);return true;} else {return false;}}/*获取用户列表*/public Vector getList() {return vector;}/*移除用户*/public void removeUserInfo(String user) {if (user != null) {vector.removeElement(user);}}}
package com.mingri;import javax.servlet.http.HttpSessionBindingEvent;public class UserInfoTrace implements javax.servlet.http.HttpSessionBindingListener {private String user;private UserInfoList container = UserInfoList.getInstance();public UserInfoTrace() {user = "";}public void setUser(String user) {this.user = user;}public String getUser() {return this.user;}public void valueBound(HttpSessionBindingEvent arg0) {System.out.println("上线" + this.user);}public void valueUnbound(HttpSessionBindingEvent arg0) {System.out.println("下线" + this.user);if (user != "") {container.removeUserInfo(user);}}}