【JavaWeb开发-Servlet】拾起海中的漂流瓶超强版

目录

原版: 

一、思路:

二、实现:

三、资源分享

四、部署服务器时记得修改文件路径



原版: 

【JavaWeb开发-Servlet】拾起海中的漂流瓶增强版_代码骑士的博客-CSDN博客【代码】【JavaWeb开发-Servlet】拾起海中的漂流瓶增强版。https://blog.csdn.net/qq_51701007/article/details/128275638?spm=1001.2014.3001.5501

基于上次的版本,我又新增了上传显示图片功能。

思路和上传文字类似,也是插入一条数据然后随机显示,只不过处理图片数据和文字略有不同。

        先说思路,在看实现过程。

一、思路:

        在dao层实现数据的查询和插入功能,在业务层copy数据插入功能并实现随机显示功能,新建一个jsp前端页面,然后在servlet中完成请求处理。img.jsp是默认界面,showimg.do是显示图片路径,addimg.do是添加图片路径。

        显示时比较简单,直接从数据库中获取图片名,然后在前端进行拼接,从而显示数据。

        添加时比较复杂,需要导入上传文件时的专用jar包,然后新建一个文件夹保存图片到服务器(但是有个问题就是每次重启服务器图片都会消失数据库中的名字还在),然后把名字保存到数据库即可。

二、实现:

        新建一张表

        先什么都不要加

         创建实体类

package oms.ck.entity;

import java.util.Objects;

public class imgs {
	
	private int id;
	private String imgPath;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getImgPath() {
		return imgPath;
	}
	public void setImgPath(String imgPath) {
		this.imgPath = imgPath;
	}
	@Override
	public int hashCode() {
		return Objects.hash(id);
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		imgs other = (imgs) obj;
		return id == other.id;
	}
	@Override
	public String toString() {
		return "imgs [id=" + id + ", imgPath=" + imgPath + "]";
	}
	
	
}

       dao层

