JAVAWEB 版本音乐网站
一、实习目的
1)了解及学习HTML标准化语言同时学会使用tomcat6.0.
2)学会MySql数据库的安装并进行数据库,表以及其他的操作.
3)学会在MyEclipse8.5环境中完成Java Project的创建以及具体实现.
4)重点是使用Servlet以及JSP进行项目的设计.
5)了解JDBC以及连接的代码书写、JSP、同时学会JavaScript脚本的实现.
二、实训环境
开发环境:window xp 、jdk 6.0 、tomcat6.0
数据库: mysql5.5
开发工具:MyEclipse8.5 EidtPlus Navicat
使用技术: JDBC、DBCP、Servlet、JSP 、EL表达式 JavaScript、Ajax
实训周期:两周
三、 实习内容及要求
本次实习主要实现一个简单的音乐网站,其主要包括六大模块:
l 网站登录:用户名,密码,登录,登录失败显示信息,登录成功跳转音乐列表界面。
l 网站注册:用户名,密码,邮箱,性别,验证码。
l 网站音乐上传:可以上传mp3的格式的音乐,并对其他格式的文件进行限制.
l 音乐下载:可以下载mp3的格式的音乐,但其他的格式比如.exe不能下载。
l 音乐列表的显示:序号,歌曲名,歌手名,大小,试听,下载。
l 音乐的试听:进入下载界面后可以对上传音乐进行播放试听.
四、 实习内容及结果
1.实验时序图
2.程序代码
(1).连接数据库
package org.softeem.fileload;
import java.sql.*;
publicclass DBUtils {
private static final String USER="root";//数据库的账号
private static final String PASSWORD="123321";//密码 向下复制 ctrl+shift+下
private static final String URL="jdbc:mysql://localhost:3306/netmusic";//连接数据库的详细的地址
private static final String DRIVERCLASS="com.mysql.jdbc.Driver";//mysql数据驱动类的全路径
//注册驱动
static{
try {
Class.forName(DRIVERCLASS);//alt+shift+z
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//建立连接
publicstatic Connection getConnection() throws SQLException{
return DriverManager.getConnection(URL,USER,PASSWORD);
}
//关闭连接
publicstatic void close(Connection conn) throws SQLException{
if(conn!=null){
conn.close();
}
}
}
(2).下载功能
package org.softeem.fileload;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class DownLoad extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session=request.getSession();
if(session.getAttribute("account")==null){
Connection conn=null;
try {
conn=DBUtils.getConnection();//得到数据连接
Statement stat=conn.createStatement();//创建Statement对象
String sql="select * from t_song";//查询歌曲表中的所有歌曲的sql
ResultSet rs=stat.executeQuery(sql);//得到数据库返回的表中数据结果
List<Song> songList=new ArrayList<Song>();
while(rs.next()){//开一个while循环判断还有没有数据了
Song song=new Song();
song.setId(rs.getInt("id"));
song.setName( rs.getString("name"));
song.setSize(rs.getString("size"));
song.setSongger(rs.getString("songger"));
songList.add(song);
}
request.setAttribute("msg", "游客你好对不你需要登录好可以下载本网站的音乐");
;
request.setAttribute("songList", songList);//把歌曲数据撞到request对象中
request.getRequestDispatcher("../musicList.jsp")//跳转到歌曲列表页面中
.forward(request, response);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try{
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}else{
String songName=request.getParameter("name");//得到歌曲的名字
System.out.println(songName);
response.setCharacterEncoding("UTF-8");
String fname = new String(songName.getBytes("gbk"), "ISO8859-1");
System.out.println(fname);
response.setHeader("Content-Disposition", "attachment; filename=\"" + fname + "\".mp3");//服务器告诉浏览器以附件的形式打开该文件(下载)
FileInputStream fis=new FileInputStream("C:/Tomcat6.0/webapps/load/music/"+songName+".mp3");//ctrl +shift +o
BufferedInputStream bis=new BufferedInputStream(fis);//使用BufferedInputStream 提高文件的读取的效率
OutputStream os=response.getOutputStream();//创建一个基于服务器响应的文件输出流
BufferedOutputStream bos=new BufferedOutputStream(os);//使用BufferedOutputStream 提高文件写的效率
int temp=0;//定义个临时变量把每次读取到字节装到该临时变量中
while((temp=bis.read())!=-1){//开一个while循环一个一个的读取字节如果读取到文件的末尾temp的值=-1
bos.write(temp);
}
bis.close();//流是一种资源使用完毕以后需要关闭 关闭输入流
bos.close();//关闭输出流
}
}
}
(3),上传功能
package org.softeem.fileload;
import java.sql.*;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUpload extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
DiskFileItemFactory dif=new DiskFileItemFactory();
ServletFileUpload sfu=new ServletFileUpload(dif);
sfu.setHeaderEncoding("utf-8");//解决接受文件中文乱码问题
File file=null;
try {
List<FileItem> fileItemList=sfu.parseRequest(request);
for(FileItem fileitem:fileItemList){
if(fileitem.isFormField()){
}else{
//上传的歌曲要放到tomcat的发布的项目的制定的位置上
//C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\load\music
String fileName=fileitem.getName();//得到文件名
String[] fs=fileName.split("\\\\");
fileName=fs[fs.length-1];//得到不带文件路径的文件名 针对于IE浏览器
//真正在做企业开发的时候路径是不能这样写死的导致项目失去了扩展性增大了后期的维护难度
file=new File("C://Tomcat6.0/webapps/load/music/"+fileName);
fileitem.write(file);
//文件上传成功
// 歌手的名字 歌曲名 文件的大小 mp3 wav 两种两种文件格式
// 两只蝴蝶.mp3
String songName=fileName.split("\\.")[0];
Long size=fileitem.getSize();//得到歌曲的大小B
double dSize=size/(1024D*1024D);
System.out.println("大小:"+dSize);
String songSize=String.valueOf(dSize);//把整型转换成字符串 歌曲的大小
songSize=songSize.substring(0, 4);
System.out.println("大小:"+dSize);
String songger="";//歌手名稍后获取
Connection conn=null;
try{
conn=DBUtils.getConnection();//得到数据库的链接
Statement stat=conn.createStatement();//Statement向数据发送并执行sql语句的对象
String sql="insert into t_song(name,songger,size) " +
" values('"+songName+"','"+songger+"','"+songSize+"')";
int flag=stat.executeUpdate(sql);
if(flag>0){
request.setAttribute("msg", "恭喜你上传音乐成功");
request.getRequestDispatcher("../index.jsp").forward(request, response);
}else{
//如果数据库保存音乐信息是失败了要把上传成功的音乐删除掉
if(file.exists()){
file.delete();
}
request.setAttribute("msg", "对不起上传音乐失败");
request.getRequestDispatcher("../index.jsp").forward(request, response);
}
}catch(SQLException se){
se.printStackTrace();
System.out.println("出错了~~~~~~~~~~~~~~~~~");
if(file.exists()){
file.delete();
}
request.setAttribute("msg", "对不起上传音乐失败");
request.getRequestDispatcher("../index.jsp").forward(request, response);
}finally{
DBUtils.close(conn);
}
}
}
} catch (FileUploadException e) {
if(file.exists()){//判断文件是否存在如果存在近if语句
file.delete();//删除存在的文件
}
request.setAttribute("msg","对不起伤处音乐失败");
request.getRequestDispatcher("../index.jsp").forward(request, response);
System.out.println("如果进到此处说明上传失败");
e.printStackTrace();
} catch (Exception e) {
if(file.exists()){//判断文件是否存在如果存在近if语句
file.delete();//删除存在的文件
}
request.setAttribute("msg", "对不起上传音乐失败");
request.getRequestDispatcher("../index.jsp").forward(request, response);
e.printStackTrace();
}
}
}
(4),登录功能
package org.softeem.fileload;
import java.sql.*;
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;
import javax.servlet.http.HttpSession;
public class loginServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String account=request.getParameter("account");
String password=request.getParameter("password");
Connection conn=null;
try{
conn=DBUtils.getConnection();
Statement stat=conn.createStatement();
String sql="select * from t_user where account='"+account+"'and password='"+password+"'";
ResultSet rs=stat.executeQuery(sql);
HttpSession session=request.getSession(true);
if(rs.next()){
session.setAttribute("account", account);
request.getRequestDispatcher("../index.jsp").forward(request, response);
}else{
request.setAttribute("msg", "账号或密码不正确");
request.getRequestDispatcher("../login.jsp").forward(request, response);
}
}catch(SQLException e){
e.printStackTrace();
}finally{
try{
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
}
(6)上传音乐列表
package org.softeem.fileload;
import java.sql.*;
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;
import java.util.*;
public class MusicList extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//该类的作用就是把t_song表中的所有的歌曲都现在歌曲列表页面中
Connection conn=null;
try {
conn=DBUtils.getConnection();//得到数据连接
Statement stat=conn.createStatement();//创建Statement对象
String sql="select * from t_song";//查询歌曲表中的所有歌曲的sql
ResultSet rs=stat.executeQuery(sql);//得到数据库返回的表中数据结果
List<Song> songList=new ArrayList<Song>();
while(rs.next()){//开一个while循环判断还有没有数据了
Song song=new Song();
song.setId(rs.getInt("id"));
song.setName( rs.getString("name"));
song.setSize(rs.getString("size"));
song.setSongger(rs.getString("songger"));
songList.add(song);
}
System.out.println(songList);
request.setAttribute("songList", songList);//把歌曲数据撞到request对象中
request.getRequestDispatcher("../musicList.jsp")//跳转到歌曲列表页面中
.forward(request, response);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try{
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
}
(7)登录功能
package org.softeem.fileload;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class registaction extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String account=request.getParameter("account");
String password=request.getParameter("password");
try {
Connection conn=DBUtils.getConnection();
Statement stat=conn.createStatement();
ResultSet rs=stat.executeQuery("select * from t_user where account='"+account+"'");
if(rs.next()){
request.setAttribute("message","对不起该账号已存在请更换");
request.getRequestDispatcher("../regist.jsp").forward(request, response);
}else{
int rows=stat.executeUpdate("INSERT INTO t_user " +
" (account,password)VALUES('"+account+"','"+password+"')");
if(rows>0){
request.setAttribute("message", "ok");
request.getRequestDispatcher("../login.jsp").forward(request,response);
}
else {
request.setAttribute("message", "no");
request.getRequestDispatcher("../regist.jsp").forward(request,response);
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
(8)歌曲列表
package org.softeem.fileload;
publicclass Song {
private int id;
private String songger;
private String name;
private String size;
publicint getId() {
return id;
}
publicvoid setId(int id) {
this.id = id;
}
public String getSongger() {
return songger;
}
publicvoid setSongger(String songger) {
this.songger = songger;
}
public String getName() {
return name;
}
publicvoid setName(String name) {
this.name = name;
}
public String getSize() {
return size;
}
publicvoid setSize(String size) {
this.size = size;
}
}
(10)下载页面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
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 'download.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="styles.css">
-->
</head>
<body>
<a href="servlet/DownLoad">java.doc下载</a>
</body>
</html>
(11)上传页面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
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="styles.css">
-->
<style>
*{padding:0px;margin:0px}
.file{
margin-left:256px;
}
.music{
margin-left:420px;
}
</style>
</head>
<body>
<form action="servlet/FileUpload" method="post" enctype="multipart/form-data">
<h3>文件上传</h3><br>
<hr size="4" color=blue>
<br>
<div class="file">
<input type="file" name="filename"><input type="submit" value="上传">
${msg}
</div>
</form>
<br>
<div class="Music">
<a href="servlet/MusicList">返回音乐列表</a>
</div>
<h3>上传说明</h3>
<HR COLOR=BLUE SIZE="4"><br>
<tr>
<td>1.文件最大上传10M.</td>
<td>2.文件上传的格式为:.MP3</td>
</tr>
</body>
</html>
(13)登录页面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
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>登录</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<style>
body{
margin:0px;
padding:0px;
}
.bg{
margin:auto auto;
width:100%;
height:700px;
background:#ccffcc;
}
.top{width:100%;height:50px;background:yellow;}
.msg{height:52px;float:left;font-size:12px;color:gray;line-height:30px;}
.outer{
margin-left:500px;
margin-top:200px;
width:500px;
height:300px;
border:1px solid red;
background:url("images/login.png");
float:centre;
}
.ipt{
width:150px;
height:20px;
}
.cop{
margin-top:100px;
margin-left:150px;
}
</style>
</head>
<body>
<form action="servlet/loginServlet" method="post">
<div class="bg">
<div class="top">
<div class="mag">
<p>返回首页|帮助中心</p>
<p>如遇问题请拨打:010-111</p>
</div>
</div>
<div class="outer">
<div class="cop">
<p>账号:<input type="text" name="account" class="ipt"></p>
<p>密码:<input type="password" name="password" class="ipt"></p>
<input type="submit" value="登录"><a href="regist.jsp">用户注册</a>
</div>
</div>
</div>
</form>
</body>
</html>
(14)音乐列表页面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="/WEB-INF/c.tld"%>
<%
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 'musicList.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="styles.css">
-->
</head>
<style>
.s1{
background:url("images/logo.png");}
</style>
<body>
<div class="s1">
<a href="index.jsp">音乐上传</a>
<table align="center">
<tr>
<td align="center">序号</td>
<td align="center">歌曲名</td>
<td align="center">歌手名</td>
<td align="center">大小</td>
<td align="center">试听</td>
<td align="center">下载</td>
</tr>
<c:forEach var="song" items="${songList}">
<tr>
<td align="center"><c:out value="${song.id}"/></td>
<td align="center"><c:out value="${song.name}"/></td>
<td align="center"><c:out value="${song.songger}"/></td>
<td align="center"><c:out value="${song.size}"/>M</td>
<td align="center"><a href="playMusic.jsp?name=<c:out value="${song.name}"/>">试听</a></td>
<td align="center"><a href="servlet/DownLoad?name=<c:out value="${song.name}"/>">下载</a></td>
</tr>
</c:forEach>
</table>
</div>
${msg}
</body>
</html>
(15)音乐播放
<%@page contentType="text/html" pageEncoding="utf-8"%>
<html>
<head>
<title>音乐播放</title>
</head>
<body>
<div id="div">
</div>
<%String mName=request.getParameter("name");%>
<script >
var oDiv=document.getElementById("div");//得到id值为div的div元素对像
var oEmbed=document.createElement("embed");//创建音乐播放元素
var name="<%=mName%>";
oEmbed.src="music/"+name+".mp3";
oDiv.appendChild(oEmbed);
</script>
</body>
</html>
(16)注册页面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
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>注册页面</title>
<script>
function check(){
var oAtVal=document.frm.account.value;
var oPassVal=document.frm.password.value;
if(oAtVal==""){
alert("对不起账号不能为空");
returnfalse;
}if(oPassVal==""){
alert("对不起密码不能为空");
returnfalse;
}if(oAtVal.length>15){
alert("对不起账号的长度不能大于15位");
returnfalse;
}if(oPassVal.length>15){
alert("对不起密码的长度不能大于15位");
returnfalse;
}
returntrue;
}
</script>
<style>
*{margin:0px;padding:0px}
.do{
font-size:35px;
font-color:red;
margin-left:650px;
}
.bg{
margin:auto auto;
width:100%;
height:700px;
background:#ccffcc;
}
.outer{
margin-left:500px;
margin-top:200px;
width:500px;
height:300px;
border:1px solid red;
background:url("images/touxiang.png");
float:centre;
}
.cop{
margin-top:100px;
margin-left:150px;
}
</style>
</head>
<body>
<div class="do">用户注册</div>
<div class="bg">
<form action='servlet/registaction' method='post' name="frm">
<div class="outer">
<div class="cop">
账号:<input type="text" name="account"><br>
<br>
<br>
密码:<input type="password" name="password"><br>
<br>
<br>
<input type="Submit" value="确定" onclick="return check()">
<font color='red'>${message}</font>
</div>
</div>
</form>
</div>
</body>
</html>
3.实验结果截图
(1)上传页面
(2)登录页面
(3)注册页面
(4)上传成功
(5)上传音乐列表
(6)播放页面
(7)数据库
五、 实习总结
本次实训的成果是建立一个自己的音乐网站,可以实现的功能也很基础,主要是可以登录,注册,还要有验证码,可以上传和下载音乐。怎么说了,这次实训的内容不同以往,风格也和我们以前编写程序的方式不一样,这个实验让我们学会了网页编程的一些基本知识,还熟悉了HTML超文本标记语言和javascript语言的应用,以及CSS级联样式表的使用。可以说,这次实验为我们打开了一扇新的大门,使我们对编程的世界有了更深一步的了解。
但是,实验之中我们还是遇到了这样或者那样的麻烦,经历了开始的迷惘与不知所措之后,接踵而来的是那么一点点的见猎心喜的感觉,觉得这个编写的还是蛮好玩的,也很实用。让我们彻底的脱离了以前控制台操作,对于我们这些喜欢迅速的看到成果的家伙来说是一个很不错的选择。
实验之初,我们接触到了新软件Myeclipsed ,虽然这个软件很先进,对于我们编写程序来说可以大大的提高编写速度,可是对于我们这些英语菜鸟来说,全英文的软件用起来可真是吃力,在老师的带领下,我们慢慢的熟悉了这个软件,并且可以迅速的利用它编写代码,所以我们才可以在这么短的时间内从一个完全不会的菜鸟到可以完成这个项目的程度,不得不说是有点小小的欣慰的。
这次实验的最大收获并不是我们完成了这个项目,而是我们学习到了完成一个项目的时候小组合作的重要性。因为实验开始的时候我们小组各人做各人的,所以做起来很吃力,后来开始团队合作的时候,才霍然觉得开始的我们是多么的愚蠢啊,我们本可以分工合作的,项目的开发本来就是小组的各个成员的精诚合作的成果,这一点对我们的裨益是很大的。