省市联动案例(jsp、ajax、sax解析)

CityPro.jsp

<%@ page language=”java” import=”java.util.*” pageEncoding=”UTF-8″%>
<%@ taglib prefix=”c” uri = “http://java.sun.com/jsp/jstl/core” %>
<!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>
<script type=”text/javascript”>
function createXMLHttpRequest() {
try {
return new XMLHttpRequest();//大多数浏览器
} catch (e) {
try {
return ActvieXObject(“Msxml2.XMLHTTP”);//IE6.0
} catch (e) {
try {
return ActvieXObject(“Microsoft.XMLHTTP”);//IE5.5及更早版本
} catch (e) {
alert(“哥们儿,您用的是什么浏览器啊?”);
throw e;
}
}
}
}
/*
 * 1. 在文档加载完毕时发送请求,得到所有省份名称,显示在<select name=”province”/>中
 * 2. 在选择了新的省份时,发送请求(参数为省名称),得到xml文档,即<province>元素
 *   解析xml文档,得到其中所有的<city>,再得到每个<city>元素的内容,即市名,使用市名生成<option>,插入到<select name=”city”>元素中
 */
window.onload = function() {
/*
ajax四步,请求ProvinceServlet,得到所有省份名称
使用每个省份名称创建一个<option>元素,添加到<select name=”province”>中
*/
var xmlHttp = createXMLHttpRequest();
xmlHttp.open(“GET”, “<c:url value=’/ProvinceServlet’/>”, true);
xmlHttp.send(null);
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
// 获取服务器的响应
var text = xmlHttp.responseText;
// 使用逗号分隔它,得到数组
var arr = text.split(“,”);
// 循环遍历每个省份名称,每个名称生成一个option对象,添加到<select>中
for(var i = 0; i < arr.length; i++) {
var op = document.createElement(“option”);//创建一个指名名称元素
op.value = arr[i];//设置op的实际值为当前的省份名称
var textNode = document.createTextNode(arr[i]);//创建文本节点
op.appendChild(textNode);//把文本子节点添加到op元素中,指定其显示值
document.getElementById(“p”).appendChild(op);
}
}
};
/*
第二件事情:给<select name=”province”>添加改变监听
使用选择的省份名称请求CityServlet,得到<province>元素(xml元素)!!!
获取<province>元素中所有的<city>元素,遍历之!获取每个<city>的文本内容,即市名称
使用每个市名称创建<option>元素添加到<select name=”city”>
*/
var proSelect = document.getElementById(“p”);
proSelect.onchange = function() {
var xmlHttp = createXMLHttpRequest();
xmlHttp.open(“POST”, “<c:url value=’/CityServlet’/>”, true);
xmlHttp.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded”);
xmlHttp.send(“pname=” + proSelect.value);//把下拉列表中选择的值发送给服务器!
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
/*
把select中的所有option移除(除了请选择)
*/
var citySelect = document.getElementById(“c”);
// 获取其所有子元素
var optionEleList = citySelect.getElementsByTagName(“option”);
// 循环遍历每个option元素,然后在citySelect中移除
while(optionEleList.length > 1) {//子元素的个数如果大于1就循环,等于1就不循环了!
citySelect.removeChild(optionEleList[1]);//总是删除1下标,因为1删除了,2就变成1了!
}
var doc = xmlHttp.responseXML;
// 得到所有名为city的元素
var cityEleList = doc.getElementsByTagName(“city”);
// 循环遍历每个city元素
for(var i = 0; i < cityEleList.length; i++) {
var cityEle = cityEleList[i];//得到每个city元素
var cityName;
// 获取市名称
if(window.addEventListener) {//处理浏览器的差异
cityName = cityEle.textContent;//支持FireFox等浏览器
} else {
cityName = cityEle.text;//支持IE
}
// 使用市名称创建option元素,添加到<select name=”city”>中
var op = document.createElement(“option”);
op.value = cityName;
// 创建文本节点
var textNode = document.createTextNode(cityName);
op.appendChild(textNode);//把文本节点追加到op元素中
//把op添加到<select>元素中
citySelect.appendChild(op);
}
}
};
};
};
</script>
  </head>
  <body>
<h1>省市联动</h1>
<select name=”province” id=”p”>
  <option>===请选择省===</option>