//----------------------------------图片-------------------------------------------------------
	
	//获取图片张数
	public int getImgCount()
	{
		int count = 0;
		try {
			
			Connection conn = DBUtil.getConnection();
			String sql = "select count(*) c from imgs";
			PreparedStatement prep=conn.prepareStatement(sql);
			ResultSet rs=prep.executeQuery();
			if(rs.next()){
				count=rs.getInt("c");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return count;
	}
	//获取图片
	public String getImg(int id) {
		String imgPath = null;
		try {
			Connection conn = DBUtil.getConnection();
			String sql = "select img from imgs where id = ?";
			PreparedStatement prep=conn.prepareStatement(sql);
			prep.setInt(1,id);
			ResultSet rs=prep.executeQuery();
			if(rs.next()){
				imgPath=rs.getString("img");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return imgPath;
	}
	//插入图片
	public void addImg(imgs img,int id) {
		try {
			Connection conn = DBUtil.getConnection();
			//定义SQL语句
			String sql = "insert into imgs(id,img)values(?,?)";
			//获取PreparedStatement对象
			PreparedStatement prep = conn.prepareStatement(sql);
			//添加占位符参数
			prep.setInt(1, id);
			prep.setString(2, img.getImgPath());
			//执行SQL
			prep.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

        service层

//抽取一个随机图片
	public String randomImg() {
		//定义一个图片路径
		String img = null;
		//获取图片总数
		int n = dao.getImgCount();
		//获取随机id
		Random rad=new Random();
		int id=rad.nextInt(n+1);//从1到n
		if(id==0) {
			id=1;
		}
		//查询
		img = dao.getImg(id);
		return img;
	}
	//将图片添加到数据库
	public void addImg(imgs img) {
		int id = 0;
		id = dao.getImgCount()+1;//实现顺序+1排列
		dao.addImg(img,id);
	}

        Servlet层

else if(path.equals("/showimg")){
			//从数据库中获取一张图片路径
			path = service.randomImg();
			System.out.println("取出"+path);
			request.setAttribute("path", path);
			//2、获取转发器
			RequestDispatcher dis=request.getRequestDispatcher("img.jsp");
			//3、转发
			dis.forward(request, response);	
		}else if(path.equals("/addimg")){
			//step1 创建一个工厂类型的实例 该实例的作用是为解析器提供了默认的配置
			DiskFileItemFactory facotry=new DiskFileItemFactory();
			//step2 创建一个解析器
			ServletFileUpload sfu=new ServletFileUpload(facotry);
			String fileName="";
			//step3使用解析器 解析数据
			try {
				//解析之后,会将表单中的数据转换成一个个FileItem对象。一个表单域中的数据对应于一个FileItem对象
				List<FileItem>items=sfu.parseRequest(request);
				//step4 遍历items集合
				for(int i=0;i<items.size();i++){
					//读取表单域中的数据时,要先区分表单域的类型
					FileItem item=items.get(i);
					if(item.isFormField()){
						//如果时普通表单域 先不做任何处理
					}else{
						//如果不是普通表单域  那就是文件上传表单域
						ServletContext sctx=this.getServletContext();
						//通过ServletContext对象的getRealPath方法来或文件的实际路径
						String savePath=sctx.getRealPath("uploadimgs");
						//获取文件名
						fileName=item.getName();
						File file = new File(savePath+"\\"+fileName);
						//保存文件至文件夹
						item.write(file);
						
						//将文件名保存在数据库中
						imgs img = new imgs();
						img.setImgPath(fileName);
						service.addImg(img);
						System.out.println("存入相对路径"+img.getImgPath()+"\n"+"绝对路径"+savePath+"\\"+fileName);
					}
				}
				response.sendRedirect("img.jsp");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

        前端

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>海边拾起一个漂流瓶,是谁的祝愿呢?</title>
<link rel="stylesheet" type="text/css"href="statics/css/bootstrap.css" />
</head>
<body background="statics/image/1.png">
	<div class="panel">
		<h1 class="text-center">
			海边拾起一个漂流瓶,是谁的祝愿呢?
		</h1>
	</div>
	<%
		String say=(String)request.getAttribute("say");
	%>
	<div class="container">
		<form action="showimg.do" method="post" class="text-center">
			<input type="button" value="回到海边" onclick="location='main.jsp'" class="btn btn-default"/>
    		<input type="button" value="换一张" onclick="location='showimg.do'" class="btn btn-default"/>
		</form>
	</div>
	<br>
	<div class="text-center">
	<%
		String path=(String)request.getAttribute("path");
	%>
		<img src="<%="uploadimgs/"+((path==null)?("3.png"):(path)) %>" alt="" width=500px height=500px class="img-thumbnail">
	</div>
	<div class="container">
		<form action="addimg.do" method="post" class="text-center" enctype="multipart/form-data">
			<div>
					<input type="file" name="file" style="height:40px;line-height:40px;width:100%">
					<br>
					<input type="submit" value="上传我的"> 
    		</div>
		</form>
	</div>
</body>
</html>

        新建文件夹

        导入的jar包

 

三、资源分享

 获取连接:

【JavaWeb开发-Servlet】文件上传功能(UpLoad)_代码骑士的博客-CSDN博客

完整项目源码:

https://download.csdn.net/download/qq_51701007/87269047

四、部署服务器时记得修改文件路径

else{
						//如果不是普通表单域  那就是文件上传表单域
						ServletContext sctx=this.getServletContext();
						//通过ServletContext对象的getRealPath方法来或文件的实际路径
						String savePath=sctx.getRealPath("/uploadimgs");
						//获取文件名
						fileName=item.getName();
						File file = new File(savePath+"/"+fileName);
						//保存文件至文件夹
						item.write(file);
						
						//将文件名保存在数据库中
						imgs img = new imgs();
						img.setImgPath(fileName);
						service.addImg(img);
						System.out.println("存入相对路径"+img.getImgPath()+"\n"+"绝对路径"+savePath+"\\"+fileName);
					}

之前图片上传不了原来是路径写错了!记得有问题就去查日志!

有问题就去查日志!

有问题就去查日志!

有问题就去查日志!

猜你喜欢

转载自blog.csdn.net/qq_51701007/article/details/128283047