目录
Android:可以使用Android Stuodio编辑
-
准备工作
-
idea工具(专业版)
-
IntelliJ IDEA创建Servlet最新方法
-
mysql:个人使用的MySQL5.7
-
mysql:可以使用SQLyou
-
Android:可以使用Android Stuodio
-
-
Android中代码
- 框架:
- 需要的jar包放在下main
- 具体代码.
-
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<String> titlelist = new ArrayList<String>(); 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<Fragment> fragmntList = new ArrayList<Fragment>(); 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<String> titlelist; private ArrayList<Fragment> fragmentList; public MyPagerAdapter(FragmentManager fm, List<String> titlelist, ArrayList<Fragment> 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<NewsBean> newsLists = new ArrayList<NewsBean>(); 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<NewsBean> newsLists = new ArrayList<NewsBean>(); 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<NewsBean> newsLists = new ArrayList<NewsBean>(); 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<NewsBean> getNewsInfo(String json){ //使用gson库解析json数据 Gson gson = new Gson(); //创建一个TypeToken的匿名子类对象,并调用对象的getType()方法 Type listType = new TypeToken<List<NewsBean>>(){}.getType(); //把获取到的信息集合存到newsInfos中 List<NewsBean> 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<NewsBean> { private ListView listView; private LayoutInflater inflater; private Context context; Holder holder = null; // String imgUrl ="";//存储图片的地址 public NewsListAdapter(Activity activity, List<NewsBean> 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; } }
- activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".activity.MainActivity" android:orientation="vertical"> <com.google.android.material.tabs.TabLayout android:id="@+id/tab_layout" android:layout_width="match_parent" android:layout_height="60dp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:tabGravity="fill" app:tabMaxWidth="0dp" app:tabMode="fixed" app:tabSelectedTextColor="@color/my_red" app:tabTextColor="@color/black" /> <androidx.viewpager.widget.ViewPager android:id="@+id/viewpager" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
- activity_show_news.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".activity.ShowNewsActivity"> <RelativeLayout android:id="@+id/relativeLayout1" android:layout_width="fill_parent" android:layout_height="wrap_content" > <ImageView android:id="@+id/imageView1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/bg_title_bar" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="电影介绍" android:textColor="#ffffff" android:textSize="20sp" /> <ImageView android:id="@+id/imageView2" android:layout_width="30dp" android:layout_height="30dp" android:layout_centerVertical="true" android:layout_alignParentRight="true" android:layout_marginRight="18dp" android:background="@drawable/ic_top_bar_category" /> </RelativeLayout> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@+id/relativeLayout1" android:orientation="vertical" > <View android:layout_width="fill_parent" android:layout_height="1dip" android:background="@drawable/ic_shelf_category_divider" /> <TextView android:id="@+id/title" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginLeft="5dip" android:layout_marginRight="5dip" android:layout_marginTop="10dip" android:textSize="20sp" android:text="title" android:textStyle="bold" /> <RelativeLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp"> <TextView android:id="@+id/author" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="5dp" android:text="环球网" /> <TextView android:id="@+id/time" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="5dip" android:layout_toRightOf="@+id/author" android:text="2016-12-11 15:58" /> </RelativeLayout> <View android:layout_width="fill_parent" android:layout_height="2dip" android:layout_marginTop="8dp" android:background="@drawable/ic_shelf_category_divider" /> <com.loopj.android.image.SmartImageView android:id="@+id/img_name" android:layout_width="300dp" android:layout_height="150dp" android:layout_gravity="center" android:layout_marginTop="10dp" android:src="@drawable/newspic1" /> <ScrollView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="5dp" android:layout_marginTop="16dp" android:padding="8dp"> <TextView android:id="@+id/content" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="content" android:textSize="16sp" /> </ScrollView> </LinearLayout> </RelativeLayout>
- fragment_news_framgment1.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".fragment.NewsFramgment1" android:orientation="vertical"> <!-- TODO: Update blank fragment layout --> <FrameLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <androidx.viewpager.widget.ViewPager android:id="@+id/viewpager1" android:layout_width="fill_parent" android:layout_height="400px" android:paddingLeft="5dp" android:paddingRight="5dp"> </androidx.viewpager.widget.ViewPager> <!-- 测换显示焦点图片底部的提示点--> <RelativeLayout android:id="@+id/tips" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="170dp"> <LinearLayout android:id="@+id/tipsBox" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:orientation="horizontal"> </LinearLayout> </RelativeLayout> </FrameLayout> <View android:layout_width="fill_parent" android:layout_height="2dp" android:background="@color/my_gray" /> <ListView android:id="@+id/listview" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout>
- fragment_news_framgment2.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".fragment.NewsFramgment2" android:orientation="vertical"> <!-- TODO: Update blank fragment layout --> <FrameLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <androidx.viewpager.widget.ViewPager android:id="@+id/viewpager2" android:layout_width="fill_parent" android:layout_height="400px" android:paddingLeft="5dp" android:paddingRight="5dp"> </androidx.viewpager.widget.ViewPager> <!-- 测换显示焦点图片底部的提示点--> <RelativeLayout android:id="@+id/tips" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="170dp"> <LinearLayout android:id="@+id/tipsBox" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:orientation="horizontal"> </LinearLayout> </RelativeLayout> </FrameLayout> <View android:layout_width="fill_parent" android:layout_height="2dp" android:background="@color/my_gray" /> <ListView android:id="@+id/listview" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout>
- fragment_news_framgment3.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".fragment.NewsFramgment3" android:orientation="vertical"> <!-- TODO: Update blank fragment layout --> <FrameLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <androidx.viewpager.widget.ViewPager android:id="@+id/viewpager3" android:layout_width="fill_parent" android:layout_height="400px" android:paddingLeft="5dp" android:paddingRight="5dp"> </androidx.viewpager.widget.ViewPager> <!-- 测换显示焦点图片底部的提示点--> <RelativeLayout android:id="@+id/tips" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="170dp"> <LinearLayout android:id="@+id/tipsBox" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:orientation="horizontal"> </LinearLayout> </RelativeLayout> </FrameLayout> <View android:layout_width="fill_parent" android:layout_height="2dp" android:background="@color/my_gray" /> <ListView android:id="@+id/listview" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout>
- fragment_news_framgment4.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".fragment.NewsFramgment4" android:orientation="vertical"> <!-- TODO: Update blank fragment layout --> <FrameLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <androidx.viewpager.widget.ViewPager android:id="@+id/viewpager4" android:layout_width="fill_parent" android:layout_height="300px" android:paddingLeft="5dp" android:paddingRight="5dp" android:layout_marginBottom="40dp"> </androidx.viewpager.widget.ViewPager> <!-- 测换显示焦点图片底部的提示点--> <RelativeLayout android:id="@+id/tips" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="400dp"> <LinearLayout android:id="@+id/tipsBox" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:orientation="horizontal"> </LinearLayout> </RelativeLayout> </FrameLayout> <View android:layout_width="fill_parent" android:layout_height="2dp" android:background="@color/my_gray" /> <ListView android:id="@+id/listview" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout>
- news.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/title" android:layout_width="300dp" android:layout_height="40dp" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" android:layout_marginBottom="16dp" android:text="topic1" android:textSize="18sp" android:textStyle="bold" /> <com.loopj.android.image.SmartImageView android:id="@+id/img" android:layout_width="80dp" android:layout_height="40dp" android:layout_alignParentRight="true" android:layout_margin="16dp" android:src="@drawable/beijing" /> <TextView android:id="@+id/author" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/title" android:layout_alignLeft="@+id/title" android:layout_marginTop="2dp" android:text="凤凰新闻客户端" android:textSize="12sp"/> <TextView android:id="@+id/time" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/author" android:layout_alignParentRight="true" android:layout_marginTop="2dp" android:text="2022年5月20日" android:textColor="#ff8247" android:textSize="12sp"/> </RelativeLayout>
-
- 框架:
-
IDEA中代码
-
框架:
-
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<NewsBean> list = new ArrayList<NewsBean>(); @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<NewsBean> 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 { /** * 状态码 * <p> * 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 List<NewsBean>findAllNews(){ List<NewsBean> 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 List<NewsBean>findNewsByType(String typeId){ List<NewsBean> 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(); } }
- login.jsp
<%-- 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"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>登录</title> <style type="text/css"> .show_div { /* border: 1px red solid; */ width: 95%; height: 300px; margin: 30px; /*background: url("img/bg_title_bar.png") -750px 0;*/ background: url("img/login.jpg") 100% ; padding-top: 200px; } .show_div_filed { width: 320px; height: 50px; margin: auto; } .show_div_filed span{ color: black; font-family: "黑体"; } </style> </head> <body> <div class="show_div"> <form action="login.htm" method="post"> <div class="show_div_filed"> <span>账号:</span> <input type="text" name="userName"> </div> <div class="show_div_filed"> <span>密码:</span> <input type="password" name="userPwd"> </div> <div class="show_div_filed"> <input type="submit" value="登录"> </div> </form> </div> </body> </html>
- news.jsp
<%@ 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+"/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <title>新闻列表</title> <!-- Bootstrap core CSS --> <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <!-- IE10 viewport hack for Surface/desktop Windows 8 bug --> <link href="../../assets/css/ie10-viewport-bug-workaround.css" rel="stylesheet"> <!-- Custom styles for this template --> <link href="dashboard.css" rel="stylesheet"> <!-- Just for debugging purposes. Don't actually copy these 2 lines! --> <!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]--> <script src="../../assets/js/ie-emulation-modes-warning.js"></script> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="https://cdn.bootcss.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script> <![endif]--> <style> .table{ table-layout:fixed; word-break:keep-all; } </style> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> //删除新闻 function delNews(id) { var isDel = confirm("确认要删除该记录吗?"); if(!isDel){ return; } $.post("delNews?id="+id,function(data){ if ("1" == data) { alert("删除成功"); window.location.reload(true); } else { alert("删除失败"); } },"json"); } //跳转到修改页面 function toUpdatePage(id){ window.location.href = "toUpdateNewsPage?id="+id; } </script> </head> <body> <div class="container"> <div class="row"> <h2 class="sub-header">电影列表</h2> <div class="table-responsive"> <table class="table table-striped table-hover table-bordered"> <thead> <tr> <th>标题</th> <th>作者</th> <th>内容</th> <th>操作</th> </tr> </thead> <tbody> <c:forEach items="${newsList}" var="item"> <tr> <td style="width:20%">${item.title}</td> <td style="width:10%">${item.author}</td> <td style="width:50%">${item.content}</td> <td style="width:20%"> <button type="button" class="btn btn-danger btn-small" onclick='delNews(${item.id})'>删除</button> <button type="button" class="btn btn-primary btn-small" onclick="toUpdatePage(${item.id})">修改</button> </td> </tr> </c:forEach> </tbody> </table> </div> </div> </div> </div> </body> </html>
- new_add.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>添加新闻</title> <!-- 最新版本的 Bootstrap 核心 CSS 文件 --> <link rel="stylesheet" href="bootstrap/css/bootstrap.css" /> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript" src="bootstrap/js/bootstrap.js"></script> <style type="text/css"> .container { padding-right: 15px; padding-left: 15px; margin-right: auto; margin-left: auto; } @media ( min-width : 768px) { .container { width: 750px; } } @media ( min-width : 992px) { .container { width: 970px; } } @media ( min-width : 1200px) { .container { width: 1170px; } } .container-fluid { padding-right: 15px; padding-left: 15px; margin-right: auto; margin-left: auto; } .show_img{ width: 100px; height: 100px; display: none; } </style> <script type="text/javascript"> // 获取选中图片 $(function() { /*原理是把本地图片路径:"D(盘符):/image/..."转为"http://..."格式路径来进行显示图片*/ $("#fileupload").change(function() { var $file = $(this); //$file[0]是将file这个jquery对象转为HTML节点元素,$file[0].files[0]就是$file[0]节点的File对象 var objUrl = $file[0].files[0]; //获得一个http格式的url路径:mozilla(firefox)||webkit or chrome var windowURL = window.URL || window.webkitURL; //createObjectURL创建一个指向该参数对象(图片)的URL var dataURL; //dataURL即使用对应浏览器处理之后的url路径 dataURL = windowURL.createObjectURL(objUrl); $("#imageview").attr("src",dataURL); $("#imageview").show(); }); }); </script> </head> <body> <div class="container"> <form class="form-horizonta" action="saveNews" method="post" enctype="multipart/form-data"> <p id="a1" class="text-center lead">创建电影名</p> <div class="form-group"> <label for="InputTitle" class="control-label">电影名:</label> <input type="text" name="newsTitle" class="form-control" id="InputTittle" placeholder="标题"/> </div> <div class="form-group"> <label for="fileupload" class="control-label">电影图片:</label> <input type="file" name="newsFile" id="fileupload"/> <img id="imageview" class="show_img" src=""/> </div> <div class="form-group"> <label for="InputAuthor" class="control-label">电影作者:</label> <input type="text" class="form-control" name="newsAuth" id="InputAuthor" placeholder="作者"/> </div> <div class="form-group"> <label for="InputContent" class="control-label">电影内容:</label> <textarea class="form-control" name="newsContent" id="InputContent" placeholder="新闻内容" rows="" cols=""></textarea> </div> <div class="form-group"> <label for="InputTime" class="control-label">发布时间:</label> <input type="text" class="form-control" name="newsTime" id="eInputTime" placeholder="时间"/> </div> <div class="form-group"> <label for="InputType" class="control-label">电影类型:</label> <select class="form-control" name="type" id="InputType" style="width: 120px"> <option value="-1">-请选择-</option> <option value="1">爱情</option> <option value="2">励志</option> <option value="3">喜剧</option> </select> </div> <button type="submit" class="btn btn-success">添加</button> </form> </div> </body> </html>
- news_update.jsp
<%@ 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" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>修改新闻</title> <!-- 最新版本的 Bootstrap 核心 CSS 文件 --> <link rel="stylesheet" href="bootstrap/css/bootstrap.css" /> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript" src="bootstrap/js/bootstrap.js"></script> <style type="text/css"> .container { padding-right: 15px; padding-left: 15px; margin-right: auto; margin-left: auto; } @media ( min-width : 768px) { .container { width: 750px; } } @media ( min-width : 992px) { .container { width: 970px; } } @media ( min-width : 1200px) { .container { width: 1170px; } } .container-fluid { padding-right: 15px; padding-left: 15px; margin-right: auto; margin-left: auto; } .show_img{ width: 100px; height: 100px; } </style> <script type="text/javascript"> // 頁面載入完畢 $(function() { /*原理是把本地图片路径:"D(盘符):/image/..."转为"http://..."格式路径来进行显示图片*/ //alert("${news}"); $("#fileupload").change(function() { var $file = $(this); var objUrl = $file[0].files[0]; //获得一个http格式的url路径:mozilla(firefox)||webkit or chrome var windowURL = window.URL || window.webkitURL; //createObjectURL创建一个指向该参数对象(图片)的URL var dataURL; dataURL = windowURL.createObjectURL(objUrl); $("#imageview").attr("src",dataURL); $("#imageview").show(); }); }); </script> </head> <body> <div class="container"> <form class="form-horizonta" action="updateNews" method="post" enctype="multipart/form-data"> <p id="a1" class="text-center lead">修改电影名</p> <input name="id" type="hidden" value="${news.id}" /> <input name="newsStatus" type="hidden" value="${news.status}" /> <input name="newsType" type="hidden" value="${news.type_id}" /> <input name="newsHiddenFile" type="hidden" value="${news.img_url}" /> <div class="form-group"> <label for="exampleInputEmail1" class="control-label">电影名:</label> <input type="text" name="newsTitle" class="form-control" id="exampleInputEmail1" placeholder="标题" value="${news.title}"> </div> <div class="form-group"> <label for="exampleInputFile" class="control-label">电影图片:</label> <input type="file" name="newsFile" id="fileupload"> <img id="imageview" class="show_img" src="${news.img_url}"> </div> <div class="form-group"> <label for="exampleInputPassword1" class="control-label">电影作者:</label> <input type="text" class="form-control" name="newsAuth" id="exampleInputPassword1" placeholder="作者" value="${news.author}"> </div> <div class="form-group"> <label for="exampleInputPassword2" class="control-label">电影内容:</label> <textarea class="form-control" name="newsContent" id="exampleInputPassword2" placeholder="新闻内容" rows="" cols="">${news.content}</textarea> </div> <div class="form-group"> <label for="exampleInputPassword1" class="control-label">发布时间:</label> <input type="text" class="form-control" name="newsTime" id="exampleInputPassword1" placeholder="时间" value="${news.time}"> </div> <button type="submit" class="btn btn-success">编辑</button> </form> </div> </body> </html>
-
-
-
个人错误
-
Java代码错误
- 关于servlet映射解决问题:解决方式
- 关于配错setvlet(The selected directory is not a TomEE home):解决方式
- 这些都是正常的,不要怕
-
出现错误
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" %>
-
自己传输数据错误(内容,作者,标题,还有,时间,传输都有问题,不过在我给出的代码中已经解决了,不要慌 (*^_^*) )
-
-
部分需要jar包和框架
- 所有需要的加载地址:百度网盘
-
提取码:wzg1
-
显示代码:
-
Android:页面显示
-
idea的java:页面显示
-
-
-
-
-
总结
-
遇到错误先看自己能解决不,如果自己不能解决就查吧。
-
实在找不到解决就重启电脑把。
-
应为我的在idea软件中我的Java代码改过所以要打完才能运行,如果只运行web就不行。
-
IP地址使用自己的
http://(ip地址):8080/Web1/TestServlet/NewsSL?typeId=1
-