搭建WebService开发环境,改进“图片上传”实验
写在前面: 本次实验是在Jsp+servlet+SqlServer实现图片上传、图片详情查看、表格分页实验的基础上进行改进…… (°ー°〃)菜鸟一枚!如有问题欢迎指出!!
结果展示
1、新建两个工程,一个是Webservice的Server端,一个是Webservice的Client端。 2、把原来业务层里的类(方法)通过Webservice发布出来,提供Client调用。
↓ 画了个简陋的图。。凑合看看
Server端
核心代码
ImageDAOImpl.java
package com.bnuz.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.jws.WebService;
import com.bnuz.dao.ImageDAO;
import com.bnuz.javabean.Image;
import com.bnuz.util.DBUtil;
@WebService
public class ImageDAOImpl implements ImageDAO{
private Connection conn;
private PreparedStatement ps;
@Override
public void add(Image image) {
try {
conn = DBUtil.getConn();
ps = conn.prepareStatement("insert into images(title,url) values (?,?)");
ps.setString(1, image.getTitle());
ps.setString(2, image.getImgurl());
ps.execute();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public List<Image> queryAll() {
List<Image> images = new ArrayList<Image>();
try {
conn = DBUtil.getConn();
ps = conn.prepareStatement("select * from images");
ResultSet rs = ps.executeQuery();
while(rs.next()) {
int id = rs.getInt("id");
String title = rs.getString("title");
String url = rs.getString("url");
Image image = new Image(id,title,url);
images.add(image);
}
} catch (SQLException e) {
e.printStackTrace();
}
return images;
}
@Override
public Image query(int id) {
Image image = new Image();
try {
conn = DBUtil.getConn();
ps = conn.prepareStatement("select * from images where id = ?");
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
while(rs.next()) {
image.setId(id);
image.setTitle(rs.getString("title"));
image.setImgurl(rs.getString("url"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return image;
}
@Override
public List<Image> queryScope(int start, int end) {
List<Image> images = new ArrayList<Image>();
try {
conn = DBUtil.getConn();
ps = conn.prepareStatement("select * from images where id>? and id<?");
ps.setInt(1, start);
ps.setInt(2, end);
ResultSet rs = ps.executeQuery();
while(rs.next()) {
int id = rs.getInt("id");
String title = rs.getString("title");
String url = rs.getString("url");
Image image = new Image(id,title,url);
images.add(image);
}
} catch (SQLException e) {
e.printStackTrace();
}
return images;
}
}
发布服务,Endpoint.publish方法含两个参数:1、服务地址;2、服务实现类 测试发布是否成功
Client端
先在eclipse中创建一个动态Web项目Client wsimport -s . http://127.0.0.1:8848/images?wsdl
随后在eclipse中refresh一下Client项目,refresh后我们将看到Client项目生成了一个com.bnuz.dao.impl包,接着我们就可以调用Server提供给我们的服务编写Client端的代码了! 上传文件需要用到的jar包 ↓
Add.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>图片上传</title>
<style>
.info-div{
margin-top:10px;
}
</style>
</head>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
<div class="info-div">
<label>主题:</label>
<input type="text" name="title">
</div>
<div class="info-div">
<label>图片:</label>
<input type="file" name="uploadImg">
</div>
<div class="info-div">
<input type="submit" value="保存">
</div>
</form>
</body>
</html>
List.jsp
<%@page import="com.bnuz.dao.impl.Image"%>
<%@page import="java.util.List"%>
<%@page import="com.bnuz.dao.impl.ImageDAOImpl"%>
<%@page import="com.bnuz.dao.impl.ImageDAOImplService"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>图片列表</title>
</head>
<body>
<%
ImageDAOImplService iService = new ImageDAOImplService();
ImageDAOImpl imageDAOImpl = iService.getPort(ImageDAOImpl.class);
List<Image> images = imageDAOImpl.queryAll();
int pages = images.size() / 3 + ((images.size() % 3 != 0) ? 1 : 0);
int start = 0;
List<Image> pageImages = imageDAOImpl.queryScope(0, 4);
if (request.getParameter("page") != null) {
String s = request.getParameter("page");
start = Integer.parseInt(s);
pageImages = imageDAOImpl.queryScope(start * 3 - 3, start * 3 + 1);
}
%>
<a href="Add.jsp">上传图片</a>
<div style="display: flex; height: 30px; margin-top:10px">
<form action="List.jsp?page=<%=start - 1%>" method="post">
<input type="submit" value="上一页">
</form>
<form action="List.jsp" method="post">
<input type="text" name="page"
value="<%=request.getParameter("page")%>" style="width: 50px;">
<input type="submit" value="跳转">
</form>
<br>
<form action="List.jsp?page=<%=start + 1%>" method="post">
<input type="submit" value="下一页">
</form>
<label>一共有<%=images.size()%>条数据,共<%=pages%>页
</label>
</div>
<table border="1" style="text-align: center;">
<tr>
<th style="width: 50px;">id</th>
<th style="width: 150px;">主题</th>
<th style="width: 100px;">图片</th>
<th style="width: 80px;">操作</th>
</tr>
<%
for (Image u : pageImages) {
%>
<tr>
<td><%=u.getId()%></td>
<td><%=u.getTitle()%></td>
<td><img style="width: 80px; height: 50px"
src="<%=u.getImgurl()%>"></img></td>
<td>
<form action="Detail.jsp?id=<%=u.getId()%>" method="post">
<input type="submit" value="查看" name="s">
</form>
</td>
</tr>
<%
}
%>
</table>
</body>
</html>
Detail.jsp
<%@page import="com.bnuz.dao.impl.Image"%>
<%@page import="com.bnuz.dao.impl.ImageDAOImpl"%>
<%@page import="com.bnuz.dao.impl.ImageDAOImplService"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>详情页</title>
</head>
<body>
<%
int id = Integer.parseInt(request.getParameter("id"));
ImageDAOImplService iService = new ImageDAOImplService();
ImageDAOImpl imageDAOImpl = iService.getPort(ImageDAOImpl.class);
Image image = imageDAOImpl.query(id);
%>
<div>
<label>主题:</label>
<label><%=image.getTitle()%></label>
</div>
<div>
<label>发布人:YE</label>
</div>
<div>
<label>图片:</label><br>
<img src="<%=image.getImgurl()%>"
style="height: 200px; width: 300px;">
</div>
</body>
</html>
UploadServlet.java
package com.bnuz.servlet;
import java.io.IOException;
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 com.bnuz.dao.impl.Image;
import com.bnuz.dao.impl.ImageDAOImpl;
import com.bnuz.dao.impl.ImageDAOImplService;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
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;
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public UploadServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("UTF-8");
Image image = new Image();
ImageDAOImplService iService = new ImageDAOImplService();
ImageDAOImpl imageDAOImpl = iService.getPort(ImageDAOImpl.class);
String name = null;
if (!ServletFileUpload.isMultipartContent(request)) {
throw new RuntimeException("当前请求不支持文件上传");
}
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024 * 1024 * 1);
String temppath = this.getServletContext().getRealPath("/temp");
File temp = new File(temppath);
factory.setRepository(temp);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
upload.setFileSizeMax(1024 * 1024 * 2);
upload.setSizeMax(1024 * 1024 * 5);
try {
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
String fieldName = item.getFieldName();
if (fieldName.equals("title")) {
name = item.getString("UTF-8");
}
System.out.println(fieldName + "=" + name);
} else {
long size = item.getSize();
String contentType = item.getContentType();
String fileName = item.getName();
System.out.println("文件大小:" + size);
System.out.println("文件的类型:" + contentType);
if ((!"image/jpeg".equals(contentType)) && (!"image/png".equals(contentType))) {
break;
}
if (fileName.contains("\\")) {
fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
}
fileName = System.currentTimeMillis() + fileName;
System.out.println("文件的名称:" + fileName);
InputStream inputStream = item.getInputStream();
String path = getServletContext().getRealPath("img/");
System.out.println(path);
File dirFile = new File(path);
if (!dirFile.exists()) {
dirFile.mkdir();
}
File file = new File(path, fileName);
OutputStream os = new FileOutputStream(file);
int len = 0;
byte[] buf = new byte[1024];
while ((len = inputStream.read(buf)) != -1) {
os.write(buf, 0, len);
}
path = "img/" + fileName;
image.setTitle(name);
image.setImgurl(path);
imageDAOImpl.add(image);
os.close();
inputStream.close();
item.delete();
}
}
response.sendRedirect("List.jsp");
} catch (FileUploadException e) {
e.printStackTrace();
}
}
}
web.xml 加上↓
<servlet>
<servlet-name>upload</servlet-name>
<servlet-class>com.bnuz.servlet.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>upload</servlet-name>
<url-pattern>/upload</url-pattern>
</servlet-mapping>
images.sql
create table images(
id int identity(1,1) primary key,
title varchar(50),
url varchar(255)
);
|