JSP语言基础(案例代码)

news2024/11/26 9:38:50

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

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1493068.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

ECMAScript6

课程链接 目录 相关介绍什么是ECMA什么是ECMAScript为什么学习ES6 letconst变量解构赋值模板字符串对象简化写法箭头函数函数参数的默认值rest参数扩展运算符Symbol迭代器生成器函数与调用Promise介绍与基本用法Promise封装读取文件Promise.prototype...then方法Promise.catch…

javascript中的强制类型转换和自动类型转换

✨✨ 欢迎大家来到景天科技苑✨✨ &#x1f388;&#x1f388; 养成好习惯&#xff0c;先赞后看哦~&#x1f388;&#x1f388; 所属专栏&#xff1a;前端泛海 景天的主页&#xff1a;景天科技苑 文章目录 1.转换函数2.强制类型转换&#xff08;1&#xff09;Number类型强转&…

数字社交时代的引领者:Facebook的元宇宙探索

引言&#xff1a; 在当今数字社交时代&#xff0c;人们的社交方式正在经历着翻天覆地的变化。随着虚拟现实技术的不断发展和元宇宙概念的崛起&#xff0c;社交网络正朝着一个全新的未来迈进。作为全球最大的社交网络平台之一&#xff0c;Facebook正在积极探索元宇宙时代的社交…

串联谐振电路基础知识1

电路图 公式 IU/Zin,其中ZinXLXCR XC&#xff1a;表示为容抗 XL&#xff1a;表示为感抗 R&#xff1a;表示为电阻阻值 特性 电感对越是高频的电流的阻力就会越大&#xff0c;对越是低频的电流的阻力就会越小&#xff0c;感抗的大小是与频率是息息相关的&#xff0c;并且可简单…

Spring事务管理与模板对象

1.事务管理 1.事务回顾 事务指数据库中多个操作合并在一起形成的操作序列 事务的作用 当数据库操作序列中个别操作失败时&#xff0c;提供一种方式使数据库状态恢复到正常状态&#xff08;A&#xff09;&#xff0c;保障数据库即使在异常状态下仍能保持数据一致性&#xff…

时钟显示 html JavaScript

