基于javaweb+mysql的jsp+servlet精美风在线音乐网站(java+jdbc+c3p0+servlet+mysql+jsp)
运行环境
Java≥8、MySQL≥5.7、Tomcat≥8
开发工具
eclipse/idea/myeclipse/sts等均可配置运行
适用
课程设计,大作业,毕业设计,项目练习,学习演示等
功能说明
基于javaweb+mysql的JSP+Servlet精美风在线音乐网站(java+jdbc+c3p0+servlet+mysql+jsp)
1.运行环境
环境配置:
Jdk1.8 + Tomcat8.5 + mysql + Eclispe(IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持)
项目技术:
JSP + C3P0+ Servlert + html+ css + JavaScript + JQuery + Ajax + Fileupload等等
Map<String, Object> map = new HashMap<String, Object>();
// 第一步:判断request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
// 第二步:解析request
if (isMultipart) {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// 阀值,超过这个值才会写到临时目录,否则在内存中
factory.setSizeThreshold(1024 * 1024 * 10);
factory.setRepository(new File(tempPath));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
// 最大上传限制
upload.setSizeMax(maxSize);
/* FileItem */
List<FileItem> items = null;
// Parse the request
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 第3步:处理uploaded items
if (items != null && items.size() > 0) {
Iterator<FileItem> iter = items.iterator();
// 文件域对象
List<FileItem> list = new ArrayList<FileItem>();
// 表单字段
Map<String, String> fields = new HashMap<String, String>();
while (iter.hasNext()) {
FileItem item = iter.next();
// 处理所有表单元素和文件域表单元素
if (item.isFormField()) { // 表单元素
@WebServlet("/admin/updateSongServlet")
public class UpdateSongServlet extends HttpServlet {
private SongService songService = null;
private TypeService typeService = null;
@Override
public void init() throws ServletException {
songService = new SongServiceImpl();
typeService = new TypeServiceImpl();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取修改表单
String songId = request.getParameter("songId");
String playerCount = request.getParameter("update_playerCount_" + songId);
String downloadCount = request.getParameter("update_downloadCount_" + songId);
String collectionCount = request.getParameter("update_collectionCount_" + songId);
String type = request.getParameter("update_songType_" + songId);
String initialType = request.getParameter("initialType_" + songId);
String lyric = request.getParameter("updateLyric_" + songId);
System.out.println(type);
// 封装数据
Song song = new Song();
song.setSongId(Integer.parseInt(songId));
song.setPlayCount(Integer.parseInt(playerCount));
song.setDownloadCount(Integer.parseInt(downloadCount));
song.setCollectionCount(Integer.parseInt(collectionCount));
song.setType(type);
song.setLyric(lyric);
song.setUpdateDate(DateUtils.getDateString());
System.out.println(song);
// 调用service执行修改操作
int flag = songService.updateSong(song);
// 判断现在的类型和原类型是否一致
if(!type.equals(initialType)){
String[] typeSplit = type.split(",");
String[] initialSplitType = initialType.split(",");
for(String s : typeSplit){
// 如果原分类字符串不包含s,则修改类型的歌曲数量
if(!initialType.contains(s)){
if(typeService.getTypeByName(s) != null){
typeService.updateTypeByName(s, true);
savePath += ymd + "/";
saveUrl += ymd + "/";
File dirFile = new File(savePath);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
// 获取上传临时路径
tempPath = request.getSession().getServletContext().getRealPath("/") + tempPath + "/";
File file = new File(tempPath);
if (!file.exists()) {
file.mkdirs();
}
}
return errorInfo;
}
/**
* 处理上传内容
*
* @param request
* @return
*/
@SuppressWarnings("unchecked")
private Map<String, Object> initFields(HttpServletRequest request) {
// 存储表单字段和非表单字段
Map<String, Object> map = new HashMap<String, Object>();
// 第一步:判断request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
// 第二步:解析request
if (isMultipart) {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// 阀值,超过这个值才会写到临时目录,否则在内存中
factory.setSizeThreshold(1024 * 1024 * 10);
factory.setRepository(new File(tempPath));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
private String makeFileName(String filename){ //2.jpg
//为防止文件覆盖的现象发生,要为上传文件产生一个唯一的文件名
return UUID.randomUUID().toString() + "_" + filename;
}
/**
* 为防止一个目录下面出现太多文件,要使用hash算法打散存储
* @Method: makePath
* @Description:
* @param filename 文件名,要根据文件名生成存储目录
* @param savePath 文件存储路径
* @return 新的存储目录
*/
private String makePath(String filename,String savePath){
//得到文件名的hashCode的值,得到的就是filename这个字符串对象在内存中的地址
int hashcode = filename.hashCode();
int dir1 = hashcode&0xf; //0--15
int dir2 = (hashcode&0xf0)>>4; //0-15
//构造新的保存目录
String dir = savePath + "\\" + dir1 + "\\" + dir2; //upload\2\3 upload\3\5
//File既可以代表文件也可以代表目录
File file = new File(dir);
//如果目录不存在
if(!file.exists()){
//创建目录
file.mkdirs();
}
return dir;
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
public void addSong(HttpServletRequest request, Song song, String realSavePath){
System.out.println("开始添加歌曲文件");
// 反馈给前端页面的数据
// JSONObject jsonObject = new JSONObject();
String url = realSavePath.substring(realSavePath.indexOf("other"));
System.out.println(url);
// 封装数据
song.setSongId(null);
song.setCdId(null);
song.setPlayCount(0);
song.setDownloadCount(0);
song.setCollectionCount(0);
Date date = new Date();
* @param subjectText
* 主题
* @param mailText
* 邮件正文
* @return
* @throws Exception
*/
public static void Send(String EmailAccount, String EmailPassword, String receiveMail, String userRemarks,
String senderName, String subjectText, String mailText) {
try {
// 1. 创建参数配置, 用于连接邮件服务器的参数配置
Properties props = new Properties(); // 参数配置
props.setProperty("mail.transport.protocol", "smtp"); // 使用的协议(JavaMail规范要求)
props.setProperty("mail.smtp.host", myEmailSMTPHost); // 发件人的邮箱的 SMTP 服务器地址
props.setProperty("mail.smtp.auth", "true"); // 需要请求认证
// PS: 某些邮箱服务器要求 SMTP 连接需要使用 SSL 安全认证 (为了提高安全性, 邮箱支持SSL连接, 也可以自己开启),
// 如果无法连接邮件服务器, 仔细查看控制台打印的 log, 如果有有类似 “连接失败, 要求 SSL 安全连接” 等错误,
// 取消下面 /* ... */ 之间的注释代码, 开启 SSL 安全连接。
/*
* // SMTP 服务器的端口 (非 SSL 连接的端口一般默认为 25, 可以不添加, 如果开启了 SSL 连接, // 需要改为对应邮箱的 SMTP
* 服务器的端口, 具体可查看对应邮箱服务的帮助, // QQ邮箱的SMTP(SLL)端口为465或587, 其他邮箱自行去查看) final String
* smtpPort = "465"; props.setProperty("mail.smtp.port", smtpPort);
* props.setProperty("mail.smtp.socketFactory.class",
* "javax.net.ssl.SSLSocketFactory");
* props.setProperty("mail.smtp.socketFactory.fallback", "false");
* props.setProperty("mail.smtp.socketFactory.port", smtpPort);
*/
// 2. 根据配置创建会话对象, 用于和邮件服务器交互
Session session = Session.getInstance(props);
// 设置为debug模式, 可以查看详细的发送 log
session.setDebug(true);
// 3. 创建一封邮件
MimeMessage message = createMimeMessage(session, receiveMail, userRemarks, senderName, subjectText,
mailText, EmailAccount);
// 4. 根据 Session 获取邮件传输对象
Transport transport = session.getTransport();
// 5. 使用 邮箱账号 和 密码 连接邮件服务器, 这里认证的邮箱必须与 message 中的发件人邮箱一致, 否则报错
//
// PS_01: 如果连接服务器失败, 都会在控制台输出相应失败原因的log。
// 仔细查看失败原因, 有些邮箱服务器会返回错误码或查看错误类型的链接,
// 根据给出的错误类型到对应邮件服务器的帮助网站上查看具体失败原因。
//
// PS_02: 连接失败的原因通常为以下几点, 仔细检查代码:
// (1) 邮箱没有开启 SMTP 服务;
// (2) 邮箱密码错误, 例如某些邮箱开启了独立密码;
// (3) 邮箱服务器要求必须要使用 SSL 安全连接;
package com.martinwj.mymusic.util;
/**
* @description: TODO
* @version: 1.0
*
* * SendEmail静态类的Send方法用于发送邮件
* * SendEmail.Send(EmailAccount, EmailPassword, receiveMail, userRemarks, senderName, subjectText, mailText);
*/
public class EmailUtils {
// https://www.cnblogs.com/xmqa/p/8458300.html
// 发件人的 邮箱 和 密码(替换为自己的邮箱和密码)
// PS: 某些邮箱服务器为了增加邮箱本身密码的安全性,给 SMTP 客户端设置了独立密码(有的邮箱称为“授权码”),
// 对于开启了独立密码的邮箱, 这里的邮箱密码必需使用这个独立密码(授权码)。
// public static String myEmailAccount = "myEmailAccount";
// public static String myEmailPassword = "myEmailPassword";
// 发件人邮箱的 SMTP 服务器地址, 必须准确, 不同邮件服务器地址不同, 一般(只是一般, 绝非绝对)格式为: smtp.xxx.com
// 网易yeah邮箱的 SMTP 服务器地址为: smtp.yeah.net
public static String myEmailSMTPHost = "smtp.163.com";
// 网站链接地址
private static final String linkString = "http://localhost:8080";
// 收件人邮箱(替换为自己知道的有效邮箱)
// public static String receiveMailAccount = "receiveMailAccount";
/**
* 创建邮件对象
*
* @param session
* 和服务器交互的会话
* @param receiveMail
* 收件人邮箱
/**
* @description: TODO
* @version: 1.0
*/
@WebServlet("/homePageServlet")
public class HomePageServlet extends HttpServlet {
private SongService songService = null;
private SingerService singerService = null;
private CommentService commentService = null;
private TypeService typeService = null;
@Override
public void init() throws ServletException {
songService = new SongServiceImpl();
singerService = new SingerServiceImpl();
commentService = new CommentServiceImpl();
typeService = new TypeServiceImpl();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
// 获取10条数量的新更新的音乐
// 分页的信息
String _currentPage = request.getParameter("currentPage");// 当前页码
String _rows = request.getParameter("rows");// 每页显示条数
if(_currentPage == null || "".equals(_currentPage)){
_currentPage = "1";
}
if(_rows == null || "".equals(_rows)){
_rows = "10";
}
int currentPage = Integer.parseInt(_currentPage);
int rows = Integer.parseInt(_rows);
commentSong.setRows(rows);
// 获取总的评论数
int totalCount = commentService.getCommentsCountBySongId(Integer.parseInt(songId));
commentSong.setTotalCount(totalCount);
// 计算总页码
int totalPage = (totalCount % rows) == 0 ? (totalCount / rows) : (totalCount/rows) + 1;
commentSong.setTotalPage(totalPage);
// 计算当前页码
if(currentPage <= 0){
currentPage = totalPage;
} else if(currentPage > totalPage) {
currentPage = 1;
}
commentSong.setCurrentPage(currentPage);
int start = (currentPage - 1) * rows;
// 获取评论列表
List<Comment> comments = commentService.getCommentsBySongId(start, rows, Integer.parseInt(songId));
Map<User, Comment> map = new HashMap<User, Comment>();
for(Comment comment : comments) {
user = userService.getUserByUserId(comment.getUserId());
comment.setContext(comment.getContext().replace("\n", "<br>"));
map.put(user, comment);
}
commentSong.setCommentMap(map);
HttpSession session = request.getSession();
session.setAttribute("commentSong", commentSong);
response.sendRedirect(request.getContextPath() + "/page/user/comment-music.jsp");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
package com.martinwj.mymusic.controller.user.home;
if(songService.deleteSongBySongId(id) > 0) {
for (String str : type.split(",")) {
typeService.updateTypeByName(str, false);
}
}
}
/**
* 根据多个歌曲ID删除歌曲信息
* @param ids
*/
public static void deleteSong(String[] ids){
for(String id : ids) {
deleteSong(Integer.parseInt(id));
}
}
}
package com.martinwj.mymusic.controller.user.song.categories;
/**
* @description: TODO
* @version: 1.0
*/
@WebServlet("/getAllCategoriesSongServlet")
public class GetAllCategoriesSongServlet extends HttpServlet {
private SongService songService = null;
private TypeService typeService = null;
@Override
public void init() throws ServletException {
songService = new SongServiceImpl();
int totalCount = Math.toIntExact(songService.getAllSongsCountBySingerName(singerName));
// 计算总页码
int totalPage = (totalCount % rows) == 0 ? (totalCount / rows) : (totalCount/rows) + 1;
songPage.setTotalPage(totalPage);
// 计算当前页码
if(currentPage <= 0){
currentPage = totalPage;
} else if(currentPage > totalPage) {
currentPage = 1;
}
songPage.setCurrentPage(currentPage);
int start = (currentPage - 1) * rows;
// 获取该歌手的所有歌曲
List<Song> allSongs = songService.getSongBySingerName(start, rows, singerName);
Singer singer = singerService.getSingerBySingerName(singerName);
songPage.setList(allSongs);
songPage.setTotalCount(totalCount);
songPage.setRows(rows);
songPage.setTotalPage(totalPage);
// 添加到session
HttpSession session = request.getSession();
session.setAttribute("songPage", songPage);
session.setAttribute("singer", singer);
// 重定向到album-single页面
response.sendRedirect(request.getContextPath() + "/page/user/album-single.jsp");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
package com.martinwj.mymusic.util;
String filename = null;
String saveFilename = null;
//得到上传文件的保存目录,将上传的文件存放于WEB-INF目录下,不允许外界直接访问,保证上传文件的安全
// String savePath = new File("").getCanonicalPath() + "\\web" + path_save;
String savePath = PathUtils.getProjectURL() + "/web" + path_save;
//上传时生成的临时文件保存目录
// String tempPath = new File("").getCanonicalPath() + "\\web" + path_temp;
String tempPath = PathUtils.getProjectURL() + "/web" + path_temp;
System.out.println("savePath: " + savePath);
System.out.println("tempPath: " + tempPath);
File tmpFile = new File(tempPath);
if (!tmpFile.exists()) {
//创建临时目录
tmpFile.mkdir();
}
//消息提示
String message = "";
String singerName = "";
try{
//使用Apache文件上传组件处理文件上传步骤:
//1、创建一个DiskFileItemFactory工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
//设置工厂的缓冲区的大小,当上传的文件大小超过缓冲区的大小时,就会生成一个临时文件存放到指定的临时目录当中。
factory.setSizeThreshold(1024*100);//设置缓冲区的大小为100KB,如果不指定,那么缓冲区的大小默认是10KB
//设置上传时生成的临时文件的保存目录
factory.setRepository(tmpFile);
//2、创建一个文件上传解析器
ServletFileUpload upload = new ServletFileUpload(factory);
//监听文件上传进度
upload.setProgressListener(new ProgressListener(){
@Override
public void update(long pBytesRead, long pContentLength, int arg2) {
System.out.println("文件大小为:" + pContentLength + ",当前已处理:" + pBytesRead);
/**
* 文件大小为:14608,当前已处理:4096
文件大小为:14608,当前已处理:7367
文件大小为:14608,当前已处理:11419
文件大小为:14608,当前已处理:14608
*/
}
});
//解决上传文件名的中文乱码
upload.setHeaderEncoding("UTF-8");
request.getRequestDispatcher("/page/manager/message.jsp").forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
public void addSinger(HttpServletRequest request, Singer singer, String realSavePath){
String url = realSavePath.substring(realSavePath.indexOf("other"));
System.out.println(url);
// 封装数据
singer.setPic(url);
addSinger(request, singer);
}
public void addSinger(HttpServletRequest request, Singer singer){
// 封装数据
singer.setCollectionCount(0);
int flag = singerService.addSinger(singer);
System.out.println(flag);
if(flag > 0) {
request.setAttribute("message", "歌手添加成功!");
} else {
request.setAttribute("message", "歌手添加失败!");
}
}
//生成上传文件的文件名,文件名以:uuid+"_"+文件的原始名称
public String mkFileName(String fileName){
return UUID.randomUUID().toString()+"_"+fileName;
}
}
package com.martinwj.mymusic.util;
int songId = Integer.parseInt(idStr);
//从数据库找到该文件信息
Song song = songService.getSongById(songId);
//获取所要下载的文件名称
String absPath = request.getSession().getServletContext().getRealPath("");
System.out.println(absPath);
String filepath = absPath + "/" + song.getUrl();
//对文件名称编码
// filename = new String(filename.trim().getBytes("iso8859-1"),"UTF-8");
System.out.println("需要下载的文件路径为:" + filepath);
// //得到要下载的文件
File file = new File(filepath);
System.out.println("文件是否存在:" + file.exists());
//如果文件不存在
if (!file.exists()) {
request.setAttribute("titleMsg", "哎呀!");
request.setAttribute("textMsg", "出了些问题,您要下载的资源不存在了!");
String url = request.getContextPath() + "/page/user/album-single.jsp";
request.setAttribute("urlMsg", url);
request.setAttribute("pageMsg", "歌曲列表");
request.setAttribute("codeMsg", "");
request.getRequestDispatcher("/page/user/message.jsp").forward(request, response);
return;
}
//改变下载量
System.out.println("改变下载量之前:" + song.getDownloadCount());
song.setDownloadCount(song.getDownloadCount() + 1);
System.out.println("改变下载量之后:" + song.getDownloadCount());
int flag = songService.updateSong(song);
System.out.println("下载量改变是否成功:" + flag);
if (flag > 0) {
// //下载文件所在目录
// String folder = "WebContent/download/";
//处理文件名
String realname = song.getName() + ".mp3";
//设置响应头,控制浏览器下载该文件
response.setContentType("application/x-msdownload");
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(realname, "UTF-8"));
//读取要下载的文件,保存到文件输入流
FileInputStream in = new FileInputStream(filepath);
//创建输出流
OutputStream out = response.getOutputStream();
//创建缓冲区
byte[] buffer = new byte[1024];
int len = 0;
//循环将输入流中的内容读取到缓冲区当中
int dir2 = (hashcode&0xf0)>>4; //0-15
//构造新的保存目录
String dir = savePath + "\\" + dir1 + "\\" + dir2; //upload\2\3 upload\3\5
//File既可以代表文件也可以代表目录
File file = new File(dir);
//如果目录不存在
if(!file.exists()){
//创建目录
file.mkdirs();
}
return dir;
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
public void addSong(HttpServletRequest request, Song song, String realSavePath){
System.out.println("开始添加歌曲文件");
// 反馈给前端页面的数据
// JSONObject jsonObject = new JSONObject();
String url = realSavePath.substring(realSavePath.indexOf("other"));
System.out.println(url);
// 封装数据
song.setSongId(null);
song.setCdId(null);
song.setPlayCount(0);
song.setDownloadCount(0);
song.setCollectionCount(0);
Date date = new Date();
String dateStr = DateUtils.getDateString(date);
song.setPublicDate(dateStr);
song.setUpdateDate(dateStr);
song.setUrl(url);
song.setTime(Tools.getMP3Timer(realSavePath));
// 设置上传用户
/**
* 表单字段常量
*/
public static final String FORM_FIELDS = "form_fields";
/**
* 文件域常量
*/
public static final String FILE_FIELDS = "file_fields";
// 最大文件大小
private long maxSize = 1000000;
// 定义允许上传的文件扩展名
private Map<String, String> extMap = new HashMap<String, String>();
// 文件保存目录相对路径
private String basePath = "upload";
// 文件的目录名
private String dirName = "song";
// 上传临时路径
private static final String TEMP_PATH = "/temp";
private String tempPath = basePath + TEMP_PATH;
// 若不指定则文件名默认为 yyyyMMddHHmmss_xyz
private String fileName;
// 文件保存目录路径
private String savePath;
// 文件保存目录url
private String saveUrl;
// 文件最终的url包括文件名
private String fileUrl;
public UploadUtils() {
// 其中images,flashs,medias,files,对应文件夹名称,对应dirName
// key文件夹名称
// value该文件夹内可以上传文件的后缀名
extMap.put("images", "gif,jpg,jpeg,png,bmp");
extMap.put("flashs", "swf,flv");
extMap.put("medias", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
extMap.put("files", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
}
}
}
package com.martinwj.mymusic.util;
/**
* @description: TODO
* @version: 1.0
*
* * SendEmail静态类的Send方法用于发送邮件
* * SendEmail.Send(EmailAccount, EmailPassword, receiveMail, userRemarks, senderName, subjectText, mailText);
*/
public class EmailUtils {
// https://www.cnblogs.com/xmqa/p/8458300.html
// 发件人的 邮箱 和 密码(替换为自己的邮箱和密码)
// PS: 某些邮箱服务器为了增加邮箱本身密码的安全性,给 SMTP 客户端设置了独立密码(有的邮箱称为“授权码”),
// 对于开启了独立密码的邮箱, 这里的邮箱密码必需使用这个独立密码(授权码)。
// public static String myEmailAccount = "myEmailAccount";
// public static String myEmailPassword = "myEmailPassword";
// 发件人邮箱的 SMTP 服务器地址, 必须准确, 不同邮件服务器地址不同, 一般(只是一般, 绝非绝对)格式为: smtp.xxx.com
// 网易yeah邮箱的 SMTP 服务器地址为: smtp.yeah.net
public static String myEmailSMTPHost = "smtp.163.com";
// 网站链接地址
private static final String linkString = "http://localhost:8080";
// 收件人邮箱(替换为自己知道的有效邮箱)
// public static String receiveMailAccount = "receiveMailAccount";
/**
* 创建邮件对象
*
* @param session
* 和服务器交互的会话
* @param receiveMail
* 收件人邮箱
* @param userRemarks
* 用户备注
* @param senderName
* 发件人昵称
* @param subjectText
StringBuilder code = new StringBuilder();
for (int i = 1; i <= 4; i++) {
int index = ran.nextInt(str.length());
//获取字符
char ch = str.charAt(index);//随机字符
g.setColor(randomColor());//随机颜色
g.setFont(randomFont());//随机字体
//2.3写验证码
g.drawString(ch+"",width/5*i,height/2);
code.append(ch);
}
//2.4画干扰线
g.setColor(Color.GREEN);
//随机生成坐标点
for (int i = 0; i < 10; i++) {
int x1 = ran.nextInt(width);
int x2 = ran.nextInt(width);
int y1 = ran.nextInt(height);
int y2 = ran.nextInt(height);
g.drawLine(x1,y1,x2,y2);//画线
}
//画干扰点
for (int i = 0; i < 10; i++) {
g.setColor(randomColor());//随机颜色
int x1 = ran.nextInt(width);
int y1 = ran.nextInt(height);
g.drawOval(x1,y1,2,2);//画点
}
System.out.println(code.toString());
//3.将图片输出到页面展示
ImageIO.write(image,"jpg",response.getOutputStream());
}
//生成随机颜色
private Color randomColor(){