JSP语言基础(案例代码)

 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>

5267b556194446498fc9c192544878c0.png

 

应用include指令包含网站Banner和版权信息栏

<%@ page pageEncoding="GB18030"%>
<img src="images/banner.JPG">
<%@ page pageEncoding="GB18030"%>
<%
String copyright="&nbsp;ALL Copyright &copy;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>&nbsp;</td>
  	</tr>
</table>
<%@ include file="copyright.jsp"%>
</body>
</html>

bee11444da2a43afa753b20892adb5af.png

应用<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>&nbsp;</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>
密&nbsp;&nbsp;码: <input name="pwd" type="password" id="pwd" style="width: 120px"> <br>
<br>
<input type="submit" name="Submit" value="提交">
</form>
</body>
</html>

8a8eb1f8b1164eb2955b2044067b0cf7.png

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>

43d671124cc94387bf73fc8320766415.png

使用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>

78800d88d6ea469cb581bb788861dd4d.png

通过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对象的名称为mrCookie
				user = 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>

2826a1674ac04bbd81eab1f692fc44ee.png

977439611dc247618621e93d56f6e0c6.png

使用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>
密&nbsp;&nbsp;码: <input name="pwd" type="password" id="pwd" style="width: 120px"> <br>
<br>
<input type="submit" name="Submit" value="提交">
</form>
</body>
</html>

c663a96256624bed84753770f5083270.png

在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>&nbsp;</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>&nbsp;</p >
</div>
  </body>
</html>

1650cabf0a974219ba94bbe520d2e2fe.png

在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>

bc01f95ca05547c0b342758dbc5bca3b.png

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;
		}
		// 返回eamil
		return 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>

fc3eea7789e54857bcb13dfc8ed3ee71.png

92f1c32fa7b24d4a8ebb591b8f11ff33.png

28707ad8e05841909d4a1b0cde52545d.png

 

在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>

b8ab130aafbe48d097b40d7f43ce2ecb.png

在类中提供属性及与属性相对应的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>

a87fcb39f08747599ca7f6273cb90d94.png

实现档案管理系统,在其中录入用户信息功能,主要通过在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>

d6df3cb49e2142d698d2ff459694b03b.png

cc1ed8d730784d3aa0ea6a454713b8b0.png

 

通过编写对字符转码的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>

d28104ca67c9474198df4ce84d13682f.png

69f041c996624011b4a8603bc623068e.png

创建获取当前时间的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();
		// 实例化SimpleDateFormat
		SimpleDateFormat 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>

f73a9ff3ae2e46e7858a403baf3218e1.png

 

创建将字符串转换成数组的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){
		// 实例化StringBuffer
		StringBuffer 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>
			&nbsp;&nbsp;&nbsp;&nbsp;<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>

282522ea97c54a1b926c3c5fde1e7467.png

93a7ca88c28c4c02a3587838d264da72.png

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 stub
		return null;
	}
	public String getServletInfo() {
		// TODO Auto-generated method stub
		return 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;

	@Override
	public 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>

1570b1ef2bd544858dd5067a76e80c5a.png

367a5bdb29884e73a15d83a88384b0b2.png

过滤器和监听器

创建一个过滤器,实现网站访问计数器的功能,并在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;
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// 获取初始化参数
		String param = filterConfig.getInitParameter("count");
		// 将字符串转换为int
		count = Integer.valueOf(param);
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// 访问数量自增
		count ++;
		// 将ServletRequest转换成HttpServletRequest
		HttpServletRequest req = (HttpServletRequest) request;
		// 获取ServletContext
		ServletContext context = req.getSession().getServletContext();
		// 将来访数量值放入到ServletContext中
		context.setAttribute("count", count);
		// 向下传递过滤器
		chain.doFilter(request, response);
	}

	@Override
	public 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>

49ad096e96474046974f3e1fd811b234.png

实现图书信息的添加功能,并创建字符编码过滤器,避免中文乱码现象的产生

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;
	@Override
	public void destroy() {
		encoding = null;
	}

	@Override
	public 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);
	}

	@Override
	public 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 {
		// 获取 PrintWriter
		PrintWriter 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>

a7030e2bcdfa4239a8b5670e346cbe12.png

4ea5aea541e544e5869682041f773e29.png

 

应用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);
    }
  }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

顺序如下: 1、多种字体大小显示 2、c:out标记输出 3、获取当前时间 4、include包含语句 5、建立错误处理页面的范例程序 6、jsp:forward 7、简单计数器 8、设置页面属性 9、使用GB2312编码 10、使用Big5编码 11、c:catch的用法 12、 begin、end和step的用法 13 、 循环 14、 varStatus 的四种属性 15、 的用法 16、从客户端传送数据至服务端 17、使用Unicode转义字符 18、使用朝鲜语字符集 19、JSP中最简单的国际化程序 20、错误检测 21、抛出异常 22、 的用法 23、和 的用法 24、 的用法 25、jsp-include的用法 26、汉字处理 27、网页重定向 28、自动更新网页 29、存取session 30、 的用法 31、单选型列表框 32、jsp文件中定义类 33、取得 JSP Container 版本 34、javax.servlet.jsp.JspWriter - out 对象 35、page 隐含对象 36、application 对象 37、PageContext 对象 38、Page范围 - pageContext 39、测试要显示的中文 40、IF控制符的操作 41、HttpServletRequest 接口所提供的方法 42、 网上测验 43、HttpSession - session 对象 44、 多选型列表框 45、解决浏览器 cache 的问题 46、使用 EL、JSTL 处理表单数据 47、 EL隐含对象 param、paramValues 48、EL隐含对象 pageContext 49、EL算术运算符 50、EL关系运算符 51、EL的运算符 52、选择钮的使用 53、检查框的使用 54、群组检查框的使用 55、数字、货币、百分数格式化 56、日期格式化 57、JSTL设置语言地区 58、Cookie数据的存取 59、session有效时间的设置与取得 60、session时间与ID 61、Cookie有效时间的设置 62、利用隐藏字段传送数据 63、JSP 使用 JavaBean 的方法 64、JSP 使用 JavaBean 65、范围为 Page 的 JavaBean范例程序 66、范围为 Request的 JavaBean 67、范围为 Session 的 JavaBean 68、范围为 Application 的 JavaBean 69、删除 JavaBean 70、url重组 71、Switch语句 72、环境变量 73、forward重定向 74、文件的建立与删除 75、取得文件属性 76、取得目录中的文件 77、目录的建立与删除 78、自Cookie存取日期/时间数据 79、管理Session变量 80、数据库中的记录数与记录指针位置 81、利用absolute方法设置记录位置 82、使用jsp指令生成Word文档 83、JSP网页模板 84、判断是否空白文件 85、cookie 用户登录次数 86、获取用户的真实IP地址 87、获取用户的浏览器信息 88、在客户端进行数据检查 89、在JSP中获取当前绝对路径 90、读取表单中所有参数 91、分行写入数据 92、显示请求URL 93、判断session是否过期 94、参数式查询数据库 95、取得数据库中各栏名称 96、使用JavaBean、设置和获取Bean的属性 97、设置Bean的一个属性与输入参数关联 98、实现基于数据库的站内搜索 99、DOM读取XML文档 100、SAX读取XML文档
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Auc23

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值