团队项目-第一阶段冲刺-7

一、说在前面

1、昨天完成了:

1)优化新闻详情界面(原来是用一个简单的textView控件来展示整个新闻文本,没有分段,换行等不美观!)现在改用webView展示新闻文本(实质是一个div)。

2、今天完成了:

1)实现用户对新闻评论的存储,和回显。

3、明天的计划:

1)整合登入界面

4、遇到的问题:

HttpURLConnection以get方式发送包含中文的网址时web端接收到的是乱码!!(未解决)

二、冲刺成果:

三、设计思路

1、新建一张评论表 Comment(nid,name,content)。用来存储所有用户的评论。

2、在用户添加评论时将评论的信息通过http请求发送到web端存入数据库。

3、进入新闻界面时,向web端请求此新闻的评论集合。并展示出来。

四、代码

1、web端-servlet

package com.me.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

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 com.google.gson.Gson;
import com.me.dao.NewsDao;
import com.me.domain.Comment;
import com.me.domain.News;


@WebServlet("/news")
public class NewsServlet_ extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private NewsDao dao = new NewsDao();
    public NewsServlet_() {
        super();
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         response.setHeader("content-type", "text/html;charset=UTF-8");
         request.setCharacterEncoding("UTF-8");

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

            if (method.equals("allnews")){
                allnews(request,response);
            }else if (method.equals("search")){
                search(request,response);
            }else if (method.equals("addUser")){
                addUser(request,response);
            }else if (method.equals("addComment")){
                addComment(request,response);
            }else if (method.equals("commentList")){
                commentList(request,response);
            }
    }

    
    /**
     * @param request
     * @param response
     * @throws IOException 
     */
    private void commentList(HttpServletRequest request, HttpServletResponse response) throws IOException {
         List<Comment> news = new ArrayList<Comment>();
         String nid = request.getParameter("nid");
         System.out.println(nid);
            try {
                news = dao.commentList(Integer.valueOf(nid));
            } catch (SQLException e) {
                e.printStackTrace();
            }

            Gson gson = new Gson();
            String s = gson.toJson(news);
            response.getWriter().write(s);
        
    }


    private void addComment(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter("name");
        String content = request.getParameter("content");
        String nid = request.getParameter("nid");
        Comment comment = new Comment();
        comment.setContent(content);
        comment.setName(name);
        comment.setNid(Integer.valueOf(nid));
        System.out.println(comment.toString());
        try {
            boolean f = dao.addComment(comment);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    private void addUser(HttpServletRequest request, HttpServletResponse response) {
        String username = request.getParameter("username");
        try {
            boolean f = dao.addUser(username);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
    private void search(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String word = request.getParameter("word");
        List<News> news = new ArrayList<News>();
        try {
            news = dao.search(word);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        Gson gson = new Gson();
        String s = gson.toJson(news);
        response.getWriter().write(s);
    }

    private void allnews(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<News> news = new ArrayList<News>();
        try {
            news = dao.newsList();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        Gson gson = new Gson();
        String s = gson.toJson(news);
        response.getWriter().write(s);
    }

}
View Code

2、web端-dao

package com.me.dao;

import com.me.domain.News;
import com.me.utils.DBUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class NewsDao {



    public boolean deleteBad() throws SQLException {
        QueryRunner qr =new QueryRunner(DBUtils.getDataSource());
        String sql="delete from newslist  where zw = null or zw=?";
        int n = qr.update(sql,"");
        if (n > 0) {
            return true;
        } else {
            return false;
        }
    }

    public boolean deleteAll() throws SQLException {
        QueryRunner qr =new QueryRunner(DBUtils.getDataSource());
        String sql="delete from newslist  ";
        int n = qr.update(sql);
        if (n > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     *
     * @param zw
     * @param id
     * @return
     * @throws SQLException
     */
    public boolean zw(String zw,int id) throws SQLException {

        QueryRunner qr = new QueryRunner(DBUtils.getDataSource());
        String sql = "update newslist set zw = ?   where id=? ";
        int n = qr.update(sql, zw,id);
        if (n > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     *
     * @return List<News>
     * @throws SQLException
     */
    public List<News> newsList() throws SQLException {
        QueryRunner qr = new QueryRunner(DBUtils.getDataSource());
        String sql = "select * from newslist where url != null  or url != '17KK0006|2145432'or url != ?";
        List<News> query = qr.query(sql, new BeanListHandler<News>(News.class),"");
        return query;
    }

    /**
     *
     * @param world
     * @return
     * @throws SQLException
     */
    public List<News> search(String world) throws SQLException {
        QueryRunner qr = new QueryRunner(DBUtils.getDataSource());
        String sql = "select * from newslist where  title like '%"+world+"%' limit 0 , 5";
        System.out.println(sql);
        List<News> query = qr.query(sql, new BeanListHandler<News>(News.class));
        return query;
    }

    /**
     *
     * @param news
     * @return
     * @throws SQLException
     */
    public boolean add(News news) throws SQLException {
        QueryRunner qr = new QueryRunner(DBUtils.getDataSource());
        String sql = "insert into newslist (source,title,priority,url,commentCount,digest,imgsrc,ptime,type) " +
                "values(?,?,?,?,?,?,?,?,?)";
        int update = qr.update(sql,news.getSource(),news.getTitle(),news.getPriority(),news.getUrl(),news.getCommentCount(),
                news.getDigest(),news.getImgsrc(),news.getPtime(),news.getType());
        if (update > 0) {
            return true;
        } else {
            return false;
        }
    }

}
View Code

3、android-逻辑代码更新

package com.me.news_2;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.me.adapter.AdapterComment;
import com.me.domain.Comment;
import com.me.domain.New_;
import com.me.domain.News;
import com.me.util.HttpUtil;
import com.me.util.JsoupNewsUtil;
import com.me.view.MyImageView;

import java.util.ArrayList;
import java.util.List;

public class NewsActivity extends AppCompatActivity implements View.OnClickListener{

    private MyImageView imageView;
    private WebView zw;
    private LinearLayout linearLayout;
    private ImageView comment;
    private ImageView chat;
    private TextView hide_down;
    private EditText comment_content;
    private Button comment_send;
    private SentUrlTask sentUrlTask;
    private SentUrlTask_ sentUrlTask_;
    private SentUrlTask_getComment sentUrlTask_getComment;
    private LinearLayout rl_enroll;
    private RelativeLayout rl_comment;

    private ListView comment_list;
    private AdapterComment adapterComment;
    private List<Comment> data;
    private New_ new_2 = new New_();
    private String html;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news);
        initView();
        action();
    }

    private class SentUrlTask extends AsyncTask<Void,Void,String> {

        private  String url;

        public SentUrlTask(String url) {
            this.url = url;
        }

        @Override
        protected String doInBackground(Void... voids) {
            return HttpUtil.setUrlT(url);
        }

        @Override
        protected void onPostExecute(@NonNull String s) {
            super.onPostExecute(s);
            html = JsoupNewsUtil.zwHtml(s);
            zw.loadData(html,"text/html;charset=utf-8",null);
        }

    }


    public void initView(){
        imageView = findViewById(R.id.iv_new_dg);
        zw = findViewById(R.id.wv_zw);
        linearLayout = findViewById(R.id.linearLayout);
        // 初始化评论列表
        comment_list =  findViewById(R.id.comment_list);
        // 初始化数据
        if (data==null){
            data = new ArrayList<>();
        }
        // 初始化适配器
        adapterComment = new AdapterComment(getApplicationContext(), data);
        // 为评论列表设置适配器
        comment_list.setAdapter(adapterComment);

        comment = findViewById(R.id.comment);
        hide_down =  findViewById(R.id.hide_down);
        comment_content = findViewById(R.id.comment_content);
        comment_send = findViewById(R.id.comment_send);

        rl_enroll =  findViewById(R.id.rl_enroll);
        rl_comment =  findViewById(R.id.rl_comment);
        chat = findViewById(R.id.chat);
        setListener();
    }

    /**
     * 设置监听
     */
    public void setListener(){
        comment.setOnClickListener(this);
        hide_down.setOnClickListener(this);
        comment_send.setOnClickListener(this);
        chat.setOnClickListener(this);
    }


    public void action(){
        Intent intent = getIntent();
        String news = intent.getStringExtra("news");
        Gson gson = new Gson();
        New_ news1 = gson.fromJson(news, New_.class);
        new_2 = news1;
        getComment(new_2.getId());
        if(news1!=null){
            sentUrlTask = new SentUrlTask(news1.getUrl());
            sentUrlTask.execute();
            imageView.setImageURL(news1.getImgsrc());
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.comment:
                // 弹出输入法
                InputMethodManager imm = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                // 显示评论框
                rl_enroll.setVisibility(View.GONE);
                rl_comment.setVisibility(View.VISIBLE);
                break;
            case R.id.hide_down:
                // 隐藏评论框
                rl_enroll.setVisibility(View.VISIBLE);
                rl_comment.setVisibility(View.GONE);
                // 隐藏输入法,然后暂存当前输入框的内容,方便下次使用
                InputMethodManager im = (InputMethodManager)getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                im.hideSoftInputFromWindow(comment_content.getWindowToken(), 0);
                break;
            case R.id.comment_send:
                sendComment();
                break;
            case R.id.chat:
                if(View.GONE==comment_list.getVisibility()){
                    comment_list.setVisibility(View.VISIBLE);
//                    linearLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,200));
                }else{
                    comment_list.setVisibility(View.GONE);
//                    linearLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,60));
                }

            default:
                break;
        }

    }
    /**
     * 发送评论
     */
    public void sendComment() {
        if (comment_content.getText().toString().equals("")) {
            Toast.makeText(getApplicationContext(), "评论不能为空!", Toast.LENGTH_SHORT).show();
        } else {
            sent("Test",comment_content.getText().toString(),new_2.getId());
            // 生成评论数据

            Comment comment = new Comment();
            comment.setName("笑天" + ":");
            comment.setContent(comment_content.getText().toString());
            adapterComment.addComment(comment);
            // 发送完,清空输入框
            comment_content.setText("");

            Toast.makeText(getApplicationContext(), "评论成功!", Toast.LENGTH_SHORT).show();
        }
    }

    public void sent(String name,String content,int nid){
        sentUrlTask_ = new SentUrlTask_("http://192.168.1.17:8080/NewsApi/news?method=addComment&name="+name+"&content="+content+"&nid="+nid);
//        sentUrlTask = new ListFragment.SentUrlTask("http://192.168.43.243:8080/NewsApi/news?method=allnews");
        sentUrlTask_.execute();
    }
    public void getComment(int nid){
        sentUrlTask_getComment = new SentUrlTask_getComment("http://192.168.1.17:8080/NewsApi/news?method=commentList&nid="+nid);
//        sentUrlTask = new ListFragment.SentUrlTask("http://192.168.43.243:8080/NewsApi/news?method=allnews");
        sentUrlTask_getComment.execute();
    }

    private class SentUrlTask_ extends AsyncTask<Void,Void,String> {

        private  String url;

        public SentUrlTask_(String url) {
            this.url = url;
        }

        @Override
        protected String doInBackground(Void... voids) {
            return HttpUtil.setUrl(url);
        }

        @Override
        protected void onPostExecute(@NonNull String s) {
            super.onPostExecute(s);
//            zw.loadData(html,"text/html;charset=utf-8",null);
        }
    }
    private class SentUrlTask_getComment extends AsyncTask<Void,Void,String> {

        private  String url;

        public SentUrlTask_getComment(String url) {
            this.url = url;
        }

        @Override
        protected String doInBackground(Void... voids) {
            return HttpUtil.setUrl(url);
        }

        @Override
        protected void onPostExecute(@NonNull String s) {
            super.onPostExecute(s);
//            zw.loadData(html,"text/html;charset=utf-8",null);
            Gson gson = new Gson();
//            Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
            if(!s.equals("")){
                data = gson.fromJson(s,new TypeToken<List<Comment>>(){}.getType());
                adapterComment.setData(data);
            }

        }
    }
}
View Code
原文地址:https://www.cnblogs.com/20183544-wangzhengshuai/p/12743055.html