第二个小项目:在线音乐服务器(更新中,后端基本完毕)

目录

1.项目结构

1.1 项目单元测试目录

 2.项目的准备工作

3. 数据库设计

4. 用户+音乐模块设计

4.1 创建User类

4. 2 创建Music类

4.3 创建JDBCUtils类

 4.4 创建UserDao类

4.5 创建MusicDao类

4.6 创建LoveMusicDao

4.7 创建单元测试类

4.7.1 UserDaoTest

4.7.2 MusicDaoTest

4.7.3 LoveMusicDaoTest

5. Servlet实现

5.1 LoginServlet实现

5.2 上传音乐UploadMusicServlet实现

5.3 FindMusicServlet实现

5.4  删除音乐信息实现

5.4.1 删除某个音乐(DeleteMusicServlet)

5.4.2 删除选中音乐

5.5 添加喜欢的音乐到喜欢列表LoveMusicServlet

5.6 查找我喜欢的音乐列表FindLoveMusicServlet

5.7 移除我喜欢的音乐RemoveLoveServlet


1.项目结构

第二个小项目:在线音乐服务器(更新中,后端基本完毕)_第1张图片第二个小项目:在线音乐服务器(更新中,后端基本完毕)_第2张图片 

1.1 项目单元测试目录

第二个小项目:在线音乐服务器(更新中,后端基本完毕)_第3张图片

 2.项目的准备工作

1. 搭建一个空的maven项目(之前有博客已经写了)

2. 对maven进行基本的配置

        2.1 首先在目录 src/main 下创建一个文件目录 webapp/WEB-INF/web.xml

        web.xml内容为:



  2.2 配置maven 的核心页 pom.xml



    4.0.0

    org.example
    Jaymusic
    1.0-SNAPSHOT

    war

    
        
        
            com.fasterxml.jackson.core
            jackson-databind
            2.11.4
        
        
            com.fasterxml.jackson.core
            jackson-core
            2.11.4
        
        
            com.fasterxml.jackson.core
            jackson-annotations
            2.11.4
        
        
        
            javax.servlet
            javax.servlet-api
            3.1.0
        
        
        
            mysql
            mysql-connector-java
            5.1.47
        
    


    
    
    JayMusic

    


3. 数据库设计

在 src/main 目录下创建 db.sql 文件

写入以下代码用于创建数据库和表:

drop database if exists `musicserver`;
create database if not exists `musicserver` character set utf8;

use `musicserver`;

DROP TABLE IF EXISTS `music`;
CREATE TABLE `music` (
                         `id` int PRIMARY KEY AUTO_INCREMENT,
                         `title` varchar(50) NOT NULL,
                         `singer` varchar(30) NOT NULL,
                         `time` varchar(13) NOT NULL,
                         `url` varchar(100) NOT NULL,
                         `userid` int(11) NOT NULL
);
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
                        `id` INT PRIMARY KEY AUTO_INCREMENT,
                        `username` varchar(20) NOT NULL,
                        `password` varchar(32) NOT NULL,
                        `age` INT NOT NULL,
                        `gender` varchar(2) NOT NULL,
                        `email` varchar(50) NOT NULL
);
DROP TABLE IF EXISTS `lovemusic`;
CREATE TABLE `lovemusic` (
                             `id` int PRIMARY KEY AUTO_INCREMENT,
                             `user_id` int(11) NOT NULL,
                             `music_id` int(11) NOT NULL
);
INSERT INTO user(username,password,age,gender,email)
VALUES("dyh","123","20","男","[email protected]");

需要3张表:user表

                    music表

                    lovemusic表

4. 用户+音乐模块设计

创建实体类

创建entity包

4.1 创建User类

public class User {
    private int id;
    private String username;
    private String password;
    private String gender;
    private int age;
    private String email;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", gender='" + gender + '\'' +
                ", age=" + age +
                ", email='" + email + '\'' +
                '}';
    }
}

4. 2 创建Music类

public class Music {
    private int id;
    private String title;
    private String singer;
    private String time;
    private String url;
    private int userid;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getSinger() {
        return singer;
    }

    public void setSinger(String singer) {
        this.singer = singer;
    }

    public String getDate() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public int getUserid() {
        return userid;
    }

    public void setUserid(int userid) {
        this.userid = userid;
    }

