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

    xiaoxiao2022-07-04  140

    1   搭建Web服务

    打开myEclipse,新建Workspace,在这我的Wrkspace是在E盘下的myEclipseProject,你也可以直接使用自己已经创建好的Workspace。打开Workspace,在file处右击,选择New下的Web Project,在Project name处填写iShareService,Java EE version选择JavaEE7-Web 3.1,然后点击finish。

     

    1-1 第三方工具包

    打开刚刚新建的项目iShareService,找到WebRoot>WEB-INF>lib文件夹,将下图中的jar包复制到lib文件夹下,下图的jar包资源可以在文末处的链接找到。引入的jar包可以分为3类,第一个jar包是为了应用rowset,最后一个是连接MySQL数据库,其余6个是封装JSON使用到的相关jar包。

     

    1-2 创建工具包

    打开iShareService,找到src目录,右击选择New,点击Package,在Name中填写org.utils,点击finish。

    1-2-1   JdbcUtils.java

    在创建好的org.utils包中右击选择New,点击Class,在name中填写JdbcUtils,点击finish。打开新建好的JdbcUtils.java文件,将下面代码复制到文件中(注意看文件头部中的url、username、password是否和你数据库的连接地址、用户名、密码一致,不一致则需要修改)。这部分的代码主要就是处理与数据库的连接,因为之后要反复使用到所以封装出来比较方便。

     

    ----------------------------- JdbcUtils.java开始 --------------------------

    package org.utils;

    import java.sql.Connection;

    import java.sql.DriverManager;

    import java.sql.PreparedStatement;

    import java.sql.ResultSet;

    import java.sql.SQLException;

    import java.sql.Statement;

     

    public class JdbcUtils {

        private static String url ="jdbc:mysql://127.0.0.1/ishare?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true";

        private static String username="root";

        private static String password="";

        private static String driverName="com.mysql.jdbc.Driver";

       

        // static静态代码块里面代码,会在类加载到内存的时候立刻执行

        static {

            //1.注册驱动

            try {

                Class.forName(driverName);

            } catch (ClassNotFoundException e) {

                e.printStackTrace();

            }

        }

       

        /**

         * 获取连接

         * @return

         * @throws SQLException

         */

        public static Connection getConnection() throws SQLException {

            //2.获取连接

            Connection connection = DriverManager.getConnection(url, username, password);

            return connection;

        }

     

        public static void close(Connection connection,PreparedStatement prepareStatement,ResultSet resultSet) {

            //5.释放资源 connection prepareStatement resultSet

            if(resultSet!=null) {

                try {

                    resultSet.close();

                } catch (SQLException e) {

                    e.printStackTrace();

                }

            }

            if(prepareStatement!=null) {

                try {

                    prepareStatement.close();

                } catch (SQLException e) {

                    e.printStackTrace();

                }

            }

            if(connection!=null) {

                try {

                    connection.close();

                } catch (SQLException e) {

                    e.printStackTrace();

                }

            }

        }

       

        public static void statementClose(Connection connection,Statement statement,ResultSet resultSet) {

            //5.释放资源 connection prepareStatement 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();

                }

            }

        }

    }

    ----------------------------- JdbcUtils.java 结束----------------------------

     

    1-2-2   JsonUtils.java

    在创建好的org.utils包中右击选择New,点击Class,在name中填写JsonUtils,点击finish。打开新建好的JsonUtils.java文件,将下面代码复制到文件中。这部分的代码就是将List类型的数据封装到JSONArray,在向客户端发送返回信息时会反复用到,所以封装出来。

     

    -----------------------------JsonUtils.java开始 ----------------------------

    package org.utils;

     

    import net.sf.json.JSONArray;

    import net.sf.json.JSONObject;

    import java.util.List;

    import java.util.Map;

     

    public class JsonUtils {

        public static JSONArray formatRsToJsonArray(List<Map<String,Object>> data){

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

            for(Map<String,Object> rowItem:data) {

                JSONObject json = new JSONObject();

                    for(Map.Entry<String, Object> entry:rowItem.entrySet()) {

                        json.put(entry.getKey(), entry.getValue());

                    }

                jsonArray.add(json);

            }

            return jsonArray;

        }

    }

     

    -------------------------------- JsonUtils.java结束 --------------------------

     

    1-3 Servlet

    打开iShareService,找到src目录,右击选择New,点击Package,在Name中填写myServlet.data,点击finish。打开iShareService> WebRoot>images文件夹,将文末链接资源中的图片复制到images文件夹下。

     

    1-3-1   Register.java

        在创建好的myServlet.data包中右击选择New,点击Servlet,在Class name中填写Register,点击finish。打开新建好的Register.java文件,将下面代码复制到文件中。这部分代码主要就是获取到从客户端传过来的参数——用户名、密码、签名,然后设置用户默认头像为userImg.png,再把这些字段插入到表user中,完成用户注册。

     

    ----------------------------- Register.java开始 -----------------------------

    package myServlet.data;

     

    import java.io.IOException;

    import java.io.PrintWriter;

    import java.sql.Connection;

    import java.sql.PreparedStatement;

     

    import javax.servlet.ServletException;

    import javax.servlet.http.HttpServlet;

    import javax.servlet.http.HttpServletRequest;

    import javax.servlet.http.HttpServletResponse;

     

    import org.utils.JdbcUtils;

     

     

    public class Register extends HttpServlet{

     

        /**

         * 注册

         */

        private static final long serialVersionUID = 1L;

       

     

        public 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 username =request.getParameter("username");

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

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

             String userlogimage = "userImg.png";  /* 默认头像*/    

             

            Connection connection = null;

            PreparedStatement prepareStatement = null;

            try {

                connection = JdbcUtils.getConnection();

                //3.获取statement

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

                prepareStatement = connection.prepareStatement(sql);

                prepareStatement.setString(1, username);

                prepareStatement.setString(2, password);

                prepareStatement.setString(3, signature);

                prepareStatement.setString(4, userlogimage);

                //4.执行sql

                prepareStatement.execute();

                out.print("注册成功!");

     

            } catch (Exception e) {

                e.printStackTrace();

                out.print("该用户名已被使用,请更换名字!"+e);

               

            }finally {

                //5.释放资源 connection prepareStatement

                JdbcUtils.close(connection, prepareStatement, null);

            }

             out.flush();

             out.close();

        }

       

        public void doPost(HttpServletRequest request, HttpServletResponse response)

                throws ServletException, IOException {

          doGet(request, response);

        }

    }

    ---------------------------- Register.java结束 -----------------------------

     

    1-3-2   Login.java

        在创建好的myServlet.data包中右击选择New,点击Servlet,在Class name中填写Login,点击finish。打开新建好的Login.java文件,将下面代码复制到文件中。这部分代码主要就是获取到从客户端传过来的参数——用户名、密码,然后查询用户表user中是否存在该用户和对应的密码,存在则登录成功,返回查询到的用户昵称、签名、用户头像。

     

    ------------------------------Login.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.ServletConfig;

    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 Login

     */

    @WebServlet("/Login")

    public class Login extends HttpServlet {

        private static final long serialVersionUID = 1L;

          

        /**

         * @see Servlet#init(ServletConfig)

         */

        public void init(ServletConfig config) throws ServletException {

            // TODO Auto-generated method stub

            super.init(config);

        }

     

        /**

         * @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 password = request.getParameter("password").trim();

            String signature = "在这里写下你的心情吧!";

            String userHeadImg = "";

                 

           

            if(username == null) {

                username = "";

            }

           

            if(password == null) {

                password = "";

            }

         

            Connection connection = null;

            PreparedStatement prepareStatement = null;

            ResultSet rs = null;

            String backnews="";

            boolean boo = false;

           

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

           

            try {

                connection = JdbcUtils.getConnection();

               

                //3.获取statement

                String sql ="select * from user where username=? and password=?";

                prepareStatement = connection.prepareStatement(sql);

                prepareStatement.setString(1, username);

                prepareStatement.setString(2, password);

               

                if(boo) {

                    //4.执行sql

                    boolean m =false;

                   

                    rs = prepareStatement.executeQuery();

                    while(rs.next()) {

                        signature = rs.getString(3);

                        userHeadImg = rs.getString(4);

                        m = true;

                    }

                   

                    if(m==true) {

                        //登录成功

                        success(request,response,username,userHeadImg,signature,backnews);

                    }else {

                        backnews="你输入的用户名或密码有误!";

                        fail(request,response,username,backnews);

                    }

                }else {

                    backnews="请输入用户名和密码";

                    fail(request,response,username,backnews);

                }

               

     

            } catch (Exception e) {

                backnews=""+e.toString();

                e.printStackTrace();

                fail(request,response,username,backnews);

            }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,String userName,String userLogImage,String signature,String backnews) {

            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("userName", userName);

                map.put("signature", signature);

                map.put("userLogImage", userLogImage);

       

                data.add(map);

                jsonArray = JsonUtils.formatRsToJsonArray(data);

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

            }catch(IOException e) {

                e.printStackTrace();

            }

        }

       

        public void fail(HttpServletRequest request, HttpServletResponse response,String logname,String backnews) {

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

            try {

                 PrintWriter out = response.getWriter();

                 out.println(backnews);

               

            }catch(IOException e) {

                e.printStackTrace();

            }

        }

     

    }

    ----------------------------- Login.java结束-- ----------------------------

     

    1-3-3   QueryDiscover.java

        在创建好的myServlet.data包中右击选择New,点击Servlet,在Class name中填写QueryDiscover,点击finish。打开新建好的QueryDiscover.java文件,将下面代码复制到文件中。这部分代码主要就是查询内容表info,将查询内容封装到Json中返回给客户端。

     

    ----------------------------QueryDiscover.java开始-- -------------------------

    package myServlet.data;

    import java.io.IOException;

    import java.io.PrintWriter;

    import java.sql.Connection;

    import java.sql.ResultSet;

    /*import java.sql.ResultSetMetaData;*/

    import java.sql.Statement;

    import javax.servlet.ServletConfig;

    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;

    import java.util.List;

    import java.util.Map;

    import java.util.HashMap;

    import java.util.ArrayList;

     

    /**

     * Servlet implementation class QueryDiscover

     */

    @WebServlet("/QueryDiscover")

    public class QueryDiscover extends HttpServlet {

        private static final long serialVersionUID = 1L;

       

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

        int pageSize; //每页加载数量

        int pageNum;   //第几页

        int totalRecord;  //总记录数

        int totalPage;   //总页数

       

        /**

         * @see HttpServlet#HttpServlet()

         */

        public QueryDiscover() {

            super();

            // TODO Auto-generated constructor stub

        }

     

        /**

         * @see Servlet#init(ServletConfig)

         */

        public void init(ServletConfig config) throws ServletException {

            // TODO Auto-generated method 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 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);    //每页加载几条

            } catch (NumberFormatException e) {

                e.printStackTrace();

            }

           

            String condition = "select * from info order by 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 {

                        //ResultSetMetaData metaData = rowSet.getMetaData();

                        //int columnCount = metaData.getColumnCount();  //返回总列数

                       

                        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) {

     

                }

           

        }

    }

    ------------------------QueryDiscover.java结束-- -------------------------

     

    1-3-4   QueryInfoById.java

        在创建好的myServlet.data包中右击选择New,点击Servlet,在Class name中填写QueryInfoById,点击finish。打开新建好的QueryInfoById.java文件,将下面代码复制到文件中。这部分代码主要就是根据客户端传来的内容Id去查询内容表info中对应的内容相关信息,将查询结果封装到Json中返回给客户端。

    -------------------------- QueryInfoById.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 QueryInfoById

     */

    @WebServlet("/QueryInfoById")

    public class QueryInfoById extends HttpServlet {

        private static final long serialVersionUID = 1L;

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

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

        int pageNum=1;   //第几页

        int totalRecord;  //总记录数

       

        /**

         * @see HttpServlet#HttpServlet()

         */

        public QueryInfoById() {

            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

            // 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");

           

            if(infoId == null||infoId.length()==0) {

                return;

            }

       

            String condition ="select * from info where info_id="+infoId;   //按id查找

       

       

            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);

               

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

                response.setCharacterEncoding("utf-8");

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

               

                //将rowSet的数据提取到Map

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

                try {

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

                    totalRecord = rowSet.getRow();

                   

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

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

                    boolean boo = true;

                   

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

                        int id = 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", id);

                        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);

                   

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

                   

                }catch(Exception e) {

                    out.println("null");

                }

            } 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);

        }

     

    }

    ------------------------- QueryInfoById.java结束-- -------------------------

     

    1-3-5   QueryHotInfo.java

        在创建好的myServlet.data包中右击选择New,点击Servlet,在Class name中填写QueryHotInfo,点击finish。打开新建好的QueryHotInfo.java文件,将下面代码复制到文件中。这部分代码主要就是查询内容表info中点赞数排行前十的内容相关信息,并将将查询结果封装到Json中返回给客户端。

     

    ---------------------------- QueryHotInfo.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.ServletConfig;

    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 QueryHotInfo

     */

    @WebServlet("/QueryHotInfo")

    public class QueryHotInfo 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 QueryHotInfo() {

            super();

            // TODO Auto-generated constructor stub

        }

     

        /**

         * @see Servlet#init(ServletConfig)

         */

        public void init(ServletConfig config) throws ServletException {

            // TODO Auto-generated method 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 condition = "select * from info order by info_support 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 {

                        //ResultSetMetaData metaData = rowSet.getMetaData();

                        //int columnCount = metaData.getColumnCount();  //返回总列数

                       

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

                        totalRecord = rowSet.getRow();

                       

                        /*out.println("全部记录数"+totalRecord);  //全部的记录数*/                 

                        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) {

                   

                }

           

        }

    }

     

    ------------------------ QueryHotInfo.java结束-- ---------------------------

     

    1-3-6   QueryInfoByKey.java

        在创建好的myServlet.data包中右击选择New,点击Servlet,在Class name中填写QueryInfoByKey,点击finish。打开新建好的QueryInfoByKey.java文件,将下面代码复制到文件中。这部分代码主要就是获取客户端传递的关键词,去info表中的标题和简述查找与关键字相关的内容并封装成Json返回。

     

    ----------------------- QueryInfoByKey.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.ServletConfig;

    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 QueryInfoByKey

     */

    @WebServlet("/QueryInfoByKey")

    public class QueryInfoByKey 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 QueryInfoByKey() {

            super();

            // TODO Auto-generated constructor stub

        }

     

        /**

         * @see Servlet#init(ServletConfig)

         */

        public void init(ServletConfig config) throws ServletException {

            // TODO Auto-generated method 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 keyWord = request.getParameter("key");  

           

            if(keyWord == null||keyWord.length()==0) {

                return;

            }

       

            String condition ="select * from info where info_title like '%"+keyWord+"%' or info_describe like '%"+keyWord+"%'" ;   //按关键词查找

       

            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<=totalRecord&&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) {

                   

                }

           

        }

     

    }

    ------------------------QueryInfoByKey.java结束-- ---------------------------

    1-3-7   QueryPeopleInfoByKey.java

       在创建好的myServlet.data包中右击选择New,点击Servlet,在Class name中填写QueryPeopleInfoByKey,点击finish。打开新建好的QueryPeopleInfoByKey.java文件,将下面代码复制到文件中。这部分代码主要就是获取客户端传递的关键词,去user表中的昵称查找与关键字相关的用户信息并封装成Json返回。

     

    --------------------- QueryPeopleInfoByKey.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.ServletConfig;

    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 QueryPeopleInfo

     */

    @WebServlet("/QueryPeopleInfoByKey")

    public class QueryPeopleInfoByKey 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 QueryPeopleInfoByKey() {

            super();

            // TODO Auto-generated constructor stub

        }

     

        /**

         * @see Servlet#init(ServletConfig)

         */

        public void init(ServletConfig config) throws ServletException {

            // TODO Auto-generated method 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 keyWord = request.getParameter("nameKey");  

           

            if(keyWord == null||keyWord.length()==0) {

                return;

            }

       

            String condition ="select * from user where username like '%"+keyWord+"%'" ;   //按关键词查找

       

            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<=totalRecord&&boo;i++){     

                            String userName = rowSet.getString(1);    //用户昵称                       

                            //String passWord = rowSet.getString(2);   //用户密码              

                            String signature = rowSet.getString(3);   //用户签名

                            String userLogImage = rowSet.getString(4);   //用户头像

                           

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

                            map.put("userName", userName);

                            /*map.put("passWord", passWord);*/

                            map.put("signature", signature);

                            map.put("userLogImage", userLogImage);

                   

                            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) {

                   

                }

           

        }

     

    }

     

    ----------------------- QueryPeopleInfoByKey.java结束-- -----------------------

     

    1-3-8   AddInfo.java

        在创建好的myServlet.data包中右击选择New,点击Servlet,在Class name中填写AddInfo,点击finish。打开新建好的AddInfo.java文件,将下面代码复制到文件中。这部分代码主要就是获取客户端传递的内容标题、内容简述、内容详情、内容类型、内容发布者,并将点赞数设置为0之后插到内容表info中,完成发布的功能。

     

    ----------------------------- AddInfo.java开始-- -----------------------------

    package myServlet.data;

     

    import java.io.IOException;

    import java.io.PrintWriter;

    import java.sql.Connection;

    import java.sql.PreparedStatement;

     

    import javax.servlet.ServletConfig;

    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;

     

    /**

     * Servlet implementation class AddInfo

     */

    @WebServlet("/AddInfo")

    public class AddInfo extends HttpServlet {

        private static final long serialVersionUID = 1L;

          

        /**

         * @see HttpServlet#HttpServlet()

         */

        public AddInfo() {

            super();

            // TODO Auto-generated constructor stub

        }

     

        /**

         * @see Servlet#init(ServletConfig)

         */

        public void init(ServletConfig config) throws ServletException {

            // TODO Auto-generated method stub

        }

     

         //处理中文字符串

        public String handleString(String s) {

            try {

                byte bb[]=s.getBytes("ISO8859-1");

                s=new String(bb,"UTF-8");

            }catch(Exception e){}

           

            return s;

        }

       

        public 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();

           

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

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

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

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

     

            String typeStr = request.getParameter("type");    //类型:0表示日记,1表示趣事

            Integer type = 0;

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

                typeStr = "0";

            }

           

            try {

                type = Integer.parseInt(typeStr);    //内容类型

            } catch (NumberFormatException e) {

                e.printStackTrace();

            }

          

            Integer support = 0;   //点赞数,默认设置为0

            String infoAuthor = request.getParameter("infoAuthor");  //作者

            

            Connection connection = null;

            PreparedStatement prepareStatement = null;

            try {

                connection = JdbcUtils.getConnection();

                //3.获取statement

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

                prepareStatement = connection.prepareStatement(sql);

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

                prepareStatement.setString(2, infoTitle);

                prepareStatement.setString(3, infoDescribe);

                prepareStatement.setString(4, infoDetail);

                prepareStatement.setInt(5, type);

                prepareStatement.setInt(6, support);

                prepareStatement.setString(7, infoAuthor);

                //4.执行sql

                prepareStatement.execute();

                out.print("发布成功!");

     

            } catch (Exception e) {

                e.printStackTrace();

                out.print("发布失败!"+e);

               

            }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);

        }

     

    }

    ----------------------------- AddInfo.java结束-- ---------------------------

     

    1-3-9   ChangeSignature.java

        在创建好的myServlet.data包中右击选择New,点击Servlet,在Class name中填写ChangeSignature,点击finish。打开新建好的ChangeSignature.java文件,将下面代码复制到文件中。这部分代码主要就是获取客户端传递的用户名、新签名,然后在User表中查找到对应的用户,更新签名。

     

    --------------------------- ChangeSignature.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 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;

     

    /**

     * Servlet implementation class ChangeSignature

     */

    @WebServlet("/ChangeSignature")

    public class ChangeSignature extends HttpServlet {

        private static final long serialVersionUID = 1L;

          

        /**

         * @see HttpServlet#HttpServlet()

         */

        public ChangeSignature() {

            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 signature = request.getParameter("signature").trim();

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

           

            if(signature == null) {

                signature = "";

            }

           

            if(userName == null) {

                userName = "";

            }

           

            Connection connection = null;

            PreparedStatement prepareStatement = null;

            PreparedStatement prepareStatement2 = null;

            ResultSet rs = null;

            ResultSet rs2 =null;

           

            String backnews="";

            boolean boo = false;

           

            boo = signature.length()>0&&userName.length()>0;

           

            try {

                connection = JdbcUtils.getConnection();

           

                //3.获取statement

                String sql ="select * from user where username=?";

                prepareStatement = connection.prepareStatement(sql);

                prepareStatement.setString(1, userName);

               

                if(boo) {

                    //4.执行sql

                    rs = prepareStatement.executeQuery();

                    boolean m = rs.next();

                   

                    if(m==true) {

                        //查询成功

                        String changeSql = "update user set signature=? where username=?";

                        prepareStatement2 = connection.prepareStatement(changeSql);

                        prepareStatement2.setString(1, signature);

                        prepareStatement2.setString(2, userName);

                       

                        prepareStatement2.execute();

                        backnews="修改成功";

                       

                    }else {

                        backnews="没有该用户!";

                    }

                }else {

                    backnews="新签名不能为空";

                }

                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);

        }

     

    }

    -------------------------ChangeSignature.java结束-- -------------------------

     

    1-3-10  ChangePassword.java

        在创建好的myServlet.data包中右击选择New,点击Servlet,在Class name中填写ChangePassword,点击finish。打开新建好的ChangePassword.java文件,将下面代码复制到文件中。这部分代码主要就是获取客户端传递的用户名、旧密码、新密码,然后在User表中查找到对应的用户名和密码的用户,将密码更新。

     

    -------------------------ChangePassword.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 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;

     

    /**

     * Servlet implementation class ChangePassword

     */

    @WebServlet("/ChangePassword")

    public class ChangePassword extends HttpServlet {

        private static final long serialVersionUID = 1L;

          

        /**

         * @see HttpServlet#HttpServlet()

         */

        public ChangePassword() {

            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 oldPass = request.getParameter("oldPass");

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

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

           

           

            if(oldPass == null||oldPass.length()==0) {

                oldPass="";

            }

           

            if(newPass == null||newPass.length()==0) {

                newPass="";

            }

           

           

            if(userName == null||userName.length()==0) {

                userName = "";

            }

           

            Connection connection = null;

            PreparedStatement prepareStatement = null;

            PreparedStatement prepareStatement2 = null;

            ResultSet rs = null;

            ResultSet rs2 =null;

           

            String backnews="";

            boolean boo = false;

           

            boo = oldPass.length()>0&&oldPass.length()>0&&userName.length()>0;

           

            try {

                connection = JdbcUtils.getConnection();

           

                //3.获取statement

                String sql ="select * from user where username=?";

                prepareStatement = connection.prepareStatement(sql);

                prepareStatement.setString(1, userName);

               

                if(boo) {

                    //4.执行sql

                    rs = prepareStatement.executeQuery();

                    boolean m = rs.next();

                   

                    if(m==true) {

                        //查询成功

                        String changeSql = "update user set password=? where username=? and password=?";

                        prepareStatement2 = connection.prepareStatement(changeSql);

                        prepareStatement2.setString(1, newPass);

                        prepareStatement2.setString(2, userName);

                        prepareStatement2.setString(3, oldPass);

                        prepareStatement2.execute();

                        backnews="修改成功";

                       

                    }else {

                        backnews="没有该用户!";

                    }

                }else {

                    backnews="密码不能为空!";

                }

                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);

        }

    }

    ------------------------ChangePassword.java结束-- ------------------------

    最新回复(0)