sf.html <!DOCTYPE html> <html><head><meta charset"UTF-8"><title>时间</title><script>function showTime(){var timenew Date();var datetime.getDate();var yeartime.getFullYear();var monthtime.getMonth()1;var …

DataGrip 连接 Centos MySql失败

首先检查Mysql是否运行&#xff1a; systemctl status mysqld &#xff0c; 如果显示没有启动则需要启动mysql 检查防火墙是否打开&#xff0c;是否打开3306的端口 sudo firewall-cmd --list-all 如果下面3306没有打开则打开3306端口 publictarget: defaulticmp-block-inver…

推荐书籍《低代码平台开发实践:基于React》—— 提升开发效率,构建优质应用

写在前面 随着数字化转型的深入&#xff0c;企业对应用开发效率和灵活性的要求不断提高。低代码平台作为新兴的软件开发方式&#xff0c;通过可视化界面和预构建组件&#xff0c;极大简化了应用开发流程&#xff0c;降低了技术门槛。基于React的低代码平台以其组件化、响应式和…

解决MySQL 5.7在Redhat 9中启动报错:libncurses.so.5和libtinfo.so.5缺失问题

在使用Linux系统搭建MySQL数据库的过程中&#xff0c;我们往往会遇到各种依赖库的问题&#xff0c;尤其是在安装较旧版本的MySQL时。最近&#xff0c;在RedHat 9&#xff08;rocky linux 9&#xff09;系统上安装MySQL 5.7版本时&#xff0c;我遇到了一个典型的依赖库缺失错误&…

动态规划(算法竞赛、蓝桥杯)--状态压缩DP蒙德里安的梦想

1、B站视频链接&#xff1a;E31 状态压缩DP 蒙德里安的梦想_哔哩哔哩_bilibili #include <bits/stdc.h> using namespace std; const int N12,M1<<N; bool st[N];//st[i]存储合并列的状态i是否合法 long long f[N][M];//f[i][j]表示摆放第i列&#xff0c;状态为…

常用“树”数据结构

哈夫曼树 在许多应用中&#xff0c;树中结点常常被赋予一个表示某种意义的数值&#xff0c;称为该结点的权。从树的根到任意结点的路径长度(经过的边数)与该结点上权值的乘积&#xff0c;称为该结点的带权路径长度。树中所有叶结点的带权路径长度之和称为该树的带权路径长度&am…

有没有无损格式转换mp3的方法?

随着数字音乐的发展&#xff0c;无损音乐格式如FLAC、APE、WAV等越来越受到音乐爱好者的青睐。无损音乐保证了音乐在传输和存储过程中不损失任何原始信息&#xff0c;从而保留了音乐的原汁原味。但有时&#xff0c;出于设备兼容性、空间节省或其他原因&#xff0c;我们可能需要…

C语言项目实战——贪吃蛇

C语言实现贪吃蛇 前言一、 游戏背景二、游戏效果演示三、课程目标四、项目定位五、技术要点六、Win32 API介绍6.1 Win32 API6.2 控制台程序6.3 控制台屏幕上的坐标COORD6.4 GetStdHandle6.5 GetConsoleCursorInfo6.5.1 CONSOLE_CURSOR_INFO 6.6 SetConsoleCursorInfo6.7 SetCon…

Ubuntu/Linux系统下Redis的基本操作命令

版本查询 redis-server --version # 或者redis-server -v 如上图所示&#xff0c;redis-server的版本为6.0.9,证明redis已经安装完成。 启动Redis服务 启动命令如下&#xff1a; redis-server启动成功如下所示&#xff1a; 启动过程中遇到如下问题时&#xff0c;杀死指定端…

Python Web开发记录 Day6:MySQL(关系型数据库)

名人说&#xff1a;莫道桑榆晚&#xff0c;为霞尚满天。——刘禹锡&#xff08;刘梦得&#xff0c;诗豪&#xff09; 创作者&#xff1a;Code_流苏(CSDN)&#xff08;一个喜欢古诗词和编程的Coder&#x1f60a;&#xff09; 目录 六、MySQL1、MySQL-概述和引入①MySQL是什么&am…

阿里云几核服务器够用?内存多少合适?

阿里云服务器配置怎么选择&#xff1f;CPU内存、公网带宽和系统盘怎么选择&#xff1f;个人开发者或中小企业选择轻量应用服务器、ECS经济型e实例&#xff0c;企业用户选择ECS通用算力型u1云服务器、ECS计算型c7、通用型g7云服务器&#xff0c;阿里云服务器网aliyunfuwuqi.com整…

【论文精读】Mask R-CNN

摘要 基于Faster RCNN&#xff0c;做出如下改变&#xff1a; 添加了用于预测每个感兴趣区域(RoI)上的分割掩码分支&#xff0c;与用于分类和边界框回归的分支并行。mask分支是一个应用于每个RoI的FCN&#xff0c;以像素到像素的方式预测分割掩码&#xff0c;只增加了很小的计…

倒计时34天

L2-1 堆宝塔 - B107 2023级选拔春季开学测重现 (pintia.cn) #include<bits/stdc.h> using namespace std; //#define int long long const int N2e56; const int inf0x3f3f3f3f; const double piacos(-1.0); vector<int>ve1,ve2; vector<vector<int> >…

推荐一个数据库脚本在线转换网站

由于各种数据库系统的功能、性能有差异&#xff0c;往往不同的项目会选用不同的数据库系统。同时&#xff0c;由于sql语法之间存在细微的差异&#xff0c;之前项目的脚本&#xff0c;就需要修改&#xff0c;并重新进行调试。鉴于这个出发点向大家推荐一个sql脚本转换的在线网站…

STM32 | 零基础 STM32 第一天

零基础 STM32 第一天 一、认知STM32 1、STM32概念 STM32:意法半导体基于ARM公司的Cortex-M内核开发的32位的高性能、低功耗单片机。 ST:意法半导体 M:基于ARM公司的Cortex-M内核的高性能、低功耗单片机 32&#xff1a;32位单片机 2、STM32开发的产品 STM32开发的产品&a…