javaweb实现简单的评论系统

简单的评论系统

首先创建数据库

CREATE DATABASE IF NOT EXISTS ssm DEFAULT CHARSET utf8 COLLATE utf8_general_ci;

然后创建表格

CREATE TABLE img(
id BIGINT not NULL auto_increment,
path VARCHAR(255) ,
fid BIGINT,
PRIMARY KEY (id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE feel(
id BIGINT not NULL auto_increment,
path VARCHAR(255) ,
fid BIGINT,
PRIMARY KEY (id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

通过https://github.com/mybatis/generator/releases 创建逆向工程





    
        
            
            
        
        
        
        
        
        
            
        

        
        
            
            
            
            
        
        
        
            
            
        
        
        
            
            
        
        
        

得到ImgMapper

public interface ImgMapper {
    int countByExample(ImgExample example);

    int deleteByExample(ImgExample example);

    int insert(Img record);

    int insertSelective(Img record);

    List selectByExample(ImgExample example);

    int updateByExampleSelective(@Param("record") Img record, @Param("example") ImgExample example);

    int updateByExample(@Param("record") Img record, @Param("example") ImgExample example);
public interface FeelMapper {
    int countByExample(FeelExample example);

    int deleteByExample(FeelExample example);

    int insert(Feel record);

    int insertSelective(Feel record);

    List selectByExample(FeelExample example);

    int updateByExampleSelective(@Param("record") Feel record, @Param("example") FeelExample example);

    int updateByExample(@Param("record") Feel record, @Param("example") FeelExample example);
}

配置applicationContext.xml



    
    

    
    


    
    
        
        
        
        
    

    
    
        
        
    

    
    
        
        
    
    
        
    


    
    
        
            
            
            
            
        
    

    
    
        
        
    

配置db.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC&characterEncoding=utf8
jdbc.username = root
jdbc.password = root

配置ftp.properties

ftpclient.host=192.168.231.148
ftpclient.port = 21
ftpclient.username = ftpuser
ftpclient.password = ftpuser
ftpclient.basePath = /home/ftpuser
ftpclient.filepath = /test

配置springmvc.xml



    
    

    
    


    
    
    
    

    
    

配置web.xml





    
        contextConfigLocation
        classpath:applicationContext.xml
    
    
    
        org.springframework.web.context.ContextLoaderListener
    
    
    
        springmvc
        org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation
            classpath:springmvc.xml
        
        1
    
    
        springmvc
        /
    
    
    
        encoding
        org.springframework.web.filter.CharacterEncodingFilter
        
            encoding
            utf-8
        
    
    
        encoding
        /*
    

编写FtpUtil类用于文件上传

package com.zxc.utils;



import org.apache.commons.net.ftp.*;

import java.io.*;

public class FtpUtils {
    public static boolean uploadFile(String host, int port, String username, String password, String basePath, String filePath, String filename, InputStream input){
        boolean result = false;


        FTPClient ftp =new FTPClient();
        try {
            int reply;

            ftp.connect(host,port);
            ftp.login(username,password);

            reply=ftp.getReplyCode();
            if(!FTPReply.isPositiveCompletion(reply)){
                ftp.disconnect();
                return result;
            }
            if(!ftp.changeWorkingDirectory(basePath+filePath)){
                String[] dirs = filePath.split("/");
                String tempPath = basePath;
                for (String dir:dirs){
                    if(null == dir || "".equals(dir))
                        continue;
                    tempPath += "/"+dir;
                    if (!ftp.changeWorkingDirectory(tempPath)){
                        if(!ftp.makeDirectory(basePath)){
                            return result;
                        }else{
                            ftp.changeWorkingDirectory(tempPath);
                        }
                    }
                }
            }
            //设置为被动模式
            ftp.enterLocalPassiveMode();
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            if(!ftp.storeFile(filename,input)){
                return result;
            }
            input.close();
            ftp.logout();
            result = true;

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(ftp.isConnected()){
                try {
                    ftp.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
    public static boolean downloadFile(String host, int port, String username, String password, String remotePath,
                                       String fileName, String localPath) {
        boolean result = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.connect(host, port);
            // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
            ftp.login(username, password);// 登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return result;
            }
            ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
            FTPFile[] fs = ftp.listFiles();
            for (FTPFile ff : fs) {
                if (ff.getName().equals(fileName)) {
                    File localFile = new File(localPath + "/" + ff.getName());

                    OutputStream is = new FileOutputStream(localFile);
                    ftp.retrieveFile(ff.getName(), is);
                    is.close();
                }
            }

            ftp.logout();
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }
    public static void main(String[] args) throws FileNotFoundException {
        InputStream is = new FileInputStream("E:/timg.jpg");
        boolean result = FtpUtils.uploadFile("192.168.139.131", 21, "ftpuser", "ftpuser", "/home/ftpuser", "/",
                "qqq.jpg", is);
        if (result)
            System.out.println("上传成功");
        else
            System.out.println("上传失败");
    }





}

创建IDUtils 用于生成随机编号

package com.zxc.utils;

import java.util.Random;

public class IDUtils {
    public static String genImageName(){
        long mills = System.currentTimeMillis();
        Random  random = new Random();
        int end3 = random.nextInt(999);
        String str = mills + String.format("%03d",end3);
        return str;
    }
    public static long genItemId(){
        long millis = System.currentTimeMillis();
        Random  random = new Random();
        int end2  = random.nextInt(99);
        String str = millis+String.format("%03d",end2);
        long id =new Long(str);
        return id;
    }

    public static void main(String[] args){
        System.out.println(genImageName());
        System.out.println(Integer.MAX_VALUE+":"+Long.MAX_VALUE);
    }
}

创建service接口

package com.zxc.service;

import com.zxc.pojo.Feel;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;

public interface FeelService {

    Map upload(MultipartFile imgFile) throws IOException;


    int insFeel(Feel feel, List imgs);
}

创建service实现类调用upload 方法还有insFeel方法

package com.zxc.service.impl;

import com.zxc.mapper.FeelMapper;
import com.zxc.mapper.ImgMapper;
import com.zxc.pojo.Feel;
import com.zxc.pojo.Img;
import com.zxc.service.FeelService;
import com.zxc.utils.FtpUtils;
import com.zxc.utils.IDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.swing.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class FeelServiceImpl implements FeelService {
    @Value("${ftpclient.host}")
    private String host;
    @Value("${ftpclient.port}")
    private int port;
    @Value("${ftpclient.username}")
    private String username;
    @Value("${ftpclient.password}")
    private String password;
    @Value("${ftpclient.basePath}")
    private String basePath;
    @Value("${ftpclient.filepath}")
    private String filePath;

    @Resource
    private FeelMapper feelMapper;
    @Resource
    private ImgMapper imgMapper;




    @Override
    public Map upload(MultipartFile imgFile) throws IOException {
        String fileName = UUID.randomUUID()+imgFile.getOriginalFilename().substring(imgFile.getOriginalFilename().indexOf("."));
        boolean result = FtpUtils.uploadFile(host,port,username,password,basePath,filePath,fileName,imgFile.getInputStream());
        System.out.println(result);
        Map  map = new HashMap<>();
        if (result){
            map.put("error",0);
            map.put("url","http://192.168.231.148"+filePath+"/"+fileName);

        }else{
            map.put("error",1);
            map.put("message","图片上传失败");

        }
        return map;
    }

    @Override
    public int insFeel(Feel feel, List imgs) {
        long id = IDUtils.genItemId();
        feel.setId(id);
        int index = feelMapper.insert(feel);
        if(index > 0){
            for(String string:imgs){
                Img img = new Img();
                img.setFid(id);
                img.setPath(string);
                index += imgMapper.insertSelective(img);

            }
            if(index == imgs.size()+1){
                return 1;
            }
        }

        //新增失败
        return 0;
    }
}

最后编写控制器

package com.zxc.controller;
import java.util.List;
import java.util.Map;

import com.zxc.pojo.Feel;
import com.zxc.service.FeelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

@Controller
public class FeelController {
    @Resource
    private FeelService feelService;


    @RequestMapping("upload")
    @ResponseBody
    public Map upload(MultipartFile imgFile){
        try {
            return feelService.upload(imgFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    @RequestMapping("insert")
    public String insert(Feel feel , @RequestParam("imgs") List imgs){
        int index = feelService.insFeel(feel,imgs);
        if (index>0){
            return  "/success.jsp";

        }else{
            return "/error.jsp";
        }
    }
}

你可能感兴趣的:(javaweb实现简单的评论系统)