“i分享”完整项目运行指导——Web服务搭建(2)

    xiaoxiao2022-07-03  134

    1-3-11  QueryAboutMe.java

        在创建好的myServlet.data包中右击选择New,点击Servlet,在Class name中填写QueryAboutMe,点击finish。打开新建好的QueryAboutMe.java文件,将下面代码复制到文件中。这部分代码主要就是获取到用户昵称、内容类型,去info表中和focus表中查询“我的分享”、“我的日记”、“我的收藏”,并将数据封装成Json返回。

     

    -------------------------- QueryAboutMe.java结束-- -----------------------

    package myServlet.data;

    import java.io.IOException;

    import java.io.PrintWriter;

    import java.sql.Connection;

    import java.sql.ResultSet;

    import java.sql.Statement;

    import java.util.ArrayList;

    import java.util.HashMap;

    import java.util.List;

    import java.util.Map;

     

    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 org.utils.JdbcUtils;

    import org.utils.JsonUtils;

     

    import com.sun.rowset.CachedRowSetImpl;

     

    import net.sf.json.JSONArray;

     

    /**

     * Servlet implementation class QueryAboutMe

     */

    @WebServlet("/QueryAboutMe")

    public class QueryAboutMe extends HttpServlet {

        private static final long serialVersionUID = 1L;

       

        CachedRowSetImpl rowSet = null;    //存储表中全部记录的行集对象

        int pageSize; //每页加载数量

        int pageNum;   //第几页

        int totalRecord;  //总记录数

        int totalPage;   //总页数

        int shareType=0;

           

        /**

         * @see HttpServlet#HttpServlet()

         */

        public QueryAboutMe() {

            super();

            // TODO Auto-generated constructor stub

        }

     

        /**

         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

         */

        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            // TODO Auto-generated method stub

            response.setContentType("text/html;charset=utf-8");

            request.setCharacterEncoding("utf-8");

            response.setCharacterEncoding("utf-8");

            PrintWriter out = response.getWriter();

           

            String userName = request.getParameter("username");

            String type = request.getParameter("type");

            String page = request.getParameter("page");

            String count = request.getParameter("count");

           

            if(page == null||page == "") {

                page = "1";

            }

           

            if(count == null|count == "") {

                count = "10";

            }

           

            try {

                pageNum = Integer.parseInt(page);    //第几页

                pageSize = Integer.parseInt(count);    //每页加载几条

                shareType = Integer.parseInt(type);

            } catch (NumberFormatException e) {

                e.printStackTrace();

            }

           

            String condition;

            if(shareType==0) {

                condition  = "select * from info where (username='"+userName+"') and (info_type=0 or info_type=1 or info_type=2) order by info_id desc";

            }else if(shareType ==1) {

                condition = "select * from info where username='"+userName+"' and info_type=3 order by info_id desc";

            }else {

                condition = "select * from info left join focus on info.info_id=focus.info_id where focus.username='"+userName+"' order by focus.info_id desc";

            }

           

       

            Connection connection = null;

            Statement sql = null;

            ResultSet rs = null;

     

            try {

                connection = JdbcUtils.getConnection();

                sql = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);

                rs = sql.executeQuery(condition);

               

               

                rowSet = new CachedRowSetImpl();  //创建行集对象

                rowSet.populate(rs);

               

               

                //按查询页数返回结果

                returnByPage(request,response,rowSet);

            } catch (Exception e) {

                out.println(condition+"异常:"+e.toString());

                e.printStackTrace();

            }finally {

                //5.释放资源 connection prepareStatement

                JdbcUtils.statementClose(connection, sql, rs);

            }

        }

     

        /**

         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

         */

        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            // TODO Auto-generated method stub

            doGet(request, response);

        }

       

        public void returnByPage(HttpServletRequest request, HttpServletResponse response,CachedRowSetImpl rowSet)throws ServletException, IOException{

            response.setContentType("text/html;charset=utf-8");

            response.setCharacterEncoding("utf-8");

                JSONArray jsonArray = new JSONArray();//存放返回的jsonOjbect数组

                JSONArray TotaljsonArray = new JSONArray();//存放返回的jsonOjbect数组

                //将rowSet的数据提取到Map

                List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();

               

                //将rowSet的数据提取到Map

                List<Map<String,Object>> Totaldata = new ArrayList<Map<String,Object>>();

                try {

                    PrintWriter out = response.getWriter();

                    try {

                        rowSet.last();    //移到随后一行

                        totalRecord = rowSet.getRow();             

                        if(totalRecord%pageSize==0){

                            totalPage = totalRecord/pageSize;  //总页数

                        }else{

                            totalPage = totalRecord/pageSize+1;

                        }

                       

                        int index = (pageNum-1)*pageSize+1;

                        rowSet.absolute(index);   //查询位置移动到查询页的起始记录位置

                        boolean boo = true;

                       

                        for(int i=1; i<=pageSize&&boo;i++){

                           

                            int infoId = rowSet.getInt(1);    //内容ID                     

                            String infoTitle = rowSet.getString(2);   //内容标题                   

                            String infoDescribe = rowSet.getString(3);   //内容简述

                            String infoDetail = rowSet.getString("info_detail");   //内容详情

                           

                            String type = rowSet.getString(5);    //类型:0表示日记,1表示趣事

                            String support = rowSet.getString(6);   //点赞数

       

                           

                            String infoAuthor = rowSet.getString(7);  //作者    

                           

                            Map<String,Object> map = new HashMap<String,Object>();

                            map.put("infoId", infoId);

                            map.put("infoTitle", infoTitle);

                            map.put("infoDescribe", infoDescribe);

                            map.put("infoDetail", infoDetail);

                            map.put("infoType", type);

                            map.put("infoSupport", support);

                            map.put("infoAuthor", infoAuthor);

                           

                            data.add(map);

                            boo = rowSet.next();

                        }

                        jsonArray = JsonUtils.formatRsToJsonArray(data);

                       

                        Map<String,Object> map = new HashMap<String,Object>();

                        map.put("totalRecord", totalRecord);

                        map.put("RecordDetail", jsonArray);

                        Totaldata.add(map);

                        TotaljsonArray = JsonUtils.formatRsToJsonArray(Totaldata);

                       

                        out.println(TotaljsonArray.toString());  //返回json

                       

                    }catch(Exception e) {

                        out.println("null");

                    }

                   

                }catch(IOException e) {

                   

                }

           

        }

     

    }

    ---------------------- QueryAboutMe.java结束-- -------------------------------

     

    1-3-12  AddSupport.java

        在创建好的myServlet.data包中右击选择New,点击Servlet,在Class name中填写AddSupport,点击finish。打开新建好的AddSupport.java文件,将下面代码复制到文件中。这部分代码主要就是获取到内容Id,在内容表info中查找到对应内容,取得点赞数,加一后更新到对应的内容中,完成点赞的功能。

     

    ------------------------ AddSupport.java开始-- ----------------------------

    package myServlet.data;

    import java.io.IOException;

    import java.io.PrintWriter;

    import java.sql.Connection;

    import java.sql.PreparedStatement;

    import java.sql.ResultSet;

    import java.util.ArrayList;

    import java.util.HashMap;

    import java.util.List;

    import java.util.Map;

     

    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 org.utils.JdbcUtils;

    import org.utils.JsonUtils;

     

    import net.sf.json.JSONArray;

     

    /**

     * Servlet implementation class AddSupport

     */

    @WebServlet("/AddSupport")

    public class AddSupport extends HttpServlet {

        private static final long serialVersionUID = 1L;

          

        /**

         * @see HttpServlet#HttpServlet()

         */

        public AddSupport() {

            super();

            // TODO Auto-generated constructor stub

        }

     

        /**

         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

         */

        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            // TODO Auto-generated method stub

            response.setContentType("text/html;charset=utf-8");

            request.setCharacterEncoding("utf-8");

            response.setCharacterEncoding("utf-8");

            PrintWriter out = response.getWriter();

          

            String infoId = request.getParameter("InfoId").trim();

           

            if(infoId == null) {

                infoId = "";

            }

           

            Connection connection = null;

            PreparedStatement prepareStatement = null;

            PreparedStatement prepareStatement2 = null;

            ResultSet rs = null;

            ResultSet rs2 =null;

           

            String backnews="";

            boolean boo = false;

           

            boo = infoId.length()>0;

           

            try {

                connection = JdbcUtils.getConnection();

           

                //3.获取statement

                String sql ="select * from info where info_id=?";

                prepareStatement = connection.prepareStatement(sql);

                prepareStatement.setString(1, infoId);

               

                if(boo) {

                    //4.执行sql

                    rs = prepareStatement.executeQuery();

                    boolean m = rs.next();

                    int support = rs.getInt(6);

                    support = support+1;

                   

                   

                    if(m==true) {

                        //查询成功

                        String changeSql = "update info set info_support=? where info_id=?";

                        prepareStatement2 = connection.prepareStatement(changeSql);

                        prepareStatement2.setInt(1, support);

                        prepareStatement2.setString(2, infoId);

                       

                        prepareStatement2.execute();

                        

                        JSONArray jsonArray = new JSONArray();//存放返回的jsonOjbect数组

                        List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();

     

                        Map<String,Object> map = new HashMap<String,Object>();

                        map.put("addOk", true);

               

                        data.add(map);

                        jsonArray = JsonUtils.formatRsToJsonArray(data);

                        out.println(jsonArray.toString());  //返回json

                       

                       

                    }else {

                        JSONArray jsonArray = new JSONArray();//存放返回的jsonOjbect数组

                        List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();

                       

                        Map<String,Object> map = new HashMap<String,Object>();

                        map.put("addOk", false);

               

                        data.add(map);

                        jsonArray = JsonUtils.formatRsToJsonArray(data);

                        out.println(jsonArray.toString());  //返回json

                    }

                }else {

                    JSONArray jsonArray = new JSONArray();//存放返回的jsonOjbect数组

                    List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();

     

               

                    Map<String,Object> map = new HashMap<String,Object>();

                    map.put("addOk", false);

           

                    data.add(map);

                    jsonArray = JsonUtils.formatRsToJsonArray(data);

                    out.println(jsonArray.toString());  //返回json

                }

                out.print(backnews.toString());

            } catch (Exception e) {

                backnews="修改失败"+e.toString();

                out.print(backnews);

                e.printStackTrace();

           

            }finally {

                //5.释放资源 connection prepareStatement

                JdbcUtils.close(connection, prepareStatement, rs);

                JdbcUtils.close(connection, prepareStatement2, rs2);

            }

             out.flush();

             out.close();

        }

     

        /**

         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

         */

        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            // TODO Auto-generated method stub

            doGet(request, response);

        }

     

    }

    ------------------------ AddSupport.java结束-- -------------------------------

     

    1-3-13  IfAddFocus.java

        在创建好的myServlet.data包中右击选择New,点击Servlet,在Class name中填写IfAddFocus,点击finish。打开新建好的IfAddFocus.java文件,将下面代码复制到文件中。这部分代码主要就是获取到内容Id、用户昵称,在收藏表focus中查询是否有对应信息,如果有则表示已经收藏,反之则未收藏。

    ----------------------------- IfAddFocus.java开始-- --------------------------

    package myServlet.data;

     

    import java.io.IOException;

    import java.io.PrintWriter;

    import java.sql.Connection;

    import java.sql.PreparedStatement;

    import java.sql.ResultSet;

    import java.util.ArrayList;

    import java.util.HashMap;

    import java.util.List;

    import java.util.Map;

     

    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 org.utils.JdbcUtils;

    import org.utils.JsonUtils;

     

    import net.sf.json.JSONArray;

     

    /**

     * Servlet implementation class IfAddlike

     */

    @WebServlet("/IfAddFocus")

    public class IfAddFocus extends HttpServlet {

        private static final long serialVersionUID = 1L;

          

        /**

         * @see HttpServlet#HttpServlet()

         */

        public IfAddFocus() {

            super();

            // TODO Auto-generated constructor stub

        }

     

        /**

         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

         */

        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            // TODO Auto-generated method stub

            response.setContentType("text/html;charset=utf-8");

            request.setCharacterEncoding("utf-8");

            response.setCharacterEncoding("utf-8");

            PrintWriter out = response.getWriter();

                 

            String username = request.getParameter("username").trim();

            String infoId = request.getParameter("infoId").trim();

            int focusId = 0;

     

           

            if(username == null) {

                username = "";

            }

           

            if(infoId == null) {

                infoId = "";

            }

         

            Connection connection = null;

            PreparedStatement prepareStatement = null;

            ResultSet rs = null;

            boolean boo = false;

           

            boo = username.length()>0&&infoId.length()>0;

           

            try {

                connection = JdbcUtils.getConnection();

                //3.获取statement

                String sql ="select * from focus where username=? and info_id=?";

                prepareStatement = connection.prepareStatement(sql);

                prepareStatement.setString(1, username);

                prepareStatement.setString(2, infoId);

               

                if(boo) {

                    //4.执行sql

                    boolean m =false;

                   

                    rs = prepareStatement.executeQuery();

                    while(rs.next()) {

                        m = true;

                        focusId = rs.getInt(1);

                    }

                   

                    if(m==true) {

                   

                        success(request,response,focusId);

                       

                    }else {

                        fail(request,response);

                    }

                }else {

                    fail(request,response);

                }

               

     

            } catch (Exception e) {

                e.printStackTrace();

                fail(request,response);

            }finally {

                //5.释放资源 connection prepareStatement

                JdbcUtils.close(connection, prepareStatement, rs);

            }

             out.flush();

             out.close();

        }

     

        /**

         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

         */

        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            // TODO Auto-generated method stub

            doGet(request, response);

        }

       

        public void success(HttpServletRequest request, HttpServletResponse response, int focusId) {

            try {

                JSONArray jsonArray = new JSONArray();//存放返回的jsonOjbect数组

                List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();

               

                PrintWriter out = response.getWriter();

       

                Map<String,Object> map = new HashMap<String,Object>();

                map.put("isFocus", true);

                map.put("focusId", focusId);

       

                data.add(map);

                jsonArray = JsonUtils.formatRsToJsonArray(data);

                out.println(jsonArray.toString());  //返回json

            }catch(IOException e) {

                e.printStackTrace();

            }

        }

       

        public void fail(HttpServletRequest request, HttpServletResponse response) {

            response.setContentType("text/html;charset=utf-8");

            try {

                JSONArray jsonArray = new JSONArray();//存放返回的jsonOjbect数组

                List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();

               

                PrintWriter out = response.getWriter();

       

                Map<String,Object> map = new HashMap<String,Object>();

                map.put("isFocus", false);

       

                data.add(map);

                jsonArray = JsonUtils.formatRsToJsonArray(data);

                out.println(jsonArray.toString());  //返回json

            }catch(IOException e) {

                e.printStackTrace();

            }

        }

     

    }

    ------------------------- IfAddFocus.java结束-- ------------------------

    1-3-14  AddFocus.java

        在创建好的myServlet.data包中右击选择New,点击Servlet,在Class name中填写AddFocus,点击finish。打开新建好的AddFocus.java文件,将下面代码复制到文件中。这部分代码主要就是获取到内容Id、用户昵称,将信息插入到收藏表focus中,完成添加收藏功能。

    ---------------------------- AddFocus.java开始-- ---------------------------

    package myServlet.data;

     

    import java.io.IOException;

    import java.io.PrintWriter;

    import java.sql.Connection;

    import java.sql.PreparedStatement;

    import java.sql.ResultSet;

    import java.util.ArrayList;

    import java.util.HashMap;

    import java.util.List;

    import java.util.Map;

     

    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 org.utils.JdbcUtils;

    import org.utils.JsonUtils;

     

    import net.sf.json.JSONArray;

     

    /**

     * Servlet implementation class AddFocus

     */

    @WebServlet("/AddFocus")

    public class AddFocus extends HttpServlet {

        private static final long serialVersionUID = 1L;

          

        /**

         * @see HttpServlet#HttpServlet()

         */

        public AddFocus() {

            super();

            // TODO Auto-generated constructor stub

        }

     

        /**

         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

         */

        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            // TODO Auto-generated method stub

            response.setContentType("text/html;charset=utf-8");

            request.setCharacterEncoding("utf-8");

            response.setCharacterEncoding("utf-8");

            PrintWriter out = response.getWriter();

           

         

            String infoId = request.getParameter("InfoId").trim();

            String username = request.getParameter("username").trim();

           

            if(infoId == null||infoId == "") {

                return;

            }

           

            if(username == null||username == "") {

                return;

            }

           

            Connection connection = null;

            PreparedStatement prepareStatement = null;

            PreparedStatement prepareStatement2 = null;

            ResultSet rs = null;

            ResultSet rs2 =null;

           

            String backnews="";

            boolean boo = false;

           

            boo = infoId.length()>0;

           

            try {

                connection = JdbcUtils.getConnection();

           

                //3.获取statement

                String sql ="select * from focus where info_id=? and username=?";

                prepareStatement = connection.prepareStatement(sql);

                prepareStatement.setString(1, infoId);

                prepareStatement.setString(2, username);

               

                if(boo) {

                    //4.执行sql

                    rs = prepareStatement.executeQuery();

                    boolean m = rs.next();

                   

                    if(m!=true) {

                        String changeSql = "INSERT INTO focus VALUES(?,?,?)";

                        prepareStatement2 = connection.prepareStatement(changeSql);

                        prepareStatement2.setInt(1, 0);

                        prepareStatement2.setString(2, username);

                        prepareStatement2.setString(3, infoId);

                       

                        prepareStatement2.execute();

                        

                        JSONArray jsonArray = new JSONArray();//存放返回的jsonOjbect数组

                        List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();

                        Map<String,Object> map = new HashMap<String,Object>();

                        map.put("addOk", true);

               

                        data.add(map);

                        jsonArray = JsonUtils.formatRsToJsonArray(data);

                        out.println(jsonArray.toString());  //返回json

                       

                    }else {

                        JSONArray jsonArray = new JSONArray();//存放返回的jsonOjbect数组

                        List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();

     

                   

                        Map<String,Object> map = new HashMap<String,Object>();

                        map.put("addOk", false);

               

                        data.add(map);

                        jsonArray = JsonUtils.formatRsToJsonArray(data);

                        out.println(jsonArray.toString());  //返回json

                    }

                }else {

                    JSONArray jsonArray = new JSONArray();//存放返回的jsonOjbect数组

                    List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();

     

               

                    Map<String,Object> map = new HashMap<String,Object>();

                    map.put("addOk", false);

           

                    data.add(map);

                    jsonArray = JsonUtils.formatRsToJsonArray(data);

                    out.println(jsonArray.toString());  //返回json

                }

                out.print(backnews.toString());

            } catch (Exception e) {

                backnews="修改失败"+e.toString();

                out.print(backnews);

                e.printStackTrace();

           

            }finally {

                //5.释放资源 connection prepareStatement

                JdbcUtils.close(connection, prepareStatement, rs);

                JdbcUtils.close(connection, prepareStatement2, rs2);

            }

             out.flush();

             out.close();

        }

     

        /**

         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

         */

        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            // TODO Auto-generated method stub

            doGet(request, response);

        }

     

    }

    ------------------------- AddFocus.java结束-- ----------------------------

     

    1-3-15  RemoveFocus.java

        在创建好的myServlet.data包中右击选择New,点击Servlet,在Class name中填写RemoveFocus,点击finish。打开新建好的RemoveFocus.java文件,将下面代码复制到文件中。这部分代码主要就是获取到内容Id、用户昵称,将对应的信息从收藏表focus中删除,完成取消收藏的功能。

     

    -------------------------- RemoveFocus.java开始-- ----------------------------

    package myServlet.data;

     

    import java.io.IOException;

    import java.io.PrintWriter;

    import java.sql.Connection;

    import java.sql.PreparedStatement;

    import java.sql.ResultSet;

    import java.util.ArrayList;

    import java.util.HashMap;

    import java.util.List;

    import java.util.Map;

     

    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 org.utils.JdbcUtils;

    import org.utils.JsonUtils;

     

    import net.sf.json.JSONArray;

     

    /**

     * Servlet implementation class RemoveFocus

     */

    @WebServlet("/RemoveFocus")

    public class RemoveFocus extends HttpServlet {

        private static final long serialVersionUID = 1L;

          

        /**

         * @see HttpServlet#HttpServlet()

         */

        public RemoveFocus() {

            super();

            // TODO Auto-generated constructor stub

        }

     

        /**

         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

         */

        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            // TODO Auto-generated method stub

            response.setContentType("text/html;charset=utf-8");

            request.setCharacterEncoding("utf-8");

            response.setCharacterEncoding("utf-8");

            PrintWriter out = response.getWriter();

            String focusId = request.getParameter("focusId").trim();

           

            if(focusId == null||focusId == "") {

                return;

            }

       

           

            Connection connection = null;

            PreparedStatement prepareStatement = null;

            ResultSet rs = null;

     

            boolean boo = false;

           

            boo = focusId.length()>0;

           

            try {

                connection = JdbcUtils.getConnection();

           

                //3.获取statement

                String sql ="delete from focus where focus_id=?";

                prepareStatement = connection.prepareStatement(sql);

                prepareStatement.setString(1, focusId);

               

                if(boo) {

                    //4.执行sql

                    prepareStatement.execute();

                       

                    JSONArray jsonArray = new JSONArray();//存放返回的jsonOjbect数组

                    List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();

                    Map<String,Object> map = new HashMap<String,Object>();

                    map.put("removeOk", true);

           

                    data.add(map);

                    jsonArray = JsonUtils.formatRsToJsonArray(data);

                    out.println(jsonArray.toString());  //返回json     

               

                }else {

                    JSONArray jsonArray = new JSONArray();//存放返回的jsonOjbect数组

                    List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();

     

               

                    Map<String,Object> map = new HashMap<String,Object>();

                    map.put("removeOk", false);

           

                    data.add(map);

                    jsonArray = JsonUtils.formatRsToJsonArray(data);

                    out.println(jsonArray.toString());  //返回json

                }

               

            } catch (Exception e) {

                JSONArray jsonArray = new JSONArray();//存放返回的jsonOjbect数组

                List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();

     

           

                Map<String,Object> map = new HashMap<String,Object>();

                map.put("removeOk", false);

       

                data.add(map);

                jsonArray = JsonUtils.formatRsToJsonArray(data);

                out.println(jsonArray.toString());  //返回json

           

            }finally {

                //5.释放资源 connection prepareStatement

                JdbcUtils.close(connection, prepareStatement, rs);

            }

             out.flush();

             out.close();

        }

     

        /**

         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

         */

        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            // TODO Auto-generated method stub

            doGet(request, response);

        }

     

    }

    --------------------------- RemoveFocus.java结束-- ----------------------------

     

    1-3-16  DeleteInfo.java

        在创建好的myServlet.data包中右击选择New,点击Servlet,在Class name中填写DeleteInfo,点击finish。打开新建好的DeleteInfo.java文件,将下面代码复制到文件中。这部分代码主要就是获取到内容Id,将对应的信息从内容表info中删除,完成删除内容的功能。

    --------------------------- DeleteInfo.java结束-- ---------------------------

    package myServlet.data;

     

    import java.io.IOException;

    import java.io.PrintWriter;

    import java.sql.Connection;

    import java.sql.PreparedStatement;

    import java.sql.ResultSet;

    import java.util.ArrayList;

    import java.util.HashMap;

    import java.util.List;

    import java.util.Map;

     

    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 org.utils.JdbcUtils;

    import org.utils.JsonUtils;

     

    import net.sf.json.JSONArray;

     

    /**

     * Servlet implementation class DeleteInfo

     */

    @WebServlet("/DeleteInfo")

    public class DeleteInfo extends HttpServlet {

        private static final long serialVersionUID = 1L;

          

        /**

         * @see HttpServlet#HttpServlet()

         */

        public DeleteInfo() {

            super();

            // TODO Auto-generated constructor stub

        }

     

        /**

         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

         */

        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            // TODO Auto-generated method stub

            response.setContentType("text/html;charset=utf-8");

            request.setCharacterEncoding("utf-8");

            response.setCharacterEncoding("utf-8");

            PrintWriter out = response.getWriter();

           

         

            String infoId = request.getParameter("infoId").trim();

           

            if(infoId == null||infoId == "") {

                return;

            }

       

           

            Connection connection = null;

            PreparedStatement prepareStatement = null;

            ResultSet rs = null;

           

            PreparedStatement prepareStatement2 = null;

            ResultSet rs2 =null;

     

            PreparedStatement prepareStatement3 = null;

            ResultSet rs3 =null;

            String backnews="";

            boolean boo = false;

           

            boo = infoId.length()>0;

           

            try {

                connection = JdbcUtils.getConnection();

           

                //3.获取statement

                String sql ="delete from focus where info_id=?";

                prepareStatement = connection.prepareStatement(sql);

                prepareStatement.setString(1, infoId);

               

                String sql2 ="delete from comment where comment_info=?";

                prepareStatement2 = connection.prepareStatement(sql2);

                prepareStatement2.setString(1, infoId);

               

                if(boo) {

                    //4.执行sql

                    prepareStatement.execute();

                    prepareStatement2.execute();

                   

                    String changeSql = "delete from info where info_id=?";

                    prepareStatement3 = connection.prepareStatement(changeSql);

                    prepareStatement3.setString(1, infoId);

                    prepareStatement3.execute();

                   

                    JSONArray jsonArray = new JSONArray();//存放返回的jsonOjbect数组

                    List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();

                    Map<String,Object> map = new HashMap<String,Object>();

                    map.put("deleteOk", true);

           

                    data.add(map);

                    jsonArray = JsonUtils.formatRsToJsonArray(data);

                    out.println(jsonArray.toString());  //返回json     

               

                }else {

                    JSONArray jsonArray = new JSONArray();//存放返回的jsonOjbect数组

                    List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();

     

               

                    Map<String,Object> map = new HashMap<String,Object>();

                    map.put("deleteOk", false);

           

                    data.add(map);

                    jsonArray = JsonUtils.formatRsToJsonArray(data);

                    out.println(jsonArray.toString());  //返回json

                }

                out.print(backnews.toString());

            } catch (Exception e) {

                backnews="修改失败"+e.toString();

                out.print(backnews);

                e.printStackTrace();

           

            }finally {

                //5.释放资源 connection prepareStatement

                JdbcUtils.close(connection, prepareStatement, rs);

                JdbcUtils.close(connection, prepareStatement2, rs2);

                JdbcUtils.close(connection, prepareStatement3, rs3);

            }

             out.flush();

             out.close();

        }

        /**

         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

         */

        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            // TODO Auto-generated method stub

            doGet(request, response);

        }

    }

    ------------------------ DeleteInfo.java结束-- --------------------------

     

    1-3-17  QueryComment.java

        在创建好的myServlet.data包中右击选择New,点击Servlet,在Class name中填写QueryComment,点击finish。打开新建好的QueryComment.java文件,将下面代码复制到文件中。这部分代码主要就是获取到内容Id,在评论表comment中查询对应的评论信息,并将数据封装成json返回。

     

    ---------------------------- QueryComment.java开始-- --------------------------

    package myServlet.data;

    import java.io.IOException;

    import java.io.PrintWriter;

    import java.sql.Connection;

    import java.sql.ResultSet;

    import java.sql.Statement;

    import java.util.ArrayList;

    import java.util.HashMap;

    import java.util.List;

    import java.util.Map;

    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 org.utils.JdbcUtils;

    import org.utils.JsonUtils;

    import com.sun.rowset.CachedRowSetImpl;

    import net.sf.json.JSONArray;

     

    /**

     * Servlet implementation class QueryComment

     */

    @WebServlet("/QueryComment")

    public class QueryComment extends HttpServlet {

        private static final long serialVersionUID = 1L;

        CachedRowSetImpl rowSet = null;    //存储表中全部记录的行集对象

        int pageSize=10; //每页加载数量

        int pageNum=1;   //第几页

        int totalRecord;  //总记录数

        int totalPage;   //总页数

        /**

         * @see HttpServlet#HttpServlet()

         */

        public QueryComment() {

            super();

            // TODO Auto-generated constructor stub

        }

     

        /**

         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

         */

        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            response.setContentType("text/html;charset=utf-8");

            request.setCharacterEncoding("utf-8");

            response.setCharacterEncoding("utf-8");

            PrintWriter out = response.getWriter();

            String infoId = request.getParameter("infoId").trim();

           

            String condition = "select * from comment where comment_info='"+infoId+"' order by comment_id desc";  

       

            Connection connection = null;

            Statement sql = null;

            ResultSet rs = null;

            try {

                connection = JdbcUtils.getConnection();

                sql = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);

                rs = sql.executeQuery(condition);

                rowSet = new CachedRowSetImpl();  //创建行集对象

                rowSet.populate(rs);

                //按查询页数返回结果

                returnByPage(request,response,rowSet);

            } catch (Exception e) {

                out.println(condition+"异常:"+e.toString());

                e.printStackTrace();

            }finally {

                //5.释放资源 connection prepareStatement

                JdbcUtils.statementClose(connection, sql, rs);

            }

        }

     

        /**

         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

         */

        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            // TODO Auto-generated method stub

            doGet(request, response);

        }

       

        public void returnByPage(HttpServletRequest request, HttpServletResponse response,CachedRowSetImpl rowSet)throws ServletException, IOException{

            response.setContentType("text/html;charset=utf-8");

            response.setCharacterEncoding("utf-8");

                JSONArray jsonArray = new JSONArray();//存放返回的jsonOjbect数组

                JSONArray TotaljsonArray = new JSONArray();//存放返回的jsonOjbect数组

                //将rowSet的数据提取到Map

                List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();

               

                //将rowSet的数据提取到Map

                List<Map<String,Object>> Totaldata = new ArrayList<Map<String,Object>>();

                try {

                    PrintWriter out = response.getWriter();

                    try {

                        rowSet.last();    //移到随后一行

                        totalRecord = rowSet.getRow();             

                        if(totalRecord%pageSize==0){

                            totalPage = totalRecord/pageSize;  //总页数

                        }else{

                            totalPage = totalRecord/pageSize+1;

                        }

                       

                        int index = (pageNum-1)*pageSize+1;

                        rowSet.absolute(index);   //查询位置移动到查询页的起始记录位置

                        boolean boo = true;

                       

                        for(int i=1; i<=pageSize&&boo;i++){

                       

                            int commentId = rowSet.getInt(1);    //评论内容ID              

                            String commentUser = rowSet.getString(2);   //评论者  

                            int commentInfo =  rowSet.getInt(3);

                            String commentDetail = rowSet.getString(4);   //评论详情

     

                            Map<String,Object> map = new HashMap<String,Object>();

                            map.put("commentId", commentId);

                            map.put("commentUser", commentUser);

                            map.put("commentInfo", commentInfo);

                            map.put("commentDetail", commentDetail);

                            data.add(map);

                            boo = rowSet.next();

                        }

                        jsonArray = JsonUtils.formatRsToJsonArray(data);

                       

                        Map<String,Object> map = new HashMap<String,Object>();

                        map.put("totalRecord", totalRecord);

                        map.put("RecordDetail", jsonArray);

                        Totaldata.add(map);

                        TotaljsonArray = JsonUtils.formatRsToJsonArray(Totaldata);

                       

                        out.println(TotaljsonArray.toString());  //返回json

                       

                    }catch(Exception e) {

                        out.println("null");

                    }

                   

                }catch(IOException e) {

                   

                }

           

        }

     

    }

    ------------------------ QueryComment.java结束-- -----------------------------

    1-3-18  AddComment.java

        在创建好的myServlet.data包中右击选择New,点击Servlet,在Class name中填写AddComment,点击finish。打开新建好的AddComment.java文件,将下面代码复制到文件中。这部分代码主要就是获取到用户昵称、内容ID,并将信息插入到评论表中,完成评论的功能。

     

    --------------------------- AddComment.java开始- ---------------------------

    package myServlet.data;

    import java.io.IOException;

    import java.io.PrintWriter;

    import java.sql.Connection;

    import java.sql.PreparedStatement;

    import java.util.ArrayList;

    import java.util.HashMap;

    import java.util.List;

    import java.util.Map;

    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 org.utils.JdbcUtils;

    import org.utils.JsonUtils;

    import net.sf.json.JSONArray;

     

    /**

     * Servlet implementation class AddComment

     */

    @WebServlet("/AddComment")

    public class AddComment extends HttpServlet {

        private static final long serialVersionUID = 1L;

          

        /**

         * @see HttpServlet#HttpServlet()

         */

        public AddComment() {

            super();

            // TODO Auto-generated constructor stub

        }

        /**

         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

         */

        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            // TODO Auto-generated method stub

            response.setContentType("text/html;charset=utf-8");

            request.setCharacterEncoding("utf-8");

            response.setCharacterEncoding("utf-8");

            PrintWriter out = response.getWriter();

            Integer commentId =0;    //内容ID,默认设置为0

            String infoIdStr = request.getParameter("infoId");   //内容标题

            String commentUser =request.getParameter("commentUser");   //内容简述

            String commentDetail = request.getParameter("commentDetail");   //内容详情

     

            if(infoIdStr == null||infoIdStr == "") {

                infoIdStr = "";

            }

            if(commentUser == null||commentUser == "") {

                commentUser = "";

            }

            if(commentDetail == null||commentDetail == "") {

                commentDetail = "";

            }

         

            Boolean m = infoIdStr.length()>0&&commentUser.length()>0&&commentDetail.length()>0;

           

            int infoId = 0;

            try {

                infoId = Integer.parseInt(infoIdStr);    //内容类型

            } catch (NumberFormatException e) {

                e.printStackTrace();

            }      

            Connection connection = null;

            PreparedStatement prepareStatement = null;

            try {

                connection = JdbcUtils.getConnection();

                //3.获取statement

                String sql ="INSERT INTO comment VALUES(?,?,?,?)";

                prepareStatement = connection.prepareStatement(sql);

               

                if(m) {

                    prepareStatement.setInt(1, commentId);  //自增

                    prepareStatement.setString(2, commentUser);

                    prepareStatement.setInt(3, infoId);

                    prepareStatement.setString(4, commentDetail);

     

                    //4.执行sql

                    prepareStatement.execute();

                    JSONArray jsonArray = new JSONArray();//存放返回的jsonOjbect数组

                    List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();

                    Map<String,Object> map = new HashMap<String,Object>();

                    map.put("addOk", true);

           

                    data.add(map);

                    jsonArray = JsonUtils.formatRsToJsonArray(data);

                    out.println(jsonArray.toString());  //返回json

                   

                }else {

                    JSONArray jsonArray = new JSONArray();//存放返回的jsonOjbect数组

                    List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();

                    Map<String,Object> map = new HashMap<String,Object>();

                    map.put("addOk", false);

           

                    data.add(map);

                    jsonArray = JsonUtils.formatRsToJsonArray(data);

                    out.println(jsonArray.toString());  //返回json

                }

               

            } catch (Exception e) {

                JSONArray jsonArray = new JSONArray();//存放返回的jsonOjbect数组

                List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();

                Map<String,Object> map = new HashMap<String,Object>();

                map.put("addOk", false);

       

                data.add(map);

                jsonArray = JsonUtils.formatRsToJsonArray(data);

                out.println(jsonArray.toString());  //返回json

               

            }finally {

                //5.释放资源 connection prepareStatement

                JdbcUtils.close(connection, prepareStatement, null);

            }

             out.flush();

             out.close();

        }

     

        /**

         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

         */

        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            // TODO Auto-generated method stub

            doGet(request, response);

        }

     

    }

     

    --------------------------- AddComment.java结束-- ----------------------------

     

        基本上Servlet到这里就已经写完整了,如下图所见一共有18个servlet文件

           ​

       

    1-4 web.xml配置

    打开项目iShareService,找到WebRoot>WEB-INF文件夹,打开文件下的web.xml文件,如果没有该文件就新建一个,然后将下面的代码复制到文件中。这个文件主要就是配置servlet的映射。

     

    ------------------------------ web.xml开始-- --------------------------

    <?xml version="1.0" encoding="UTF-8"?>

    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">

      <servlet>

        <description>This is the description of my J2EE component</description>

        <display-name>This is the display name of my J2EE component</display-name>

        <servlet-name>Register</servlet-name>

        <servlet-class>myServlet.data.Register</servlet-class>

      </servlet>

      <servlet-mapping>

        <servlet-name>Register</servlet-name>

        <url-pattern>/servlet/Register</url-pattern>

      </servlet-mapping>

      <servlet>

        <servlet-name>Login</servlet-name>

        <servlet-class>myServlet.data.Login</servlet-class>

      </servlet>

      <servlet-mapping>

        <servlet-name>Login</servlet-name>

        <url-pattern>/servlet/Login</url-pattern>

      </servlet-mapping>

      <servlet>

        <servlet-name>QueryDiscover</servlet-name>

        <servlet-class>myServlet.data.QueryDiscover</servlet-class>

      </servlet>

      <servlet-mapping>

        <servlet-name>QueryDiscover</servlet-name>

        <url-pattern>/servlet/QueryDiscover</url-pattern>

      </servlet-mapping>

      <servlet>

        <servlet-name>QueryHotInfo</servlet-name>

        <servlet-class>myServlet.data.QueryHotInfo</servlet-class>

      </servlet>

      <servlet-mapping>

        <servlet-name>QueryHotInfo</servlet-name>

        <url-pattern>/servlet/QueryHotInfo</url-pattern>

      </servlet-mapping>

      <servlet>

        <servlet-name>QueryInfoByKey</servlet-name>

        <servlet-class>myServlet.data.QueryInfoByKey</servlet-class>

      </servlet>

      <servlet-mapping>

        <servlet-name>QueryInfoByKey</servlet-name>

        <url-pattern>/servlet/QueryInfoByKey</url-pattern>

      </servlet-mapping>

      <servlet>

        <servlet-name>QueryPeopleInfoByKey</servlet-name>

        <servlet-class>myServlet.data.QueryPeopleInfoByKey</servlet-class>

      </servlet>

      <servlet-mapping>

        <servlet-name>QueryPeopleInfoByKey</servlet-name>

        <url-pattern>/servlet/QueryPeopleInfoByKey</url-pattern>

      </servlet-mapping>

      <servlet>

        <servlet-name>AddInfo</servlet-name>

        <servlet-class>myServlet.data.AddInfo</servlet-class>

      </servlet>

      <servlet-mapping>

        <servlet-name>AddInfo</servlet-name>

        <url-pattern>/servlet/AddInfo</url-pattern>

      </servlet-mapping>

      <servlet>

        <servlet-name>ChangeSignature</servlet-name>

        <servlet-class>myServlet.data.ChangeSignature</servlet-class>

      </servlet>

      <servlet-mapping>

        <servlet-name>ChangeSignature</servlet-name>

        <url-pattern>/servlet/ChangeSignature</url-pattern>

      </servlet-mapping>

      <servlet>

        <servlet-name>QueryInfoById</servlet-name>

        <servlet-class>myServlet.data.QueryInfoById</servlet-class>

      </servlet>

      <servlet-mapping>

        <servlet-name>QueryInfoById</servlet-name>

        <url-pattern>/servlet/QueryInfoById</url-pattern>

      </servlet-mapping>

      <servlet>

        <servlet-name>IfAddFocus</servlet-name>

        <servlet-class>myServlet.data.IfAddFocus</servlet-class>

      </servlet>

      <servlet-mapping>

        <servlet-name>IfAddFocus</servlet-name>

        <url-pattern>/servlet/IfAddFocus</url-pattern>

      </servlet-mapping>

      <servlet>

        <servlet-name>AddSupport</servlet-name>

        <servlet-class>myServlet.data.AddSupport</servlet-class>

      </servlet>

      <servlet-mapping>

        <servlet-name>AddSupport</servlet-name>

        <url-pattern>/servlet/AddSupport</url-pattern>

      </servlet-mapping>

      <servlet>

        <servlet-name>AddFocus</servlet-name>

        <servlet-class>myServlet.data.AddFocus</servlet-class>

      </servlet>

      <servlet-mapping>

        <servlet-name>AddFocus</servlet-name>

        <url-pattern>/servlet/AddFocus</url-pattern>

      </servlet-mapping>

      <servlet>

        <servlet-name>RemoveFocus</servlet-name>

        <servlet-class>myServlet.data.RemoveFocus</servlet-class>

      </servlet>

      <servlet-mapping>

        <servlet-name>RemoveFocus</servlet-name>

        <url-pattern>/servlet/RemoveFocus</url-pattern>

      </servlet-mapping>

      <servlet>

        <servlet-name>DeleteInfo</servlet-name>

        <servlet-class>myServlet.data.DeleteInfo</servlet-class>

      </servlet>

      <servlet-mapping>

        <servlet-name>DeleteInfo</servlet-name>

        <url-pattern>/servlet/DeleteInfo</url-pattern>

      </servlet-mapping>

      <servlet>

        <servlet-name>ChangePassword</servlet-name>

        <servlet-class>myServlet.data.ChangePassword</servlet-class>

      </servlet>

      <servlet-mapping>

        <servlet-name>ChangePassword</servlet-name>

        <url-pattern>/servlet/ChangePassword</url-pattern>

      </servlet-mapping>

      <servlet>

        <servlet-name>QueryAboutMe</servlet-name>

        <servlet-class>myServlet.data.QueryAboutMe</servlet-class>

      </servlet>

      <servlet-mapping>

        <servlet-name>QueryAboutMe</servlet-name>

        <url-pattern>/servlet/QueryAboutMe</url-pattern>

      </servlet-mapping>

      <servlet>

        <servlet-name>QueryComment</servlet-name>

        <servlet-class>myServlet.data.QueryComment</servlet-class>

      </servlet>

      <servlet-mapping>

        <servlet-name>QueryComment</servlet-name>

        <url-pattern>/servlet/QueryComment</url-pattern>

      </servlet-mapping>

      <servlet>

        <servlet-name>AddComment</servlet-name>

        <servlet-class>myServlet.data.AddComment</servlet-class>

      </servlet>

      <servlet-mapping>

        <servlet-name>AddComment</servlet-name>

        <url-pattern>/servlet/AddComment</url-pattern>

      </servlet-mapping>

    </web-app>

     

    ----------------------------------- web.xml结束-- -----------------------------

     

    2         资源链接

    百度网盘:https://pan.baidu.com/s/1yJHbLxlqFnS2jD_8-T_cow

    提取码:29y1

    博客链接:https://blog.csdn.net/YanMeiHe

    最新回复(0)