    @Override
    public String toString() {
        return "Music{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", singer='" + singer + '\'' +
                ", time=" + time +
                ", url='" + url + '\'' +
                ", userid=" + userid +
                '}';
    }
}

封装数据库操作

创建一个util包

4.3 创建JDBCUtils类

public class DBUtils {
    private static String url = "jdbc:mysql://127.0.0.1:3306/musicserver?useSSL=false";
    private static String password = "123456";
    private static String username = "root";
    private static volatile DataSource DATASOURCE;
    private static DataSource getDataSource(){
// 双重校验锁
        if(DATASOURCE == null){
            synchronized (DBUtils.class){
                if(DATASOURCE == null){
                    DATASOURCE = new MysqlDataSource();
                    ((MysqlDataSource) DATASOURCE).setUrl(url);
                    ((MysqlDataSource) DATASOURCE).setUser(username);
                    ((MysqlDataSource) DATASOURCE).setPassword(password);
                }
            }
        }
        return DATASOURCE;
    }
    public static Connection getConn(){
        try {
            Connection connection = getDataSource().getConnection();
            return connection;
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("获取数据库连接失败");
        }
    }
    public static void getClose(Connection connection, PreparedStatement statement,
                                ResultSet resultSet) {
        if(resultSet!=null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(statement!=null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(connection!=null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

创建dao包

 4.4 创建UserDao类

1 实现UserDao.login

2 实现UserDao.register

public class UserDao {
    /**
     *
     * 依据用户名查询,如果找不到,返回null,
     * 否则返回一个User对象(包含了用户的所有信息)
     *
     */
    public User login(User loginUser) {
        //先定义JDBC中最重要的3个类
        Connection con = null;
        PreparedStatement prs = null;
        ResultSet resultSet = null;
        User user = null;

        try {
            con = DBUtils.getConn();
            String sql = "select * from user where username = ? and  password = ?";
            prs = con.prepareStatement(sql);
            prs.setString(1, loginUser.getUsername());
            prs.setString(2, loginUser.getPassword());

            resultSet = prs.executeQuery();

            if(resultSet.next()){
                user = new User();
                user.setId(resultSet.getInt("id"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                user.setAge(resultSet.getInt("age"));
                user.setGender(resultSet.getString("gender"));
                user.setEmail(resultSet.getString("email"));
            }else {
                System.out.println("登录失败");
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DBUtils.getClose(con, prs ,resultSet);
        }
        return user;
    }

    /**
     * 注册
     */
    public void insertUser(User user) {
        Connection con = null;
        PreparedStatement prs = null;
        ResultSet resultSet = null;

        try {
        con = DBUtils.getConn();
        String sql = "insert into user(username,password,age,gender,email) values (?,?,?,?,?) ";
        prs = con.prepareStatement(sql);

        prs.setString(1, user.getUsername());
        prs.setString(2, user.getPassword());
        prs.setInt(3, user.getAge());
        prs.setString(4, user.getGender());
        prs.setString(5, user.getEmail());

        int ret = prs.executeUpdate();

        if(ret == 1){
            System.out.println("注册成功");
        }else {
            System.out.println("注册失败");
        }

        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            DBUtils.getClose(con, prs, resultSet);
        }
    }

    public static void main1(String[] args) {
        User user = new User();
        user.setUsername("dyh");
        user.setPassword("123");

        UserDao userDao = new UserDao();
        User user1 = userDao.login(user);

        System.out.println(user1);
    }

    public static void main(String[] args) {
        User user = new User();
        user.setUsername("wed");
        user.setPassword("123");
        user.setAge(19);
        user.setGender("男");
        user.setEmail("[email protected]");

        UserDao userDao = new UserDao();
        userDao.insertUser(user);
    }
}

4.5 创建MusicDao类

1 实现MusicDao.Insert

2 实现MusicDao.findMusic

3 实现MusicDao.findMusicById

4 实现MusicDao.findMusicByKey

5 实现MusicDao.deleteMusicById

public class MusicDao {
    /**
     * 上传音乐
     * @param title
     * @param singer
     * @param time
     * @param url
     * @param userid
     * @return
     */
    public int insert(String title, String singer,String time, String url, int userid) {
        Connection con = null;
        PreparedStatement prs = null;
        ResultSet resultSet = null;

        try {
            con = DBUtils.getConn();
            String sql = "insert into music(title,singer,time,url,userid) values (?,?,?,?,?)";
            prs = con.prepareStatement(sql);

            prs.setString(1,title);
            prs.setString(2,singer);
            prs.setString(3,time);
            prs.setString(4,url);
            prs.setInt(5,userid);

            int ret = prs.executeUpdate();
            if(ret == 0){
                return 0;
            }
            return ret;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DBUtils.getClose(con, prs, null);
        }
        return 0;
    }

    /**
     * 查询全部歌单
     */
    public List findMusic(){
        Connection con = null;
        PreparedStatement prs = null;
        ResultSet resultSet = null;
        List musicList = new ArrayList();

        try {
            con = DBUtils.getConn();
            String sql = "select * from music";
            prs = con.prepareStatement(sql);

             resultSet = prs.executeQuery();

             while (resultSet.next()){
                 Music music = new Music();
                 music.setId(resultSet.getInt("id"));
                 music.setTitle(resultSet.getString("title"));
                 music.setSinger((resultSet.getString("singer")));
                 music.setTime(resultSet.getString("time"));
                 music.setUrl(resultSet.getString("url"));
                 music.setUserid(resultSet.getInt("userid"));
                 musicList.add(music);
             }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DBUtils.getClose(con, prs, resultSet);
        }
        return musicList;
    }


    /**
     * 根据id查找音乐
     * @param id
     * @return
     */
    public Music findMusicById(int id){
        Connection con = null;
        PreparedStatement prs = null;
        ResultSet resultSet = null;
        Music music = null;

        try {
            con = DBUtils.getConn();
            String sql = "select * from music where id=?";
            prs = con.prepareStatement(sql);

            prs.setInt(1,id);

            resultSet = prs.executeQuery();
            if(resultSet.next()){
                music = new Music();
                music.setId(resultSet.getInt("id"));
                music.setTitle(resultSet.getString("title"));
                music.setSinger((resultSet.getString("singer")));
                music.setTime(resultSet.getString("time"));
                music.setUrl(resultSet.getString("url"));
                music.setUserid(resultSet.getInt("userid"));
                return music;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtils.getClose(con, prs, resultSet);
        }
        return null;
    }

    /**
     * 根据关键字查询歌单,模糊查询
     */
    public List findMusicByKey(String str){
        Connection con = null;
        PreparedStatement prs = null;
        ResultSet resultSet = null;
        List musicList = new ArrayList();

        try {
            con = DBUtils.getConn();
            String sql = "select * from music where title like ?";
            prs = con.prepareStatement(sql);
            str = "%"+ str +"%";
            prs.setString(1,str);

            resultSet = prs.executeQuery();

            while (resultSet.next()){
                Music music = new Music();
                music.setId(resultSet.getInt("id"));
                music.setTitle(resultSet.getString("title"));
                music.setSinger((resultSet.getString("singer")));
                music.setTime(resultSet.getString("time"));
                music.setUrl(resultSet.getString("url"));
                music.setUserid(resultSet.getInt("userid"));
                musicList.add(music);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DBUtils.getClose(con, prs, resultSet);
        }
        return musicList;
    }

    /**
     * 删除歌曲:
     */
    public int deleteMusicById(int musicId){
        Connection con = null;
        PreparedStatement prs = null;

        try {
            con = DBUtils.getConn();
            String sql = "delete from  music where id = ?";
            prs = con.prepareStatement(sql);
            prs.setInt(1,musicId);

            int ret = prs.executeUpdate();
            if (ret == 1){
                if(findLoveMusicById(musicId)){
                    int ret2 = deleteLoveMusicById(musicId);
                    if (ret2 == 1){
                        System.out.println("删除成功");
                        return 1;
                    }
                }
                return 1;
            }else {
                return 0;
            }


        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DBUtils.getClose(con, prs, null);
        }
        return 0;
    }

    /**
     * 看中间表是否有该id的音乐数据
     */
    public boolean findLoveMusicById(int musicId){
        Connection con = null;
        PreparedStatement prs = null;
        ResultSet resultSet = null;
        try {
            con = DBUtils.getConn();
            String sql = "select * from lovemusic where music_id=?";
            prs = con.prepareStatement(sql);

            prs.setInt(1,musicId);

            resultSet = prs.executeQuery();
            if(resultSet.next()){
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtils.getClose(con, prs, resultSet);
        }
        return false;
    }

    /**
     * 当删除服务器上的音乐时,同时在我喜欢的列表的数据库中进行删除。
     * @param musicId
     * @return
     */
    public int deleteLoveMusicById(int musicId){
        Connection con = null;
        PreparedStatement prs = null;
        try {
            con = DBUtils.getConn();
            String sql = "delete from lovemusic where music_id=?";
            prs = con.prepareStatement(sql);
            prs.setInt(1,musicId);

            int ret= prs.executeUpdate();
            if(ret == 1){
                return 1;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtils.getClose(con, prs, null);
        }
        return 0;
    }




    public static void main1(String[] args) {
        MusicDao musicDao = new MusicDao();
        musicDao.insert("花海","周杰伦","2021-07-120","music\\花海",1);
    }

    public static void main2(String[] args) {
        MusicDao musicDao = new MusicDao();
        List musicList = musicDao.findMusic();
        for (Music music : musicList){
            System.out.println(music);
        }
    }

    public static void main3(String[] args) {
        MusicDao musicDao = new MusicDao();
        Music music= musicDao.findMusicById(1);
        System.out.println(music);
    }

    public static void main4(String[] args) {
        MusicDao musicDao = new MusicDao();
        List musicList = musicDao.findMusicByKey("花");
        for (Music music : musicList){
            System.out.println(music);
        }
    }

}

4.6 创建LoveMusicDao

1 实现insertLoveMusic

2 实现findLoveMusic

3 实现findLoveMusicByMusicIdAndUserId

4 实现findLoveMusicBykeyAndUID

5 removeLoveMusic

public class LoveMusicDao {
    /**
     * 添加音乐到“喜欢”列表中
     * 用户-》音乐
     * 多对多
     * 需要中间表
     */
    public boolean insertLoveMusic(int userId, int musicId) {
        Connection con = null;
        PreparedStatement prs = null;
        ResultSet resultSet = null;

        try {
            con = DBUtils.getConn();
            String sql = "insert into lovemusic(user_id,music_id) values (?,?)";
            prs = con.prepareStatement(sql);
            prs.setInt(1, userId);
            prs.setInt(2, musicId);

            int ret = prs.executeUpdate();
            if (ret == 1) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtils.getClose(con, prs, null);
        }
        return false;
    }

    /**
     * 查找喜欢的音乐
     * @return
     */
    public List findLoveMusic(int user_id){
        List musicList = new ArrayList();
        Connection con = null;
        PreparedStatement prs = null;
        ResultSet resultSet = null;

        try {
            con = DBUtils.getConn();
            String sql = "select m.id as m_id,title,singer,time,url,userid from" +
                    " lovemusic lm,music m where" +
                    " m.id = lm.music_id and  lm.user_id = ?";
            prs = con.prepareStatement(sql);
            prs.setInt(1,user_id);

            resultSet = prs.executeQuery();
            while (resultSet.next()){
                Music music = new Music();
                music.setId(resultSet.getInt("m_id"));
                music.setTitle(resultSet.getString("title"));
                music.setSinger((resultSet.getString("singer")));
                music.setTime(resultSet.getString("time"));
                music.setUrl(resultSet.getString("url"));
                music.setUserid(resultSet.getInt("userid"));
                musicList.add(music);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtils.getClose(con, prs, null);
        }
        return musicList;
    }

    /**
     * 添加喜欢的音乐的时候,需要先判断该音乐是否存在
     * @param musicID
     * @return
     */
    public boolean findLoveMusicByMusicIdAndUserId(int user_id,int musicID){
        Connection con = null;
        PreparedStatement prs = null;
        ResultSet resultSet = null;

        try {
            con = DBUtils.getConn();
            String sql = "select * from lovemusic where user_id = ? and musicID + ?";
            prs = con.prepareStatement(sql);
            prs.setInt(1,user_id);
            prs.setInt(2,musicID);

            resultSet = prs.executeQuery();
            if (resultSet.next()){
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtils.getClose(con, prs, null);
        }
        return false;
    }

    /**
     * 根据关键字查询喜欢的歌单
     * @param str
     * @return
     */
    public List findLoveMusicBykeyAndUID(String str,int user_id){
        Connection con = null;
        PreparedStatement prs = null;
        ResultSet resultSet = null;
        List musicList = new ArrayList();

        try {
            con = DBUtils.getConn();
            String sql = "select m.id as m_id,title,singer,time,url,userid from" +
                    " lovemusic lm,music m where m.id = lm.music_id and  lm.user_id=? and title like ?";
            prs = con.prepareStatement(sql);
            prs.setInt(1,user_id);
            str = "%"+str+"%";
            prs.setString(2,str);

            resultSet = prs.executeQuery();
            if (resultSet.next()){
                Music music = new Music();
                music.setId(resultSet.getInt("m_id"));
                music.setTitle(resultSet.getString("title"));
                music.setSinger((resultSet.getString("singer")));
                music.setTime(resultSet.getString("time"));
                music.setUrl(resultSet.getString("url"));
                music.setUserid(resultSet.getInt("userid"));
                musicList.add(music);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtils.getClose(con, prs, null);
        }
        return musicList;
    }

    /**
     * @param userId 用户id
     * @param musicId 歌曲id
     * @return 返回受影响的行数
     * 移除当前用户喜欢的这首音乐,因为同一首音乐可能多个用户喜欢,所以需要传入当前用户的id
     */
    public int removeLoveMusic(int userId,int musicId){
        Connection con = null;
        PreparedStatement prs = null;

        try {
            con = DBUtils.getConn();
            String sql = "delete from lovemusic where user_id = ? and music_id = ?";
            prs = con.prepareStatement(sql);
            prs.setInt(1,userId);
            prs.setInt(2,musicId);

            int ret = prs.executeUpdate();
            if (ret == 1){
                return 1;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtils.getClose(con, prs, null);
        }
        return 0;
    }





    public static void main1(String[] args) {
        LoveMusicDao loveMusicDao = new LoveMusicDao();
        loveMusicDao.insertLoveMusic(1, 2);
    }

    public static void main2(String[] args) {
        LoveMusicDao loveMusicDao = new LoveMusicDao();
        List musicList = loveMusicDao.findLoveMusic(1);
        for (Music music : musicList){
            System.out.println(music);
        }
    }

    public static void main3(String[] args) {
        LoveMusicDao loveMusicDao = new LoveMusicDao();
        List loveMusic = loveMusicDao.findLoveMusicBykeyAndUID("花",1);
        System.out.println(loveMusic);
    }

    public static void main4(String[] args) {
        LoveMusicDao loveMusicDao = new LoveMusicDao();
        loveMusicDao.removeLoveMusic(1, 2);
        System.out.println("删除成功");

    }

4.7 创建单元测试类

4.7.1 UserDaoTest

public class UserDaoTest {

    @Test
    public void login() {
        User user = new User();
        user.setUsername("dyh");
        user.setPassword("123");

        UserDao userDao = new UserDao();
        User user1 = userDao.login(user);

        System.out.println(user1);
    }

    @Test
    public void insertUser() {
        User user = new User();
        user.setUsername("wed");
        user.setPassword("123");
        user.setAge(19);
        user.setGender("男");
        user.setEmail("[email protected]");

        UserDao userDao = new UserDao();
        userDao.insertUser(user);
    }
}

4.7.2 MusicDaoTest

public class MusicDaoTest {

    @Test
    public void insert() {
        MusicDao musicDao = new MusicDao();
        musicDao.insert("花海","周杰伦","2021-07-120","music\\花海",1);
    }

    @Test
    public void findMusic() {
        MusicDao musicDao = new MusicDao();
        List musicList = musicDao.findMusic();
        for (Music music : musicList){
            System.out.println(music);
        }
    }

    @Test
    public void findMusicById() {
        MusicDao musicDao = new MusicDao();
        Music music= musicDao.findMusicById(1);
        System.out.println(music);
    }

    @Test
    public void findMusicByKey() {
        MusicDao musicDao = new MusicDao();
        List musicList = musicDao.findMusicByKey("花");
        for (Music music : musicList){
            System.out.println(music);
        }
    }

    @Test
    public void deleteMusicById() {
        MusicDao musicDao = new MusicDao();
        int ret= musicDao.deleteMusicById(1);
        System.out.println(ret);
    }


}

4.7.3 LoveMusicDaoTest

public class LoveMusicDaoTest {

    @Test
    public void insertLoveMusic() {
        LoveMusicDao loveMusicDao = new LoveMusicDao();
        loveMusicDao.insertLoveMusic(1, 2);
    }

    @Test
    public void findLoveMusic() {
        LoveMusicDao loveMusicDao = new LoveMusicDao();
        List musicList = loveMusicDao.findLoveMusic(1);
        for (Music music : musicList){
            System.out.println(music);
        }
    }

    @Test
    public void findLoveMusicByMusicIdAndUserId() {
        LoveMusicDao loveMusicDao = new LoveMusicDao();
        boolean loveMusic = loveMusicDao.findLoveMusicByMusicIdAndUserId(1,1);
        System.out.println(loveMusic);
    }

    @Test
    public void findLoveMusicBykeyAndUID() {
        LoveMusicDao loveMusicDao = new LoveMusicDao();
        List loveMusic = loveMusicDao.findLoveMusicBykeyAndUID("花",1);
        System.out.println(loveMusic);
    }

    @Test
    public void removeLoveMusic() {
        LoveMusicDao loveMusicDao = new LoveMusicDao();
        loveMusicDao.removeLoveMusic(1, 2);
        System.out.println("删除成功");
    }
}

5. Servlet实现

首先在项目根目录下创建一个 servlet 包

包装实现如下servlet类

5.1 LoginServlet实现

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json; charset=utf-8");

        String username = req.getParameter("username");
        String password = req.getParameter("password");

        Map return_map = new HashMap();

        UserDao userDao = new UserDao();
        User loginUser = new User();
        loginUser.setUsername(username);
        loginUser.setPassword(password);

        User user = userDao.login(loginUser);

        if (user == null){
            return_map.put("msg",false);

        }else {
            req.getSession().setAttribute("user",user);
            return_map.put("msg",false);

            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(resp.getWriter(),return_map);
        }
    }
}

5.2 上传音乐UploadMusicServlet实现

上传音乐分为2步:

第一步将音乐上传到服务器

第二步将音乐信息存放到数据库

@WebServlet("/upload")
@MultipartConfig
public class UploadMusicServlet extends HttpServlet {

    private static final String SAVEPATH = "D:\\idea\\workspaces\\Jaymusic\\src\\main\\wabapp\\music";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        User user = (User) req.getSession().getAttribute("user");
        if (user == null){
            System.out.println("没有登录,不能上传");
        }else {
            Part part = req.getPart("filename");

            String header = part.getHeader("Content-Disposition");
            int start = header.lastIndexOf("=");
            String fileName = header.substring(start + 1)
                    .replace("\"", "");


            System.out.println("fileName:"+fileName);
            part.write(SAVEPATH + fileName);

            String singer = req.getParameter("singer");
            System.out.println("歌手:" + singer);


            //插入数据库
            String[] titles = fileName.split("\\.");
            String title = titles[0];
            System.out.println("title:" + title);



            String url = "music/" + title;
            System.out.println("url:" + url);

            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            String time=sdf.format(new Date());

            int userId = user.getId();

            MusicDao musicDao = new MusicDao();
            int ret = musicDao.insert(title, singer, time, url, userId);
            if(ret == 1){
                resp.sendRedirect("list.html");
            }else {
                System.out.println("上传失败");
                part.delete();
            }
        }
    }
}

5.3 FindMusicServlet实现

@WebServlet("/findLoveMusic")
public class FindLoveMusicServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");

        String musicName = req.getParameter("musicName");
        System.out.println("musicName" + musicName);

        User user = (User) req.getSession().getAttribute("user");
        int user_id = user.getId();

        LoveMusicDao lovemusicDao = new LoveMusicDao();
        List musics = new ArrayList();

        if (musicName != null){
            musics = lovemusicDao.findLoveMusicBykeyAndUID(musicName, user_id);
        }else {
            musics = lovemusicDao.findLoveMusic(user_id);
        }

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.writeValue(resp.getWriter(),musics);

    }
}

5.4  删除音乐信息实现

5.4.1 删除某个音乐(DeleteMusicServlet)

获取前端参数id

@WebServlet("deleteServlet")
public class DeleteMusicServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");

        int id = Integer.parseInt(req.getParameter("id"));

        Map return_map = new HashMap();

        MusicDao musicDao = new MusicDao();
        Music music = musicDao.findMusicById(id);
        if (music == null){
            return;
        }

        int ret = musicDao.deleteMusicById(id);
        if(ret == 1){
            File file = new File("D:\\idea\\workspaces\\Jaymusic\\src\\main\\wabapp\\music");
            if (file.delete()){
                return_map.put("msg",true);
            }else {
                return_map.put("msg",false);
            }
        }else {
            return_map.put("msg",false);
        }

        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(resp.getWriter(),return_map);

    }
}

5.4.2 删除选中音乐

获取前端选中的id数组

@WebServlet("/deleteSelMusicServlet")
public class DeleteSelMusicServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");

        Map return_map = new HashMap();

        MusicDao musicDao = new MusicDao();

        String[] sIds = req.getParameterValues("id[]");

        int sum = 0;
        for (int i = 0; i < sIds.length; i++){
            int id = Integer.parseInt(sIds[i]);

            Music music = musicDao.findMusicById(id);
            if (music == null) continue;

            int ret = musicDao.deleteMusicById(id);
            if(ret == 1){
                File file = new File("D:\\idea\\workspaces\\Jaymusic\\src\\main\\wabapp\\music");
                if (file.delete()){
                    sum += ret;
                }else {
                    return_map.put("msg",false);
                    System.out.println("删除失败");
                }
            }else {
                return_map.put("msg",false);
                System.out.println("删除失败");
            }
        }

        if (sum == sIds.length){
            return_map.put("msg",true);
            System.out.println("删除成功");
        }else {
            return_map.put("msg",false);
            System.out.println("删除失败");
        }

        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(resp.getWriter(),return_map);

    }
}

5.5 添加喜欢的音乐到喜欢列表LoveMusicServlet

WebServlet("/loveMusicServlet")
public class LoveMusicServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");

        Map return_map = new HashMap();

        String musicIds = req.getParameter("id");
        int musicId = Integer.parseInt(musicIds);

        User user = (User) req.getSession().getAttribute("user");
        int userID = user.getId();

        LoveMusicDao loveMusicDao = new LoveMusicDao();

        boolean effect2 = loveMusicDao.findLoveMusicByMusicIdAndUserId(userID, musicId);
        if (effect2){
            return_map.put("msg",false);
        }else {
            boolean effect = loveMusicDao.insertLoveMusic(userID, musicId);
            if (effect){
                return_map.put("msg",true);
             }else {
                 return_map.put("msg",false);
            }
        }

        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(resp.getWriter(),return_map);
    }

}

5.6 查找我喜欢的音乐列表FindLoveMusicServlet

@WebServlet("/findLoveMusic")
public class FindLoveMusicServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");

        String musicName = req.getParameter("musicName");
        System.out.println("musicName" + musicName);

        User user = (User) req.getSession().getAttribute("user");
        int user_id = user.getId();

        LoveMusicDao lovemusicDao = new LoveMusicDao();
        List musics = new ArrayList();

        if (musicName != null){
            musics = lovemusicDao.findLoveMusicBykeyAndUID(musicName, user_id);
        }else {
            musics = lovemusicDao.findLoveMusic(user_id);
        }

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.writeValue(resp.getWriter(),musics);

    }
}

5.7 移除我喜欢的音乐RemoveLoveServlet

@WebServlet("/removeLoveServlet")
public class RemoveLoveServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");

        Map map = new HashMap();

        String strId = req.getParameter("id");
        int musicid = Integer.parseInt(strId);

        User user = (User) req.getSession().getAttribute("user");
        int user_id = user.getId();

        LoveMusicDao lovemusicDao = new LoveMusicDao();
        int ret = lovemusicDao.removeLoveMusic(user_id, musicid);
        if (ret == 1){
            map.put("msg",true);
        }else {
            map.put("msg",false);
        }

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.writeValue(resp.getWriter(),map);

    }
}

最后美图收尾嘻嘻~~(FPX 2019 涅槃

第二个小项目:在线音乐服务器(更新中,后端基本完毕)_第4张图片

你可能感兴趣的:(Java项目,java,http,web,servlet,mysql)