目录
准备工作
idea工具(专业版)编辑
IntelliJ IDEA创建Servlet最新方法
mysql:个人使用的MySQL5.7编辑
mysql:可以使用SQLyou编辑
Android:可以使用Android Stuodio编辑
Android中代码
IDEA中代码
个人错误
Java代码错误
部分需要jar包和框架
显示代码:
Android:页面显示
idea的java:页面显示
编辑
总结
MainActivity
package com.e.myapplicationtest.activity;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.e.myapplicationtest.R;
import com.e.myapplicationtest.fragment.MyPagerAdapter;
import com.e.myapplicationtest.fragment.NewsFramgment1;
import com.e.myapplicationtest.fragment.NewsFramgment2;
import com.e.myapplicationtest.fragment.NewsFramgment3;
import com.e.myapplicationtest.fragment.NewsFramgment4;
import com.google.android.material.tabs.TabLayout;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ViewPager mViewPager;
private TabLayout tabLayout;
private MyPagerAdapter myPagerAdapter;
private List titlelist = new ArrayList();
private NewsFramgment1 nfragment1;
private NewsFramgment2 nfragment2;
private NewsFramgment3 nfragment3;
private NewsFramgment4 nfragment4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
titlelist.add("爱情");
titlelist.add("励志");
titlelist.add("喜剧");
titlelist.add("我的");
nfragment1 = new NewsFramgment1();
nfragment2 = new NewsFramgment2();
nfragment3 = new NewsFramgment3();
nfragment4 = new NewsFramgment4();
ArrayList fragmntList = new ArrayList();
fragmntList.add(nfragment1);
fragmntList.add(nfragment2);
fragmntList.add(nfragment3);
fragmntList.add(nfragment4);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
myPagerAdapter = new MyPagerAdapter(getSupportFragmentManager(),titlelist, fragmntList);
mViewPager.setAdapter(myPagerAdapter);
tabLayout.setupWithViewPager(mViewPager);
}
}
ShowNewsActivity
package com.e.myapplicationtest.activity;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Window;
import android.widget.TextView;
import com.e.myapplicationtest.R;
import com.e.myapplicationtest.bean.NewsBean;
import com.loopj.android.image.SmartImageView;
public class ShowNewsActivity extends AppCompatActivity {
TextView title,author,time,content;
SmartImageView imageView;
static BitmapFactory.Options opts;
Bitmap bitmap = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//去掉标题栏
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_show_news);
Intent intent = getIntent();
NewsBean newsBean = (NewsBean) intent.getExtras().getSerializable("NewsList");
// 显示子啊什么位置
title = (TextView) this.findViewById(R.id.title);
author = (TextView) this.findViewById(R.id.author);
time = (TextView) this.findViewById(R.id.time);
content = (TextView) this.findViewById(R.id.content);
imageView = (SmartImageView) this.findViewById(R.id.img_name);
// 获取数据
title.setText(newsBean.getTitle());
author.setText(newsBean.getAuthor());
time.setText(newsBean.getTime());
content.setText(newsBean.getContent());
imageView.setImageUrl("http//(ip地址):8080/Web1/TestServlet/img/"+newsBean.getImg_name(),R.drawable.newspic1);
}
}
NewsBean
package com.e.myapplicationtest.bean;
import java.io.Serializable;
public class NewsBean implements Serializable {
public int id;
public String title;
public String content;
public String img_url;
public String img_name;
public String big_img_name;
public String author;
public String time;
public int type_id;
private int status;
public NewsBean()
{
}
public NewsBean(int id, String title, String content, String img_url,
String img_name, String big_img_name, String author, String time,int type_id,int status) {
this.id = id;
this.title = title;
this.content = content;
this.img_url = img_url;
this.img_name = img_name;
this.big_img_name = big_img_name;
this.author = author;
this.time = time;
this.type_id = type_id;
this.status=status;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getImg_url() {
return img_url;
}
public void setImg_url(String img_url) {
this.img_url = img_url;
}
public String getImg_name() {
return img_name;
}
public void setImg_name(String img_name) {
this.img_name = img_name;
}
public String getBig_img_name() {
return big_img_name;
}
public void setBig_img_name(String big_img_name) {
this.big_img_name = big_img_name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public int getType_id() {
return type_id;
}
public void setType_id(int type_id) {
this.type_id = type_id;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
MyPagerAdapter
package com.e.myapplicationtest.fragment;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import java.util.ArrayList;
import java.util.List;
public class MyPagerAdapter extends FragmentPagerAdapter {
private List titlelist;
private ArrayList fragmentList;
public MyPagerAdapter(FragmentManager fm, List titlelist, ArrayList fragmentList) {
super(fm);
this.titlelist = titlelist;
this.fragmentList = fragmentList;
}
@NonNull
@Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
@Override
public int getCount() {
return fragmentList.size();
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return titlelist.get(position);
}
}
NewsFramgment1
package com.e.myapplicationtest.fragment;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
//import androidx.fragment.app.Fragment;
import android.preference.PreferenceActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import com.e.myapplicationtest.R;
import com.e.myapplicationtest.activity.ShowNewsActivity;
import com.e.myapplicationtest.bean.NewsBean;
import com.e.myapplicationtest.tool.JsonParse;
import com.e.myapplicationtest.tool.NewsListAdapter;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import org.apache.http.Header;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
* Use the {@link NewsFramgment1#?newInstance} factory method to
* create an instance of this fragment.
*/
public class NewsFramgment1 extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
ListView listView = null;
List newsLists = new ArrayList();
AsyncHttpClient client = new AsyncHttpClient();//创建AsyncHttpClient实例
// ListView listView = null;
private View mMainView;
//显示新闻大图片代码
private ViewPager viewPager;
private ImageView[] tips;//提示性点点数组
private int[] images;//图片ID数组
private int[] image_tips;
private int currentPage = 0 ;
public Bitmap[] bmp = null;
public Bitmap[] bmp_tips = null;
public NewsFramgment1() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
// * @param param1 Parameter 1.
// * @param param2 Parameter 2.
* @return A new instance of fragment NewsFramgment1.
*/
// TODO: Rename and change types and number of parameters
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater inflater = getActivity().getLayoutInflater();
mMainView = inflater.inflate(R.layout.fragment_news_framgment1,(ViewGroup) getActivity().findViewById(R.id.viewpager),false);
showBigImages();
listView = (ListView) mMainView.findViewById(R.id.listview);
//使用GET方式请求
client.get("http://(ip地址):8080/Web1/TestServlet/NewsSL?typeId=1",new AsyncHttpResponseHandler(){
public void onSuccess(int i , org.apache.http.Header[] headers, byte[] bytes){
//请求成功
try {
String json = new String(bytes,"gbk");
newsLists = JsonParse.getNewsInfo(json);
if (newsLists == null){
Log.i("newsList","解析失败!");
}else {
NewsListAdapter adapter = new NewsListAdapter(getActivity(),newsLists,listView);
listView.setAdapter(adapter);
//新闻列表被选中监听,跳转到新闻详细页面
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView> arg0, View arg1, int arg2, long arg3) {
Intent intent = new Intent(getActivity(), ShowNewsActivity.class);
NewsBean newsBean = newsLists.get(arg2);
Bundle bundle = new Bundle();
bundle.putSerializable("NewsList",newsBean);
intent.putExtras(bundle);
startActivity(intent);
}
});
}
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public void onFailure(int i, org.apache.http.Header[] headers ,byte[] bytes,Throwable throwable){
}
});
}
private void showBigImages() {
viewPager =(ViewPager) mMainView.findViewById(R.id.viewpager1);
//存放点点的容器
LinearLayout tipsBox = (LinearLayout) mMainView.findViewById(R.id.tipsBox);
//初始化图片资源
images = new int[]{R.drawable.app7,R.drawable.app2,R.drawable.app6};
image_tips = new int[]{R.drawable.page, R.drawable.pagenow};
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inPreferredConfig = Bitmap.Config.RGB_565;
opts.inPurgeable = true;
opts.inInputShareable = true;
bmp = new Bitmap[images.length];
for (int i = 0; i < images.length;i++){
InputStream is = this.getResources().openRawResource(images[i]);
bmp[i] = BitmapFactory.decodeStream(is,null,opts);//将普通图片转换成位图
}
//小原点图片
bmp_tips = new Bitmap[image_tips.length];
for (int i = 0 ; i < image_tips.length;i++){
InputStream is = this.getResources().openRawResource(image_tips[i]);
bmp_tips[i] = BitmapFactory.decodeStream(is,null,opts);//将普通图片转换成位图
}
//初始化 提示点点
tips = new ImageView[10];
for (int i = 0 ; i< images.length;i++){
ImageView img = new ImageView(getActivity());
img.setLayoutParams(new LinearLayout.LayoutParams(20,20));
tips[i] = img;
if (i == 0){
img.setImageBitmap(bmp_tips[1]);
}else {
img.setImageBitmap(bmp_tips[0]);
}
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
new ViewGroup.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
params.leftMargin = 20;
params.rightMargin =20;
tipsBox.addView(img,params);
}
//初始化PagerAdapter
PagerAdapter adapter = new PagerAdapter() {
@Override
public int getCount() {
return images.length;
}
@Override
public boolean isViewFromObject(@NonNull View arg0, @NonNull Object arg1) {
return arg0 == arg1;
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
ImageView im = new ImageView(getActivity());
im.setScaleType(ImageView.ScaleType.CENTER);
im.setImageBitmap(zoomImg(bmp[position],680,420));
container.addView(im);
return im;
}
};
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
Log.e("rf",String.valueOf(position));
tips[currentPage].setImageBitmap(bmp_tips[0]);
currentPage = position;
tips[currentPage].setImageBitmap(bmp_tips[1]);
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
private Bitmap zoomImg(Bitmap bm,int newWidth,int newHeight) {
//获得图片的宽高
int width = bm.getWidth();
int height = bm.getHeight();
//计算缩放比例
float scaleWidth = ((float) newWidth)/width;
float scaleHeight = ((float) newHeight)/height;
//取得想要缩放的matrix参数
Matrix martix = new Matrix();
martix.postScale(scaleWidth,scaleHeight);
//取得新的图片,www.2cto.com
Bitmap newbm = Bitmap.createBitmap(bm,0,0,width,height,martix,true);
return newbm;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup p = (ViewGroup) mMainView.getParent();
if (p!=null) {
p.removeAllViewsInLayout();
}
return mMainView;
}
}
NewsFramgment2
package com.e.myapplicationtest.fragment;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import com.e.myapplicationtest.R;
import com.e.myapplicationtest.activity.ShowNewsActivity;
import com.e.myapplicationtest.bean.NewsBean;
import com.e.myapplicationtest.tool.JsonParse;
import com.e.myapplicationtest.tool.NewsListAdapter;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
* Use the {@link NewsFramgment2#?newInstance} factory method to
* create an instance of this fragment.
*/
public class NewsFramgment2 extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
ListView listView = null;
List newsLists = new ArrayList();
AsyncHttpClient client = new AsyncHttpClient();//创建AsyncHttpClient实例
// ListView listView = null;
private View mMainView;
//显示新闻大图片代码
private ViewPager viewPager;
private ImageView[] tips;//提示性点点数组
private int[] images;//图片ID数组
private int[] image_tips;
private int currentPage = 0 ;
public Bitmap[] bmp = null;
public Bitmap[] bmp_tips = null;
public NewsFramgment2() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
// * @param param1 Parameter 1.
// * @param param2 Parameter 2.
* @return A new instance of fragment NewsFramgment1.
*/
// TODO: Rename and change types and number of parameters
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater inflater = getActivity().getLayoutInflater();
mMainView = inflater.inflate(R.layout.fragment_news_framgment2,(ViewGroup) getActivity().findViewById(R.id.viewpager),false);
showBigImages();
listView = (ListView) mMainView.findViewById(R.id.listview);
//使用GET方式请求
client.get("http://(ip地址):8080/Web1/TestServlet/NewsSL?typeId=2",new AsyncHttpResponseHandler(){
public void onSuccess(int i , org.apache.http.Header[] headers, byte[] bytes){
//请求成功
try {
String json = new String(bytes,"gbk");
newsLists = JsonParse.getNewsInfo(json);
if (newsLists == null){
Log.i("newsList","解析失败!");
}else {
NewsListAdapter adapter = new NewsListAdapter(getActivity(),newsLists,listView);
listView.setAdapter(adapter);
//新闻列表被选中监听,跳转到新闻详细页面
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView> arg0, View arg1, int arg2, long arg3) {
Intent intent = new Intent(getActivity(), ShowNewsActivity.class);
NewsBean newsBean = newsLists.get(arg2);
Bundle bundle = new Bundle();
bundle.putSerializable("NewsList",newsBean);
intent.putExtras(bundle);
startActivity(intent);
}
});
}
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public void onFailure(int i, org.apache.http.Header[] headers ,byte[] bytes,Throwable throwable){
}
});
}
private void showBigImages() {
viewPager =(ViewPager) mMainView.findViewById(R.id.viewpager2);
//存放点点的容器
LinearLayout tipsBox = (LinearLayout) mMainView.findViewById(R.id.tipsBox);
//初始化图片资源
images = new int[]{R.drawable.app9,R.drawable.app15,R.drawable.app5};
image_tips = new int[]{R.drawable.page, R.drawable.pagenow};
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inPreferredConfig = Bitmap.Config.RGB_565;
opts.inPurgeable = true;
opts.inInputShareable = true;
bmp = new Bitmap[images.length];
for (int i = 0; i < images.length;i++){
InputStream is = this.getResources().openRawResource(images[i]);
bmp[i] = BitmapFactory.decodeStream(is,null,opts);//将普通图片转换成位图
}
//小原点图片
bmp_tips = new Bitmap[image_tips.length];
for (int i = 0 ; i < image_tips.length;i++){
InputStream is = this.getResources().openRawResource(image_tips[i]);
bmp_tips[i] = BitmapFactory.decodeStream(is,null,opts);//将普通图片转换成位图
}
//初始化 提示点点
tips = new ImageView[5];
for (int i = 0 ; i< images.length;i++){
ImageView img = new ImageView(getActivity());
img.setLayoutParams(new LinearLayout.LayoutParams(20,20));
tips[i] = img;
if (i == 0){
img.setImageBitmap(bmp_tips[1]);
}else {
img.setImageBitmap(bmp_tips[0]);
}
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
new ViewGroup.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
params.leftMargin = 20;
params.rightMargin =20;
tipsBox.addView(img,params);
}
//初始化PagerAdapter
PagerAdapter adapter = new PagerAdapter() {
@Override
public int getCount() {
return images.length;
}
@Override
public boolean isViewFromObject(@NonNull View arg0, @NonNull Object arg1) {
return arg0 == arg1;
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
ImageView im = new ImageView(getActivity());
im.setScaleType(ImageView.ScaleType.CENTER);
im.setImageBitmap(zoomImg(bmp[position],680,420));
container.addView(im);
return im;
}
};
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
Log.e("rf",String.valueOf(position));
tips[currentPage].setImageBitmap(bmp_tips[0]);
currentPage = position;
tips[currentPage].setImageBitmap(bmp_tips[1]);
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
private Bitmap zoomImg(Bitmap bm,int newWidth,int newHeight) {
//获得图片的宽高
int width = bm.getWidth();
int height = bm.getHeight();
//计算缩放比例
float scaleWidth = ((float) newWidth)/width;
float scaleHeight = ((float) newHeight)/height;
//取得想要缩放的matrix参数
Matrix martix = new Matrix();
martix.postScale(scaleWidth,scaleHeight);
//取得新的图片,www.2cto.com
Bitmap newbm = Bitmap.createBitmap(bm,0,0,width,height,martix,true);
return newbm;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup p = (ViewGroup) mMainView.getParent();
if (p!=null) {
p.removeAllViewsInLayout();
}
return mMainView;
}
}
NewsFramgment3
package com.e.myapplicationtest.fragment;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
//import androidx.fragment.app.Fragment;
import android.preference.PreferenceActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import com.e.myapplicationtest.R;
import com.e.myapplicationtest.activity.ShowNewsActivity;
import com.e.myapplicationtest.bean.NewsBean;
import com.e.myapplicationtest.tool.JsonParse;
import com.e.myapplicationtest.tool.NewsListAdapter;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
* Use the {@link NewsFramgment3#?newInstance} factory method to
* create an instance of this fragment.
*/
public class NewsFramgment3 extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
ListView listView = null;
List newsLists = new ArrayList();
AsyncHttpClient client = new AsyncHttpClient();//创建AsyncHttpClient实例
// ListView listView = null;
private View mMainView;
//显示新闻大图片代码
private ViewPager viewPager;
private ImageView[] tips;//提示性点点数组
private int[] images;//图片ID数组
private int[] image_tips;
private int currentPage = 0 ;
public Bitmap[] bmp = null;
public Bitmap[] bmp_tips = null;
public NewsFramgment3() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
// * @param param1 Parameter 1.
// * @param param2 Parameter 2.
* @return A new instance of fragment NewsFramgment1.
*/
// TODO: Rename and change types and number of parameters
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater inflater = getActivity().getLayoutInflater();
mMainView = inflater.inflate(R.layout.fragment_news_framgment3,(ViewGroup) getActivity().findViewById(R.id.viewpager),false);
showBigImages();
listView = (ListView) mMainView.findViewById(R.id.listview);
//使用GET方式请求
client.get("http://(ip地址):8080/Web1/TestServlet/NewsSL?typeId=3",new AsyncHttpResponseHandler(){
public void onSuccess(int i , org.apache.http.Header[] headers, byte[] bytes){
//请求成功
try {
String json = new String(bytes,"gbk");
newsLists = JsonParse.getNewsInfo(json);
if (newsLists == null){
Log.i("newsList","解析失败!");
}else {
NewsListAdapter adapter = new NewsListAdapter(getActivity(),newsLists,listView);
listView.setAdapter(adapter);
//新闻列表被选中监听,跳转到新闻详细页面
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView> arg0, View arg1, int arg2, long arg3) {
Intent intent = new Intent(getActivity(), ShowNewsActivity.class);
NewsBean newsBean = newsLists.get(arg2);
Bundle bundle = new Bundle();
bundle.putSerializable("NewsList",newsBean);
intent.putExtras(bundle);
startActivity(intent);
}
});
}
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public void onFailure(int i, org.apache.http.Header[] headers ,byte[] bytes,Throwable throwable){
}
});
}
private void showBigImages() {
viewPager =(ViewPager) mMainView.findViewById(R.id.viewpager3);
//存放点点的容器
LinearLayout tipsBox = (LinearLayout) mMainView.findViewById(R.id.tipsBox);
//初始化图片资源
images = new int[]{R.drawable.app13,R.drawable.app14,R.drawable.app11};
image_tips = new int[]{R.drawable.page, R.drawable.pagenow};
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inPreferredConfig = Bitmap.Config.RGB_565;
opts.inPurgeable = true;
opts.inInputShareable = true;
bmp = new Bitmap[images.length];
for (int i = 0; i < images.length;i++){
InputStream is = this.getResources().openRawResource(images[i]);
bmp[i] = BitmapFactory.decodeStream(is,null,opts);//将普通图片转换成位图
}
//小原点图片
bmp_tips = new Bitmap[image_tips.length];
for (int i = 0 ; i < image_tips.length;i++){
InputStream is = this.getResources().openRawResource(image_tips[i]);
bmp_tips[i] = BitmapFactory.decodeStream(is,null,opts);//将普通图片转换成位图
}
//初始化 提示点点
tips = new ImageView[5];
for (int i = 0 ; i< images.length;i++){
ImageView img = new ImageView(getActivity());
img.setLayoutParams(new LinearLayout.LayoutParams(20,20));
tips[i] = img;
if (i == 0){
img.setImageBitmap(bmp_tips[1]);
}else {
img.setImageBitmap(bmp_tips[0]);
}
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
new ViewGroup.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
params.leftMargin = 20;
params.rightMargin =20;
tipsBox.addView(img,params);
}
//初始化PagerAdapter
PagerAdapter adapter = new PagerAdapter() {
@Override
public int getCount() {
return images.length;
}
@Override
public boolean isViewFromObject(@NonNull View arg0, @NonNull Object arg1) {
return arg0 == arg1;
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
ImageView im = new ImageView(getActivity());
im.setScaleType(ImageView.ScaleType.CENTER);
im.setImageBitmap(zoomImg(bmp[position],680,420));
container.addView(im);
return im;
}
};
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
Log.e("rf",String.valueOf(position));
tips[currentPage].setImageBitmap(bmp_tips[0]);
currentPage = position;
tips[currentPage].setImageBitmap(bmp_tips[1]);
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
private Bitmap zoomImg(Bitmap bm,int newWidth,int newHeight) {
//获得图片的宽高
int width = bm.getWidth();
int height = bm.getHeight();
//计算缩放比例
float scaleWidth = ((float) newWidth)/width;
float scaleHeight = ((float) newHeight)/height;
//取得想要缩放的matrix参数
Matrix martix = new Matrix();
martix.postScale(scaleWidth,scaleHeight);
//取得新的图片,www.2cto.com
Bitmap newbm = Bitmap.createBitmap(bm,0,0,width,height,martix,true);
return newbm;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup p = (ViewGroup) mMainView.getParent();
if (p!=null) {
p.removeAllViewsInLayout();
}
return mMainView;
}
}
NewsFramgment4
package com.e.myapplicationtest.fragment;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
//import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import com.e.myapplicationtest.R;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import java.io.InputStream;
/**
* A simple {@link Fragment} subclass.
* Use the {@link NewsFramgment4#?newInstance} factory method to
* create an instance of this fragment.
*/
public class NewsFramgment4 extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
ListView listView = null;
private View mMainView;
//显示新闻大图片代码
private ViewPager viewPager;
private ImageView[] tips;//提示性点点数组
private int[] images;//图片ID数组
private int[] image_tips;
private int currentPage = 0 ;
public Bitmap[] bmp = null;
public Bitmap[] bmp_tips = null;
public NewsFramgment4() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
// * @param param1 Parameter 1.
// * @param param2 Parameter 2.
* @return A new instance of fragment NewsFramgment1.
*/
// TODO: Rename and change types and number of parameters
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater inflater = getActivity().getLayoutInflater();
mMainView = inflater.inflate(R.layout.fragment_news_framgment4,(ViewGroup) getActivity().findViewById(R.id.viewpager),false);
showBigImages();
// listView = (ListView) mMainView.findViewById(R.id.listview);
}
private void showBigImages() {
viewPager =(ViewPager) mMainView.findViewById(R.id.viewpager4);
//存放点点的容器
LinearLayout tipsBox = (LinearLayout) mMainView.findViewById(R.id.tipsBox);
//初始化图片资源
images = new int[]{R.drawable.app10,R.drawable.app11,R.drawable.app12,R.drawable.app13,R.drawable.app14};
image_tips = new int[]{R.drawable.page, R.drawable.pagenow};
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inPreferredConfig = Bitmap.Config.RGB_565;
opts.inPurgeable = true;
opts.inInputShareable = true;
bmp = new Bitmap[images.length];
for (int i = 0; i < images.length;i++){
InputStream is = this.getResources().openRawResource(images[i]);
bmp[i] = BitmapFactory.decodeStream(is,null,opts);//将普通图片转换成位图
}
//小原点图片
bmp_tips = new Bitmap[images.length];
for (int i = 0 ; i < image_tips.length;i++){
InputStream is = this.getResources().openRawResource(images[i]);
bmp_tips[i] = BitmapFactory.decodeStream(is,null,opts);//将普通图片转换成位图
}
//初始化 提示点点
tips = new ImageView[7];
for (int i = 0 ; i< images.length;i++){
ImageView img = new ImageView(getActivity());
img.setLayoutParams(new LinearLayout.LayoutParams(20,20));
tips[i] = img;
if (i == 0){
img.setImageBitmap(bmp_tips[1]);
}else {
img.setImageBitmap(bmp_tips[0]);
}
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
new ViewGroup.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
params.leftMargin = 20;
params.rightMargin =20;
tipsBox.addView(img,params);
}
//初始化PagerAdapter
PagerAdapter adapter = new PagerAdapter() {
@Override
public int getCount() {
return images.length;
}
@Override
public boolean isViewFromObject(@NonNull View arg0, @NonNull Object arg1) {
return arg0 == arg1;
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
ImageView im = new ImageView(getActivity());
im.setScaleType(ImageView.ScaleType.CENTER);
im.setImageBitmap(zoomImg(bmp[position],680,420));
container.addView(im);
return im;
}
};
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
Log.e("rf",String.valueOf(position));
tips[currentPage].setImageBitmap(bmp_tips[0]);
currentPage = position;
tips[currentPage].setImageBitmap(bmp_tips[1]);
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
private Bitmap zoomImg(Bitmap bm,int newWidth,int newHeight) {
//获得图片的宽高
int width = bm.getWidth();
int height = bm.getHeight();
//计算缩放比例
float scaleWidth = ((float) newWidth)/width;
float scaleHeight = ((float) newHeight)/height;
//取得想要缩放的matrix参数
Matrix martix = new Matrix();
martix.postScale(scaleWidth,scaleHeight);
//取得新的图片,www.2cto.com
Bitmap newbm = Bitmap.createBitmap(bm,0,0,width,height,martix,true);
return newbm;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup p = (ViewGroup) mMainView.getParent();
if (p!=null) {
p.removeAllViewsInLayout();
}
return mMainView;
}
}
JsonParse
package com.e.myapplicationtest.tool;
import com.e.myapplicationtest.bean.NewsBean;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;
public class JsonParse {
public static List getNewsInfo(String json){
//使用gson库解析json数据
Gson gson = new Gson();
//创建一个TypeToken的匿名子类对象,并调用对象的getType()方法
Type listType = new TypeToken>(){}.getType();
//把获取到的信息集合存到newsInfos中
List newsInfos = gson.fromJson(json,listType);
return newsInfos;
}
}
NewsListAdapter
package com.e.myapplicationtest.tool;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import com.e.myapplicationtest.R;
import com.e.myapplicationtest.bean.NewsBean;
import com.google.android.material.transition.Hold;
import com.loopj.android.image.SmartImageView;
import org.w3c.dom.Text;
import java.util.List;
import java.util.logging.Handler;
public class NewsListAdapter extends ArrayAdapter {
private ListView listView;
private LayoutInflater inflater;
private Context context;
Holder holder = null;
// String imgUrl ="";//存储图片的地址
public NewsListAdapter(Activity activity, List newsBeans,ListView listView) {
super(activity,0,newsBeans);
this.listView = listView;
//得到一个渲染对象
inflater = activity.getLayoutInflater();
this.context = activity;
holder = new Holder();
}
public View getView(int position, View convertView, ViewGroup parent){
if (convertView == null){
convertView = inflater.inflate(R.layout.news,null);
holder.img = (SmartImageView)convertView.findViewById(R.id.img);
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.author = (TextView) convertView.findViewById(R.id.author);
holder.time = (TextView)convertView.findViewById(R.id.time);
convertView.setTag(holder);
}else {
holder = (Holder) convertView.getTag();
}
//获取item对应第几条(positon)的Model实体
NewsBean newsBean = getItem(position);
String imageUrl = "http://(ip地址):8080/Web1/TestServlet/img/"+newsBean.getImg_name();
System.out.println("imageUrl"+imageUrl);
holder.img.setTag(imageUrl);
holder.img.setImageUrl(imageUrl,R.drawable.icon);
holder.title.setText(newsBean.getTitle());
holder.author.setText(newsBean.getAuthor());
holder.time.setText(newsBean.getTime());
Log.i("text","position = "+position);
return convertView;
}
static class Holder{
SmartImageView img;
TextView title;
TextView author;
TextView time;
}
}
bootstrap框架,以放在下面
具体的代码
DelNewsServlet
package com.user.action;
import com.user.dao.NewsDao;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/delNews")
public class DelNewsServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
private NewsDao newsDao = new NewsDao();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json;charset=gbk");
String id = request.getParameter("id");
int delNums = newsDao.delNewById(id);
//1表示成功 0表示失败
response.getWriter().write(delNums>0?"1":"0");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
ListNewsServlet
package com.user.action;
import com.user.bean.NewsBean;
import com.user.dao.NewsDao;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/listNews")
public class ListNewsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private NewsDao newsDao = new NewsDao();
private List list = new ArrayList();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("gbk");
list = newsDao.findAllNews();
request.setAttribute("newsList",list);
request.getRequestDispatcher("news.jsp").forward(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
LoginServlet
package com.user.action;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/login.htm")
public class LoginServlet extends HttpServlet {
private String name = "wzg",pwd = "123";
protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
//接受页面参数
String userName = request.getParameter("userName");
String userPwd = request.getParameter("userPwd");
System.out.println(userName+""+userPwd);
if (name.equals(userName)&&pwd.equals(userPwd)){
request.getRequestDispatcher("news_add.jsp").forward(request,response);
}else {
request.getRequestDispatcher("login.jsp").forward(request,response);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
NewsServlet
package com.user.action;
import com.user.bean.NewsBean;
import com.user.dao.NewsDao;
import com.user.util.JsonUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.util.List;
@WebServlet("/NewsSL")
public class NewsServlet extends HttpServlet {
private NewsDao newsDao = new NewsDao();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=gbk");
PrintWriter out = response.getWriter();
String typeId = request.getParameter("typeId");//以typeId为查询条件
ResultSet rs = null;
List ls = newsDao.findNewsByType(typeId);
System.out.println("ls=="+ls);
String news = JsonUtil.list2json(ls);
System.out.println("news=="+news);
out.println(news);
out.flush();
out.close();
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=gbk");
PrintWriter out = response.getWriter();
out.flush();
out.close();
}
}
SaveNewsServlet
package com.user.action;
import com.user.bean.NewsBean;
import com.user.dao.NewsDao;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;
import java.io.IOException;
import java.io.*;
// 使用注解@MultipartConfig将一个Servlet标识为支持文件上传
@MultipartConfig
@WebServlet("/saveNews")
public class SaveNewsServlet extends HttpServlet {
//private static final long serialVersionUID = 1L;
private NewsDao dao = new NewsDao();
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("gbk");
response.setContentType("text/html;charset=gbk");
// 获取页面上的值
String newsTitle = request.getParameter("newsTitle");
String newsAuth = request.getParameter("newsAuth");
String newsContent = request.getParameter("newsContent");
// 获取新闻类别
String typeId = request.getParameter("type");
// 获取新闻发布时间
String newsTime = request.getParameter("newsTime");
// 获取上传文件
Part part = request.getPart("newsFile");
// 获取文件名称
String header = part.getHeader("content-disposition");
// getFileName(header);自定义方法获取带后缀的文件名
String fileName = getFileName(header);
//文件名称
String newFileName =System.currentTimeMillis()+fileName.substring(fileName.lastIndexOf("."));
//图片上传路径
String rootPath = request.getServletContext().getRealPath("\\img");
//rootPath+="/images/";
// log(newsTitle+","+newsAuth);
//输出图片完整路径
part.write(rootPath+"\\"+newFileName);
System.out.println("图片路径:"+rootPath+"\\"+newFileName);;
// 写入文件D:\Student\Web1\web\img
// File file=new File("D:\\Workspaces\\MyEclipse Professional 2014\\NewsServer\\WebRoot\\img\\"+newFileName);
File file=new File("D:\\Student\\Web1\\web\\img\\"+newFileName);
System.out.println("新图片地址是:"+file.getAbsolutePath());
DataInputStream dis=null;
DataOutputStream dos=null;
FileInputStream fis=null;
FileOutputStream fos=null;
//创建输入流对象
fis=new FileInputStream(rootPath+"\\"+newFileName);
dis=new DataInputStream(fis);
//创建输出流对象
fos=new FileOutputStream(file.getAbsolutePath());
dos=new DataOutputStream(fos);
//读取文件并写入文件
int temp;
while((temp=dis.read())!=-1){
dos.write(temp);
}
if(dis!=null){
dis.close();
}
if(dos!=null){
dos.close();
}
if(fis!=null){
fis.close();
}
if(fos!=null){
fos.close();
}
NewsBean news = new NewsBean();
news.setAuthor(newsAuth);
news.setContent(newsContent);
news.setImg_name(newFileName);
news.setBig_img_name("null");
news.setImg_url("img\\");
news.setTitle(newsTitle);
news.setTime(newsTime);
news.setType_id(Integer.parseInt(typeId));
news.setStatus(1);
// 保存数据库
dao.saveNews(news);
response.sendRedirect("listNews");
}
/**
* 根据请求头解析出文件名
* @param header 请求头
* @return 文件名
*/
public String getFileName(String header) {
//将文件头按照“;“分割成字符串,再按照”=“号分割成字符串
String[] tempArr1 = header.split(";");
String[] tempArr2 = tempArr1[2].split("=");
// 获取文件名,兼容各种浏览器的写法
String fileName = tempArr2[1].substring(tempArr2[1].lastIndexOf("\\") + 1).replaceAll("\"", "");
return fileName;
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
ShowNewsServlet
package com.user.action;
import com.user.dao.NewsDao;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@MultipartConfig
public class ShowNewsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private NewsDao dao = new NewsDao();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("gbk");
response.setContentType("text/html;charset=gbk");
//获取页面上的值
String id = request.getParameter("id");
request.setAttribute("news",dao.findNewsById(id));
request.getRequestDispatcher("news_update.jsp?id="+id).forward(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
ShowUpdateNewsServlet
package com.user.action;
import com.user.dao.NewsDao;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@MultipartConfig
@WebServlet("/toUpdateNewsPage")
public class ShowUpdateNewsServlet extends HttpServlet {
private static final long serialVersionUID =1L;
private NewsDao dao = new NewsDao();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("gbk");
response.setContentType("text/html;charset=gbk");
//获取页面上的值
String id = request.getParameter("id");
request.setAttribute("news",dao.findNewsById(id));
request.getRequestDispatcher("news_update.jsp?id="+id).forward(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
UpdateNewsServlet
package com.user.action;
import com.user.bean.NewsBean;
import com.user.dao.NewsDao;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;
import java.io.IOException;
@MultipartConfig
@WebServlet("/updateNews")
public class UpdateNewsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private NewsDao dao = new NewsDao();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("gbk");
response.setContentType("text/html;charset=gbk");
String newsStatus =request.getParameter("newsStatus");
String id = request.getParameter("id");
//获取页面上的值
String newsTitle = request.getParameter("newsTitle");
String newsAuth = request.getParameter("newsAuth");
String newsContent = request.getParameter("newsContent");
//获取行文类别
String type = request.getParameter("newsType");
//获取上传文件
Part part = request.getPart("newsFile");
//获取文件名称
String header = part.getHeader("content-disposition");
//获取文件名
String fileName = getFileName(header);
String newFileName ="";
if (!"".equals(fileName)){
newFileName = System.currentTimeMillis()+fileName.substring(fileName.lastIndexOf("."));
String rootPath = request.getServletContext().getRealPath("/img/");
//rootPath+="images";
part.write(rootPath+newFileName);
}else {
newFileName = request.getParameter("newsHiddenFile");
}
NewsBean news = new NewsBean();
news.setAuthor(newsAuth);
news.setContent(newsContent);
// if(newFileName.contains("/img/")){
// news.setImg_url(newFileName);
// }else {
// news.setImg_url("/img/"+newFileName);
// }
news.setImg_url(newFileName);
news.setTitle(newsTitle);
news.setImg_name(newFileName);
news.setType_id(Integer.parseInt(type));
news.setStatus(1);
// news.setStatus(Integer.valueOf(newsStatus));
news.setId(Integer.valueOf(id));
//保存数据
dao.updateNews(news);
//跳转回列表页面
response.sendRedirect("listNews");
}
private String getFileName(String header) {
String[] tempArr1 = header.split(";");
String[] tempArr2 = tempArr1[2].split("=");
if ("".equals(tempArr2[1])){
return "";
}
String fileName = tempArr2[1].substring(tempArr2[1].lastIndexOf("\\")+1).replaceAll("\"","");
return fileName;
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
JsonBean
package com.user.bean;
public class JsonBean {
/**
* 状态码
*
* 0请求失败
* 1请求成功
*/
private String code;
/**
* 服务器返回的真实数据
*/
private Object result;
/**
* 消息
*/
private String message;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Object getResult() {
return result;
}
public void setResult(Object result) {
this.result = result;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
NewsBean
package com.user.bean;
public class NewsBean {
public int id;
public String title;
public String content;
public String img_url;
public String img_name;
public String big_img_name;
public String author;
public String time;
public int type_id;
private int status;
public NewsBean(){
}
public NewsBean(int id, String title, String content, String img_url, String img_name, String big_img_name, String author, String time, int type_id, int status) {
this.id = id;
this.title = title;
this.content = content;
this.img_url = img_url;
this.img_name = img_name;
this.big_img_name = big_img_name;
this.author = author;
this.time = time;
this.type_id = type_id;
this.status = status;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getImg_url() {
return img_url;
}
public void setImg_url(String img_url) {
this.img_url = img_url;
}
public String getImg_name() {
return img_name;
}
public void setImg_name(String img_name) {
this.img_name = img_name;
}
public String getBig_img_name() {
return big_img_name;
}
public void setBig_img_name(String big_img_name) {
this.big_img_name = big_img_name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public int getType_id() {
return type_id;
}
public void setType_id(int type_id) {
this.type_id = type_id;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
BaseDao
package com.user.dao;
import java.sql.*;
public class BaseDao {
/**
* 连接
*/
protected Connection connection;
/**
* 桥梁
*/
protected PreparedStatement preparedStatement;
//连接地址 &useUnicode=true&characterEncoding=UTR-8
private String url = "jdbc:mysql://localhost:3306/news?useSSL=false&useUnicode=true&characterEncoding=UTF-8";
//账号
private String name="root";
//密码
private String pwd = "123456";
/**
* 结果集
*/
protected ResultSet resultSet;
//获取连接
protected Connection initConnection(){
// 加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");//有问题
connection = DriverManager.getConnection(url, name, pwd);
}catch (ClassNotFoundException e){
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
public void delObject(String table,int id){
connection = initConnection();
String sql = "delete from"+table+"where id ="+id;
try {
preparedStatement = connection.prepareStatement(sql);
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 关闭数据库信息
* @param resultSet
* @param statement
// * @param connection
*/
protected void closeDBInfo(ResultSet resultSet,Statement statement,Connection connection){
/**
* Connection:获得数据库连接是操作数据库的第一步,是应用程序和数据库的一次“握手”过程。数据库打开的连接数是有限的,所以连接使用完成后需要关闭。
* Statement:Statement用于执行静态 SQL 语句并返回它所生成结果的对象
* ResultSet:1.Result表示数据库结果集的数据表,通常通过执行查询数据库的语句生成。
* 2.ResultSet 对象具有指向其当前数据行的光标。最初,光标被置于第一行之前。next 方法将光标移动到下一行;因为该方法在 ResultSet 对象没有下一行时返回 false,所以可以在 while 循环中使用它来迭代结果集。
* 3.ResultSet 接口提供用于从当前行获取列值的获取 方法(getBoolean、getLong 等)。可以使用列的索引编号或列的名称获取值。一般情况下,使用列索引较为高效。列从 1 开始编号。为了获得最大的可移植性,应该按从左到右的顺序读取每行中的结果集列,每列只能读取一次。
*
*/
try {
if (resultSet !=null){
resultSet.close();
}if (statement !=null){
statement.close();
}if (connection !=null){
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
NewsDao
package com.user.dao;
import com.user.bean.NewsBean;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class NewsDao extends BaseDao {
/**
* 保存,增加新闻信息到列表
*/
public void saveNews(NewsBean news){
connection = initConnection();
//news表格
String sql = "insert into news(title,content,img_url,img_name,big_img_name,author,time ,type_id,status) value (?,?,?,?,?,?,?,?,?)";
try {
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,news.getTitle());
preparedStatement.setString(2,news.getContent());
preparedStatement.setString(3,news.getImg_url());
preparedStatement.setString(4,news.getImg_name());
preparedStatement.setString(5,news.getBig_img_name());
preparedStatement.setString(6,news.getAuthor());
preparedStatement.setString(7,news.getTime());
preparedStatement.setInt(8,news.getType_id());
preparedStatement.setInt(9,news.getStatus());
preparedStatement.executeUpdate();
// preparedStatement.execute();
} catch (SQLException e) {
e.printStackTrace();
}finally {
closeDBInfo(resultSet,preparedStatement,connection);
}
}
/**
* 保存
* @param news
*/
public void updateNews(NewsBean news){
connection = initConnection();
String sql = "update news set title =?,img_url=?,img_name=?,author=?,content=?,type_id=?,status=? where id=?";
try {
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,news.getTitle());
preparedStatement.setString(2,news.getImg_url());
preparedStatement.setString(3,news.getImg_name());
preparedStatement.setString(4,news.getAuthor());
preparedStatement.setString(5,news.getContent());
preparedStatement.setInt(6,news.getType_id());
preparedStatement.setInt(7,news.getStatus());
preparedStatement.setInt(8,news.getId());
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
closeDBInfo(resultSet,preparedStatement,connection);
}
}
/**
* 返回新闻
*/
public NewsBean findNewsById(String id){
connection = initConnection();
//status为1表示该条记录没有使用
String sql = "select * from news where id = ?";
NewsBean news = new NewsBean();
try {
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,Integer.valueOf(id));
resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
news.setId(resultSet.getInt("id"));
news.setTitle(resultSet.getString("title"));
news.setImg_url(resultSet.getString("img_url"));
news.setImg_name(resultSet.getString("img_name"));
news.setContent(resultSet.getString("content"));
news.setAuthor(resultSet.getString("author"));
news.setTime(resultSet.getString("time"));
news.setType_id(resultSet.getInt("type_id"));
news.setStatus(resultSet.getInt("status"));
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
closeDBInfo(resultSet,preparedStatement,connection);
}
return news;
}
/**
* 返回所有的新闻
*/
public ListfindAllNews(){
List ls = new ArrayList<>();
connection = initConnection();
//status为1表示该条记录还没有使用
String sql = "select * from news;";
try {
preparedStatement = connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
NewsBean newsBean = new NewsBean();
newsBean.setId(resultSet.getInt("id"));
newsBean.setTitle(resultSet.getString("title"));
newsBean.setImg_url(resultSet.getString("img_url"));
newsBean.setImg_name(resultSet.getString("img_name"));
newsBean.setContent(resultSet.getString("content"));
newsBean.setAuthor(resultSet.getString("author"));
newsBean.setTime(resultSet.getString("time"));
newsBean.setType_id(resultSet.getInt("type_id"));
newsBean.setStatus(resultSet.getInt("status"));
ls.add(newsBean);
}
for (Object obj:ls){
NewsBean nBean = (NewsBean) obj;
System.out.println(nBean.getAuthor()+"|"+nBean.getTime());
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
closeDBInfo(resultSet,preparedStatement,connection);
}
return ls;
}
/**
* 删除新闻
*/
public int delNewById(String id){
connection = initConnection();
String sql = "delete from news where id = "+id;
try {
preparedStatement = connection.prepareStatement(sql);
return preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
return 0;
}
}
public ListfindNewsByType(String typeId){
List ls = new ArrayList<>();
connection = initConnection();
//status为1表示该条记录没有使用
String sql = "select * from news where type_id=? and status=1";
try {
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,typeId);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
NewsBean newsBean = new NewsBean();
newsBean.setId(resultSet.getInt("id"));
newsBean.setTitle(resultSet.getString("title"));
newsBean.setImg_url(resultSet.getString("img_url"));
newsBean.setImg_name(resultSet.getString("img_name"));
newsBean.setContent(resultSet.getString("content"));
newsBean.setAuthor(resultSet.getString("author"));
newsBean.setTime(resultSet.getString("time"));
newsBean.setType_id(resultSet.getInt("type_id"));
ls.add(newsBean);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
closeDBInfo(resultSet,preparedStatement,connection);
}
return ls;
}
}
JsonUtil
package com.user.util;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class JsonUtil {
public static String object2json(Object obj) {
StringBuilder json = new StringBuilder();
if (obj == null) {
json.append("\"\"");
} else if (obj instanceof String || obj instanceof Integer
|| obj instanceof Float || obj instanceof Boolean
|| obj instanceof Short || obj instanceof Double
|| obj instanceof Long || obj instanceof BigDecimal
|| obj instanceof BigInteger || obj instanceof Byte) {
json.append("\"").append(string2json(obj.toString())).append("\"");
} else if (obj instanceof Object[]) {
json.append(array2json((Object[]) obj));
} else if (obj instanceof List) {
json.append(list2json((List>) obj));
} else if (obj instanceof Map) {
json.append(map2json((Map, ?>) obj));
} else if (obj instanceof Set) {
json.append(set2json((Set>) obj));
} else {
json.append(bean2json(obj));
}
return json.toString();
}
public static String bean2json(Object bean) {
StringBuilder json = new StringBuilder();
json.append("{");
PropertyDescriptor[] props = null;
try {
props = Introspector.getBeanInfo(bean.getClass(), Object.class)
.getPropertyDescriptors();
} catch (IntrospectionException e) {
}
if (props != null) {
for (int i = 0; i < props.length; i++) {
try {
String name = object2json(props[i].getName());
String value = object2json(props[i].getReadMethod().invoke(
bean));
json.append(name);
json.append(":");
json.append(value);
json.append(",");
} catch (Exception e) {
}
}
json.setCharAt(json.length() - 1, '}');
} else {
json.append("}");
}
return json.toString();
}
public static String list2json(List> list) {
StringBuilder json = new StringBuilder();
// json.append("{");
// json.append("\"list\":");
json.append("[");
if (list != null && list.size() > 0) {
for (Object obj : list) {
json.append(object2json(obj));
json.append(",");
}
json.setCharAt(json.length() - 1, ']');
// json.append("}");
} else {
json.append("]}");
}
return json.toString();
}
public static String array2json(Object[] array) {
StringBuilder json = new StringBuilder();
json.append("[");
if (array != null && array.length > 0) {
for (Object obj : array) {
json.append(object2json(obj));
json.append(",");
}
json.setCharAt(json.length() - 1, ']');
} else {
json.append("]");
}
return json.toString();
}
public static String map2json(Map, ?> map) {
StringBuilder json = new StringBuilder();
json.append("{");
if (map != null && map.size() > 0) {
for (Object key : map.keySet()) {
json.append(object2json(key));
json.append(":");
json.append(object2json(map.get(key)));
json.append(",");
}
json.setCharAt(json.length() - 1, '}');
} else {
json.append("}");
}
return json.toString();
}
public static String set2json(Set> set) {
StringBuilder json = new StringBuilder();
json.append("[");
if (set != null && set.size() > 0) {
for (Object obj : set) {
json.append(object2json(obj));
json.append(",");
}
json.setCharAt(json.length() - 1, ']');
} else {
json.append("]");
}
return json.toString();
}
public static String string2json(String s) {
if (s == null)
return "";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
switch (ch) {
case '"':
sb.append("\\\"");
break;
case '\\':
sb.append("\\\\");
break;
case '\b':
sb.append("\\b");
break;
case '\f':
sb.append("\\f");
break;
case '\n':
sb.append("\\n");
break;
case '\r':
sb.append("\\r");
break;
case '\t':
sb.append("\\t");
break;
case '/':
sb.append("\\/");
break;
default:
if (ch >= '\u0000' && ch <= '\u001F') {
String ss = Integer.toHexString(ch);
sb.append("\\u");
for (int k = 0; k < 4 - ss.length(); k++) {
sb.append('0');
}
sb.append(ss.toUpperCase());
} else {
sb.append(ch);
}
}
}
return sb.toString();
}
}
<%--
Created by IntelliJ IDEA.
User: 吴治国
Date: 2022/5/24
Time: 21:10
To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
登录
<%@ page language="java" import="com.user.bean.NewsBean"
contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"
isELIgnored="false"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
新闻列表
电影列表
标题
作者
内容
操作
${item.title}
${item.author}
${item.content}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false"%>
添加新闻
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
修改新闻
出现错误
Tue May 31 17:03:37 CST 2022 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
错误的解决方法:解决方法
注意web里面的映射,如果映射不对要自己写。(我自己就是个例子,不知道是没搞懂idea还是配置错了,反正我映射是自己写的。/(ㄒoㄒ)/~~)
错误问题:javax.servlet.jsp.tagext.TagLibraryValidator
原因:应为我用的是tomcat10所以要。
官方解释是:由于Tomcat10使用的是JakartaEE9的标准,Servlet的标准包不再由Apache支持维护,转交给Jakarta管理,对应的最新JSTL只能在Jakarta.ee官网下载
所以需要下载jakarta.servlet.jsp.jstl-api-2.0.0.jar与jakarta.servlet.jsp.jstl-2.0.0.jar下载地址是:本人已下载课使用百度网盘下载jar包https://pan.baidu.com/s/1p5TQj2fqp9K3JjiUFpKeHA#list/path=%2F 提取码:wzg1
出现错误(没办法正常导入)
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
解决方式
自己传输数据错误(内容,作者,标题,还有,时间,传输都有问题,不过在我给出的代码中已经解决了,不要慌 (*^_^*) )
提取码:wzg1
遇到错误先看自己能解决不,如果自己不能解决就查吧。
实在找不到解决就重启电脑把。
应为我的在idea软件中我的Java代码改过所以要打完才能运行,如果只运行web就不行。
IP地址使用自己的
http://(ip地址):8080/Web1/TestServlet/NewsSL?typeId=1