</select>
<select name=”city” id=”c”>
  <option>===请选择市===</option>
</select>
  </body>
</html>

ProvinceServlet.java

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;
/**
 * Servlet implementation class ProvinceServlet
 */
@WebServlet(“/ProvinceServlet”)
public class ProvinceServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(“text/html;charset=utf-8”);
/*
* 响应所有省份名称,使用逗号分隔!
*/
/*
* 1. Document对象
*   * 创建解析器对象
*   * 调用解析器的读方法,传递一个流对象,得到Document
*/
try {
SAXReader reader = new SAXReader();
InputStream input = this.getClass().getResourceAsStream(“/china.xml”);
Document doc = reader.read(input);
/*
* 查询所有province的name属性,得到一堆的属性对象
* 循环遍历,把所有的属性值连接成一个字符串,发送给客户端
*/
List<Attribute> arrList = doc.selectNodes(“//province/@name”);
StringBuilder sb = new StringBuilder();
for(int i = 0; i < arrList.size(); i++) {
sb.append(arrList.get(i).getValue());//把每个属性的值存放到sb中。
if(i < arrList.size() – 1) {
sb.append(“,”);
}
}
response.getWriter().print(sb);
} catch(Exception e) {
throw new RuntimeException(e);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}

CityServlet.java

import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
/**
 * Servlet implementation class CityServlet
 */
@WebServlet(“/CityServlet”)
public class CityServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding(“utf-8”);
response.setContentType(“text/xml;charset=utf-8”);//注意:发送xml这里要修改!!!
/*
* 获取省份名称,加载该省对应的<province>元素!
* 把元素转换成字符串发送给客户端
*/
/*
* 1. 获取省份的名称
* 2. 使用省份名称查找到对应的<province>元素
* 3. 把<province>元素转换成字符串,发送!
*/
try {
/*
* 得到Document
*/
SAXReader reader = new SAXReader();
InputStream input = this.getClass().getResourceAsStream(“/china.xml”);
Document doc = reader.read(input);
/*
* 获取参数
*/
String pname = request.getParameter(“pname”);//获取省份名称
Element proEle = (Element) doc.selectSingleNode(“//province[@name='” + pname + “‘]”);
String xmlStr = proEle.asXML();//把元素转换成字符串
response.getWriter().print(xmlStr);
} catch(Exception e) {
throw new RuntimeException(e);
}
}
}

JavaSwing实现简单的音乐播放停止

import java.applet.Applet;
import java.applet.AudioClip;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Ta extends JFrame{
public static void main(String[] args) {
new Ta();
}
private AudioClip audio;
int i=0;
public Ta() {
JButton jb1 = new JButton(“点击”);
this.audio = Applet.newAudioClip(Ta.class.getResource(“1.wav”));
this.audio.loop();
this.add(jb1);
jb1.addActionListener((e)->{
if(i%2==0)
{
this.audio.stop();
i++;
}
else
{
this.audio.loop();
i++;
}
});
this.setVisible(true);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.setSize(300, 300);
}
}

邮件发送

jsp代码:

<%@ 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=”/MailTest/mail” method=”post”>
邮件主题<input type=”text” name=”theme”></input>
邮件内容<input type=”text” name=”content”></input>
<br>附件<input type=”file” name=”file” />
<input type=”submit” value=”发送”/>
</form>
</body>
</html>

servlet代码:

import java.io.File;
import java.io.IOException;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.itcast.mail.AttachBean;
import cn.itcast.mail.Mail;
import cn.itcast.mail.MailUtils;
@WebServlet(“/mail”)
public class mail extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding(“utf-8”);
String theme = request.getParameter(“theme”);
String content = request.getParameter(“content”);
String file = request.getParameter(“file”);
System.out.println(file);
Session session = MailUtils.createSession(“smtp.163.com”, “发件人163邮箱帐号”, “邮箱密码”);
Mail mail = new Mail(“发件人的163邮箱”,”收件人的163邮箱”,theme,content);
AttachBean ab1 = new AttachBean(new File(file),file);
mail.addAttach(ab1);
try {
MailUtils.send(session, mail);
response.sendRedirect(“Mail.jsp”);
} catch (MessagingException e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}