上一篇文章中,我们介绍了环境配置与后台设计
这篇文章,我们将直接面向功能进行分析,是这个系列文章中干货最多,最需要理解的一篇。
首先,我们要搭一个后台,需要提前做的是确定Java Resources中Package的目录结构,将不同的java类放在不同的文件夹下面。第一级目录我们一般设为com,而在本项目中,我将com下面的包划分为数据访问层(Dao层),实体映射层(Entity层)、功能层(Util层)以及放Servlet和Filter的两个层。
PS: 建包的时候在空包下面建包会得到同级目录的包,要先在包中新建一个类再创建。
(1)用户登陆与注册
DengluServlet
package com.servlet;
import java.io.IOException;
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;
import com.dao.PhotoDaoImpl;
import com.dao.UserDao;
import com.dao.UserDaoImpl;
import com.entity.Photo;
import com.entity.User;
public class DengluServlet extends HttpServlet { //需要继承HttpServlet 并重写doGet doPost方法
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response); //将信息使用doPost方法执行 对应jsp页面中的form表单中的method
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("user"); //得到jsp页面传过来的参数
String pwd = request.getParameter("pswd"); //得到jsp页面传过来的参数
UserDao ud = new UserDaoImpl();
HttpSession session = request.getSession();
if(ud.login(name, pwd)){
if(name.equals("root"))
{
UserDaoImpl userService = new UserDaoImpl();
List<User> UserList = new ArrayList<User>();
UserList = userService.getUserAll();
request.setAttribute("UserList",UserList);
session.setAttribute("loginMsg","管理员登陆成功!");
request.getRequestDispatcher("UserManagement.jsp").forward(request, response);//转发到成功页面
}else {
PhotoDaoImpl photoService = new PhotoDaoImpl();
List<Photo> PhotoList = new ArrayList<Photo>();
PhotoList = photoService.getAllPhotos();
request.setAttribute("PhotoList",PhotoList);
session.setAttribute("loginMsg","普通用户登陆成功!");
request.setAttribute("user", name);
request.getRequestDispatcher("SatellitePic.jsp").forward(request, response);
}
}
else{
session.setAttribute("loginMsg","用户不存在或密码错误!");
response.sendRedirect("login.jsp"); //重定向到首页
}
}
}
ZhuceServlet
package com.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.dao.UserDao;
import com.dao.UserDaoImpl;
import com.entity.User;
public class ZhuceServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("register_user"); //获取jsp页面传过来的参数
String pwd = request.getParameter("register_pswd");
User user = new User(); //实例化一个对象,组装属性
user.setName(name);
user.setPwd(pwd);
UserDao ud = new UserDaoImpl();
if(ud.register(user)){
request.setAttribute("username", name); //向request域中放置参数
request.getRequestDispatcher("login.jsp").forward(request, response); //转发到登录页面
}else{
response.sendRedirect("login.jsp");//重定向到首页
}
}
}
UserDao(用户层接口)
package com.dao;
import java.util.List;
import com.entity.User;
public interface UserDao {
public boolean login(String name,String pwd);//登录
public boolean register(User user);//注册
public List<User> getUserAll();//返回用户信息集合
public boolean delete(String name) ;//根据id删除用户
public boolean update(String name, String pwd) ;//更新用户信息
}
UserDaoImpl(用户层接口实现)
package com.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.entity.User;
import com.util.DBconn;
public class UserDaoImpl implements UserDao{
public boolean register(User user) {
boolean flag = false;
DBconn.init();
int i =DBconn.addUpdDel("insert into userdata(user,password) " +
"values('"+user.getName()+"','"+user.getPwd()+"')");
if(i>0){
flag = true;
}
DBconn.closeConn();
return flag;
}
public boolean login(String name, String pwd) {
boolean flag = false;
try {
DBconn.init();
ResultSet rs = DBconn.selectSql("select * from userdata where user='"+name+"' and password='"+pwd+"'");
while(rs.next()){
if(rs.getString("user").equals(name) && rs.getString("password").equals(pwd)){
flag = true;
}
}
DBconn.closeConn();
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
public List<User> getUserAll() {
List<User> list = new ArrayList<User>();
try {
DBconn.init();
ResultSet rs = DBconn.selectSql("select * from userdata");
while(rs.next()){
User user = new User();
user.setName(rs.getString("user"));
user.setPwd(rs.getString("password"));
list.add(user);
}
DBconn.closeConn();
return list;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public boolean update(String name, String pwd) {
boolean flag = false;
DBconn.init();
String sql ="update user set user ='"+name
+"' , password ='"+pwd
+"' where user = "+name;
int i =DBconn.addUpdDel(sql);
if(i>0){
flag = true;
}
DBconn.closeConn();
return flag;
}
public boolean delete(String name) {
boolean flag = false;
DBconn.init();
String sql = "delete from userdata where user='"+name+"'";
int i =DBconn.addUpdDel(sql);
if(i>0){
flag = true;
}
DBconn.closeConn();
return flag;
}
}
User(对应数据库中一条User信息)
package com.entity;
public class User {
private String name;
private String pwd;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
(2) 图片增删改查(以卫星图片为例)
PhotoDaoImpl(方法层)
package com.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.entity.Photo;
import com.util.DBconn;
public class PhotoDaoImpl implements PhotoDao {
public boolean add(Photo photo) {
DBconn.init();
int i = 0;
try {
ResultSet rs = DBconn.selectSql("select * from j2ee_satellite_pic");
while(rs.next()){
if(rs.getString("name").equals(photo.getName()) ){
i = 1;
}
}
}
catch (SQLException e) {
e.printStackTrace();
}
if(i==0)
{
i = DBconn.addUpdDel("insert into j2ee_satellite_pic(src,country,name,resolution,latitude_longtitude,ac_time) values('"+photo.getSrc()+"','"+photo.getCountry()+"','"+photo.getName()+"','"+photo.getResolution()+"','"+photo.getLatitude_longitude()+"','"+photo.getAc_time()+"')");
return true;
}
return false;
}
public boolean delete(String name) {
boolean flag = false;
DBconn.init();
String sql = "delete from j2ee_satellite_pic where name='"+ name +"'";
int i = DBconn.addUpdDel(sql);
System.out.print(i);
flag = (i>0)?true:false;
DBconn.closeConn();
System.out.print(flag);
return flag;
}
public boolean update(String name,String country,String resolution,String lalg,String actime) {
boolean flag = false;
DBconn.init();
try {
ResultSet rs = DBconn.selectSql("select name,country,resolution,latitude_longtitude,ac_time from j2ee_satellite_pic where name ='"+name+"'");
while(rs.next()){
if(rs.getString("name").equals(name) ){
if(country=="")
{
country = rs.getString("country");
}
if(resolution=="")
{
resolution = rs.getString("resolution");
}
if(lalg=="")
{
lalg = rs.getString("latitude_longtitude");
}
if(actime=="")
{
actime = rs.getString("ac_time");
}
}
}
}
catch (SQLException e) {
e.printStackTrace();
}
//对图库的值进行更新
String sql1 ="update j2ee_satellite_pic set country ='"+ country
+"' , resolution ='"+resolution + "', latitude_longtitude ='"
+ lalg + "' , ac_time = '" + actime
+"' where name = '"+name + "'";
System.out.print(sql1);
int j = DBconn.addUpdDel(sql1);
if(j>0)
flag = true;
else {
flag = false;
}
return flag;
}
public List <Photo> search(String sql){
List<Photo> photolistList = new ArrayList<Photo>();
try {
DBconn.init();
ResultSet rs = DBconn.selectSql(sql);
while(rs.next()){
Photo photo = new Photo();
System.out.println(rs.getString("name"));
photo.setSrc(rs.getString("src"));
photo.setName(rs.getString("name"));
photo.setCountry(rs.getString("country"));
photo.setResolution(rs.getString("resolution"));
photo.setLatitude_longitude(rs.getString("latitude_longtitude"));
photo.setAc_time(rs.getString("ac_time"));
photolistList.add(photo);
}
DBconn.closeConn();
} catch (SQLException e) {
e.printStackTrace();
}
return photolistList;
}
public List <Photo> getAllPhotos(){
List<Photo> photolistList = new ArrayList<Photo>();
try {
DBconn.init();
String sql = "select * from j2ee_satellite_pic";
ResultSet rs = DBconn.selectSql(sql);
while(rs.next()){
Photo photo = new Photo();
System.out.println(rs.getString("name"));
photo.setSrc(rs.getString("src"));
photo.setName(rs.getString("name"));
photo.setCountry(rs.getString("country"));
photo.setResolution(rs.getString("resolution"));
photo.setLatitude_longitude(rs.getString("latitude_longtitude"));
photo.setAc_time(rs.getString("ac_time"));
photolistList.add(photo);
}
DBconn.closeConn();
} catch (SQLException e) {
e.printStackTrace();
}
return photolistList;
}
}
图片增加
在这个部分我将介绍两种存储图片的方式并将它们的代码放下来,第一种是将图片存到本地的服务器中,然后获得图片路径并将图片路径存到数据库中。第二种方法是将图片以二进制流的形式读入,然后直接将二进制流存在数据库中,这里我强烈选择第一种,虽然第二种方便很多,但是数据库的资源是极其有限的,直接存图片到数据库中效率是很低的。
第一种方法(推荐):
增加图片(AddPictureServlet)
package com.servlet;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import com.dao.LogDaoImpl;
import com.dao.PhotoDao;
import com.dao.PhotoDaoImpl;
import com.dao.p;
import com.entity.Photo;
public class AddPictureServlet extends HttpServlet {
public AddPictureServlet() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String method = request.getParameter("method");
try {
switch (method) {
case "add":
//转接给相对应的函数去处理相关数据。
addDVDinfo(request, response);
break;}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();}
}
/**
* <p>
* 这个函数实现了增加dvd的功能
* <p>
* @throws SQLException
* @throws ServletException
*/
private static void addDVDinfo(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException, ServletException {
List<String> list=new ArrayList<String>();
String filename=p.getPhotoNewName();
ServletContext servletContext=null;
servletContext=request.getSession().getServletContext();
//数据库中存储格式:/webTest/imgs/***.jpg
//第一步:获取页面上上传的图片资源
List<FileItem> items=p.getRequsetFileItems(request,servletContext);
String isLoadToSQL;
/*
* Date date = new Date(); DateFormat format = new
* SimpleDateFormat("yyyy-MM-dd"); String currentData = format.format(date);
* String name = request.getParameter("name");
*/
Photo photo = new Photo();
for(FileItem item:items) {
if(!item.isFormField()){
//判断后缀名是否是jpg
if(p.isGif(item)) {
isLoadToSQL=p.saveFile(item,filename);
System.out.println(isLoadToSQL);
}else {
System.out.println("后缀格式有误,保存文件失败");
}
}
else {
/*获取表单中的非文件值
表单中的空间name值*/
System.out.println("name值: "+item.getFieldName());
/*该name值空间中的value值*/
System.out.println(item.getString("UTF-8"));
list.add(item.getString("UTF-8"));
}
}
String fileaddress1 = "pic/satellitepic/"+filename;
String name = list.get(0);
String country = list.get(1);
String resolution = list.get(2);
String lalg = list.get(3);
String actime = list.get(4);
String user = list.get(5);//记录操作者
photo.setSrc(fileaddress1);
photo.setName(name);
photo.setCountry(country);
photo.setResolution(resolution);
photo.setLatitude_longitude(lalg);
photo.setAc_time(actime);
PhotoDao ph = new PhotoDaoImpl();
HttpSession session = request.getSession();
Boolean x = ph.add(photo);
if(x==true) {
//增加日志
SimpleDateFormat sdf = new SimpleDateFormat();// 格式化时间
sdf.applyPattern("yyyy-MM-dd HH:mm:ss a");// a为am/pm的标记
Date date = new Date();// 获取当前时间
String time = sdf.format(date).toString();
LogDaoImpl tempDaoImpl = new LogDaoImpl();
tempDaoImpl.add(user,"增加", time, "卫星图片", name);
//得到所有图片
PhotoDaoImpl photoService = new PhotoDaoImpl();
List<Photo> PhotoList = new ArrayList<Photo>();
PhotoList = photoService.getAllPhotos();
request.setAttribute("PhotoList",PhotoList);
request.setAttribute("user", user);
session.setAttribute("operationMsg", "图片增加成功!");
request.getRequestDispatcher("SatellitePic.jsp").forward(request, response);
}
else {
PhotoDaoImpl photoService = new PhotoDaoImpl();
List<Photo> PhotoList = new ArrayList<Photo>();
PhotoList = photoService.getAllPhotos();
request.setAttribute("PhotoList",PhotoList);
request.setAttribute("user", user);
session.setAttribute("operationMsg", "图片增加失败,已存在同名图片!");
request.getRequestDispatcher("SatellitePic.jsp").forward(request, response);
}
}
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
辅助增加图片的类p
package com.dao;
import java.io.File;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
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 p {
/**
*这个函数的功能是获取前端的数据集合,将文件打包成File以便后续操作
*/
public static List<FileItem> getRequsetFileItems(HttpServletRequest request,ServletContext servletContext){
boolean isMultipart=ServletFileUpload.isMultipartContent(request);
if(isMultipart) {
DiskFileItemFactory factory = new DiskFileItemFactory();
String str="javax.servelet.context.tempdir";
File repository=(File) servletContext.getAttribute(str);
factory.setRepository(repository);
ServletFileUpload upload=new ServletFileUpload(factory);
try {
return upload.parseRequest(request);
}catch (FileUploadException e) {
// TODO: handle exception
return null;
}
}else {
return null;
}
}
/**
*这个函数的功能是将文件传到预先设置的绝对路径中,也就是项目里的imgs文件夹
*/
public static String saveFile(FileItem item,String fileName) {
File savePath=new File("C:javaeclipseImageManagerWebContentpicsatellitepic");
if(!savePath.exists()) {
savePath.mkdirs();
}
File uploadFile=new File(savePath+File.separator+fileName);
String fileaddress = "pic/satellitepic/"+fileName;
try{
item.write(uploadFile);
System.out.println("保存文件成功");
return fileaddress;
}catch(Exception e){
System.out.println("保存文件失败");
}
return "false";
}
/**
*这个函数的功能是获取当前时间点与1970年的间隔秒数
*/
public static int getSecondTimestamp(Date date){
if (null == date) {
return 0;
}
String timestamp = String.valueOf(date.getTime());
System.out.println(timestamp);
int length = timestamp.length();
if (length > 3) {
return Integer.valueOf(timestamp.substring(0,length-3));
} else {
return 0;
}
}
/**
*
*这个函数的功能是得到新的照片名称
*/
public static String getPhotoNewName() {
Date date=new Date();
int second=getSecondTimestamp(date);
String fileName=String.valueOf(second)+".jpg";
return fileName;
}
/**
*这个函数的功能是判断文件后缀是否是jpg格式
*/
public static boolean isGif(FileItem item) {
String fileFullName=item.getName();
File fileInfo=new File(fileFullName);
String suffix = fileInfo.getName().substring(fileInfo.getName().lastIndexOf(".") + 1);
if(suffix.equals("jpg")) {
return true;
}
return false;
}
}
第二种方法(不推荐):
package com.servlet;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
//这个方法是将路径变为二进制流存在路径中 但因为效率不高没被使用
@WebServlet("/uploadServlet")
@MultipartConfig(maxFileSize = 16177215) // upload file's size up to 16MB
public class FileUploadDBServlet extends HttpServlet {
// database connection settings
private String dbURL = "jdbc:mysql://localhost:3306/mysql?useUnicode=true&characterEncoding=utf-8";
private String dbUser = "root";
private String dbPass = "WAMM0609dd";
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// gets values of text fields
String name = request.getParameter("pic_name");
String country = request.getParameter("sat_nationality");
String resolution = request.getParameter("sat_resolution");
String lalg = request.getParameter("sat_longtitude");
String actime = request.getParameter("sat_actime");
System.out.println(name);
System.out.println(country);
System.out.println(resolution);
System.out.println(lalg);
System.out.println(actime);
InputStream inputStream = null; // input stream of the upload file
// obtains the upload file part in this multipart request
Part filePart = request.getPart("sat_address");
if (filePart != null) {
// prints out some information for debugging
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
// obtains input stream of the upload file
inputStream = filePart.getInputStream();
}
Connection conn = null; // connection to the database
String message = null; // message will be sent back to client
try {
// connects to the database
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
// constructs SQL statement
String sql = "INSERT INTO j2ee_satellite_pic (name,country,resolution,latitude_longtitude,ac_time,src) values (?,?,?,?,?,?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, name);
statement.setString(2, country);
statement.setString(3, resolution);
statement.setString(4, lalg);
statement.setString(5, actime);
if (inputStream != null) {
// fetches input stream of the upload file for the blob column
statement.setBlob(6, inputStream);
}
// sends the statement to the database server
int row = statement.executeUpdate();
if (row > 0) {
message = "File uploaded and saved into database";
}
} catch (SQLException ex) {
message = "ERROR: " + ex.getMessage();
ex.printStackTrace();
} finally {
if (conn != null) {
// closes the database connection
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
// sets the message in request scope
request.setAttribute("Message", message);
// forwards to the message page
getServletContext().getRequestDispatcher("/Message.jsp").forward(request, response);
}
}
}
第二种方法大家看看就好,作者自己先实现了第二种,但是发现很不好,然后连夜更换了全部后台。
图片删除
DeleteServlet
package com.servlet;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
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;
import com.dao.LogDaoImpl;
import com.dao.PhotoDaoImpl;
import com.dao.UserDaoImpl;
import com.entity.Photo;
public class DeleteServlet extends HttpServlet { //需要继承HttpServlet 并重写doGet doPost方法
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response); //将信息使用doPost方法执行 对应jsp页面中的form表单中的method
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
String name = request.getParameter("sat_name"); //得到jsp页面传过来的参数
String user = request.getParameter("username");
System.out.println(name);
PhotoDaoImpl tempDaoImpl = new PhotoDaoImpl();
boolean i = tempDaoImpl.delete(name);
System.out.print(i);
if(i==true)
{
//增加日志
SimpleDateFormat sdf = new SimpleDateFormat();// 格式化时间
sdf.applyPattern("yyyy-MM-dd HH:mm:ss a");// a为am/pm的标记
Date date = new Date();// 获取当前时间
String time = sdf.format(date).toString();
LogDaoImpl logDaoImpl = new LogDaoImpl();
logDaoImpl.add(user,"删除", time, "卫星图片", name);
UserDaoImpl userService = new UserDaoImpl();
PhotoDaoImpl photoService = new PhotoDaoImpl();
List<Photo> PhotoList = new ArrayList<Photo>();
PhotoList = photoService.getAllPhotos();
request.setAttribute("PhotoList",PhotoList);
request.setAttribute("user",user);
session.setAttribute("operationMsg","删除成功!");
request.getRequestDispatcher("SatellitePic.jsp").forward(request, response);
}
else {
PhotoDaoImpl photoService = new PhotoDaoImpl();
List<Photo> PhotoList = new ArrayList<Photo>();
PhotoList = photoService.getAllPhotos();
request.setAttribute("PhotoList",PhotoList);
request.setAttribute("user", user);
session.setAttribute("operationMsg","删除失败,请输入正确的名字!");
request.getRequestDispatcher("SatellitePic.jsp").forward(request, response);
}
}
}
图片修改
这个这个地方需要注意的是假如用户在表单中不输入某个参数,数据库的这个值不应该修改而是保留不变,作者这个地方的方法比较物理,假如有比较精妙的SQL语句一定要跟作者交流!
UpdateSevlet
package com.servlet;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
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;
import com.dao.LogDaoImpl;
import com.dao.PhotoDaoImpl;
import com.entity.Photo;
import com.util.DBconn;
public class UpdateServlet extends HttpServlet { //需要继承HttpServlet 并重写doGet doPost方法
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response); //将信息使用doPost方法执行 对应jsp页面中的form表单中的method
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("sat_name");
String country = request.getParameter("sat_nationality");
String resolution = request.getParameter("sat_resolution");
String lalg = request.getParameter("sat_latitude_longtitude");
String actime = request.getParameter("sat_actime");//得到jsp页面传过来的参数
String user = request.getParameter("username");
System.out.println(name);
PhotoDaoImpl photoDaoImpl = new PhotoDaoImpl();
boolean a = photoDaoImpl.update(name, country, resolution, lalg, actime);
HttpSession session = request.getSession();
if(a==true)
{
//增加日志
SimpleDateFormat sdf = new SimpleDateFormat();// 格式化时间
sdf.applyPattern("yyyy-MM-dd HH:mm:ss a");// a为am/pm的标记
Date date = new Date();// 获取当前时间
String time = sdf.format(date).toString();
LogDaoImpl logDaoImpl = new LogDaoImpl();
logDaoImpl.add(user,"更新", time, "卫星图片", name);
PhotoDaoImpl photoService = new PhotoDaoImpl();
List<Photo> PhotoList = new ArrayList<Photo>();
PhotoList = photoService.getAllPhotos();
request.setAttribute("user",user);
request.setAttribute("PhotoList",PhotoList);
session.setAttribute("operationMsg","图像信息更新成功!");
request.getRequestDispatcher("SatellitePic.jsp").forward(request, response);
}
else {
PhotoDaoImpl photoService = new PhotoDaoImpl();
List<Photo> PhotoList = new ArrayList<Photo>();
PhotoList = photoService.getAllPhotos();
request.setAttribute("user",user);
request.setAttribute("PhotoList",PhotoList);
session.setAttribute("operationMsg","图像信息更新失败,请正确输入图片名!" );
request.getRequestDispatcher("SatellitePic.jsp").forward(request, response);
}
DBconn.closeConn();
}
}
图片查找
这里实现的是模糊查找,也就是SQL语句中使用 'where parameter like %XXX%'这种结构。
SearchServlet
package com.servlet;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
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;
import com.dao.LogDaoImpl;
import com.dao.PhotoDaoImpl;
import com.entity.Photo;
public class SearchServlet extends HttpServlet { //需要继承HttpServlet 并重写doGet doPost方法
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response); //将信息使用doPost方法执行 对应jsp页面中的form表单中的method
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("sat_name");
String country = request.getParameter("sat_nationality");
String resolution = request.getParameter("sat_resolution");
String lalg = request.getParameter("sat_latitude_longtitude");
String actime = request.getParameter("sat_actime");//得到jsp页面传过来的参数
String user = request.getParameter("username");
if(name==null)
name = "";
if(country==null)
country = "";
if(resolution==null)
resolution = "";
if(lalg==null)
lalg = "";
if(actime==null)
actime = "";
System.out.println(name);
String sql ="select * from j2ee_satellite_pic where name like '%" + name + "%'" + " and"
+ " country like '%" + country + "%' and"
+ " resolution like '%" + resolution + "%' and"
+ " latitude_longtitude like '%" + lalg + "%' and"
+ " ac_time like '%" + actime + "%'";
System.out.println(sql);
List<Photo> list = new ArrayList <Photo>();
PhotoDaoImpl photoDaoImpl = new PhotoDaoImpl();
list = photoDaoImpl.search(sql);
HttpSession session = request.getSession();
boolean flag = list.isEmpty();
System.out.println(list.isEmpty());
if(flag==false)
{
/*
* for(Photo a:list) { System.out.println(a.getSrc());
* System.out.println(a.getName()); System.out.println(a.getCountry());
* System.out.println(a.getResolution());
* System.out.println(a.getLatitude_longitude());
* System.out.println(a.getAc_time()); }
*/
//增加日志
SimpleDateFormat sdf = new SimpleDateFormat();// 格式化时间
sdf.applyPattern("yyyy-MM-dd HH:mm:ss a");// a为am/pm的标记
Date date = new Date();// 获取当前时间
String time = sdf.format(date).toString();
LogDaoImpl logDaoImpl = new LogDaoImpl();
logDaoImpl.add(user,"查询", time, "卫星图片", name);
request.setAttribute("user",user);
request.setAttribute("PhotoList",list);
session.setAttribute("operationMsg", "查询成功!");
request.getRequestDispatcher("SatellitePic.jsp").forward(request, response);
}
else {
request.setAttribute("user",user);
request.setAttribute("PhotoList",list);
session.setAttribute("operationMsg", "没有符合条件的图片!");
request.getRequestDispatcher("SatellitePic.jsp").forward(request, response);
}
}
}
以上就是我的后台中最为核心的部分了。