今天帶大家做一個百思不得姐,糗百類型的服務(wù)器項目,市面上我們能看到的項目很多都是需要編輯去提交一些數(shù)據(jù)到服務(wù)器,比如,我看到兩個搞笑的段子,現(xiàn)在把內(nèi)容整理好了。要提交到服務(wù)器,用戶刷新就能看到了。
任然使用Eclipse來創(chuàng)建一個服務(wù)器,創(chuàng)建一個servlet
String title = request.getParameter("title");
String desc = request.getParameter("desc");
String pic = request.getParameter("pic");
System.out.println("title : " + title);
System.out.println("desc : " + desc);
System.out.println("pic : " + pic);
Part part = request.getPart("pic");
如上代碼,就是服務(wù)器端的代碼,獲取信息并打印,現(xiàn)在我們再去寫用于上傳的表單,在WebContent目錄下新建一個html文件,取名為upload.html這個可以,然后在<body></body> 標簽中加入下面代碼,這段代碼主要是定義了一個格式
<form action="/upload/uploadservlet" method="post" enctype="multipart/form-data">
標題: <input type="text" name="title"><br/>
描述: <input type="text" name="desc"><br/>
圖片: <input type="file" name="pic"><br/>
<input type="submit" value="提交">
</form>
這段代碼簡單解釋下,因為我們要上傳,所以要使用post請求方式, 然后我們要添加圖片,所以圖片這里的type 值是“file” 還有就是我們<form > 標簽中,加入了enctype="multipart/form-data" 這個的意思是用來解碼的,一會表單的數(shù)據(jù)會使用mime 協(xié)議進行描述,其中/upload/uploadservlet 前面是表單的名字,后面就是我們要新建的servlet 的名字。運行這個表單文件,然后在里面輸入內(nèi)容,然后再看下我們的打印內(nèi)容,你會看到都是沒有傳遞過來,因為忽略了一個注解。@MultipartConfig,加上后,前面兩個都有內(nèi)容,但是第三個圖片我們傳遞的是null 因為我么針對這個東西的獲取方式要更改一下:
Part part = request.getPart("pic");
String value = UUID.randomUUID().toString();
File file = new File("d:\\pics\\"+value+".jpg");
part.write(file.getAbsolutePath());
這里我想要把提交的圖片放在我的d 盤下,而調(diào)用了一個UUID的一個隨機生成的方法去命名,這樣的好處是不會重復,這個時候,我們?nèi)盤看。圖片就過來了;
然后還要考慮到輸出給瀏覽器的亂碼問題,加上如下代碼:
// 解決 輸出 給瀏覽器時 中文的 亂碼
response.setContentType("text/html;charset=utf-8");
response.getWriter().println("上傳成功");
現(xiàn)在我們想一下,我們數(shù)據(jù)存放在哪里呢。肯定是存在數(shù)據(jù)庫中,這里防暑jdbc的jar文件放到web-info下的llib中,然后在剛才代碼為之一加入下面代碼:
try {
// jdbc的代碼, 大家 了解一下就好了
Class.forName("org.sqlite.JDBC");
// http://www.itheima.com
Connection conn = DriverManager.getConnection("jdbc:sqlite:d:\\test.db");
// org.sqlite.SQLiteConnection@7f1bfcfc
System.out.println(conn);
Statement stmt = conn.createStatement();
//創(chuàng)建表
// create table 表名 (列名 列的類型 額外的信息 , 列名 列的類型 , 列名 列的類型 ...);
// 操作的時候, 第一次把這個 打開, 創(chuàng)建表, 然后 就可以 注釋掉了
// stmt.execute("create table news (id integer primary key autoincrement, title varchar(20), desc varchar(200),"
// + "picpath varchar(200))");
//
// ? 占位符替換 ...
//加數(shù)據(jù) 插入到 表中
stmt.execute("insert into news (id,title,desc,picpath) values(null,'"+title+"','"+desc+"','"+picpath+"')");
} catch (Exception e) {
e.printStackTrace();
return;
}
我們還要增加查詢所有內(nèi)容的servlet
新建一個javaBean來接受數(shù)據(jù):
public class NewsBean {
private int id;
private String title;
private String desc;
private String picpath;
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 getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getPicpath() {
return picpath;
}
public void setPicpath(String picpath) {
this.picpath = picpath;
}
public NewsBean(int id, String title, String desc, String picpath) {
super();
this.id = id;
this.title = title;
this.desc = desc;
this.picpath = picpath;
}
public NewsBean() {
super();
}
}
然后寫我們的服務(wù)器:
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.itheima.web.domain.NewsBean;
/**
* Servlet implementation class GetAllNewsServlet
*
* 處理 來自 手機客戶端的請求, 返回 新聞的信息
*
*/
@WebServlet("/getall")
public class GetAllNewsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public GetAllNewsServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List<NewsBean> list = new ArrayList<NewsBean>();
// 查詢 數(shù)據(jù)庫, 把 所有的信息查詢了之后返回...
// jdbc的代碼
// jdbc的代碼, 大家 了解一下就好了
try {
Class.forName("org.sqlite.JDBC");
// http://www.itheima.com
Connection conn = DriverManager.getConnection("jdbc:sqlite:d:\\test.db");
// org.sqlite.SQLiteConnection@7f1bfcfc
System.out.println(conn);
Statement stmt = conn.createStatement();
//查詢 所有的
// select * from news;
// select id, title, desc, picpath from news
String sql ="select id, title, desc, picpath from news";
// Cursor
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
int id = rs.getInt("id");
String title = rs.getString("title");
String desc = rs.getString("desc");
String picpath = rs.getString("picpath");
//封裝到 一個 javabean 中 , 針對 新聞的信息要去寫一個 java類
NewsBean bean = new NewsBean(id, title, desc, picpath);
list.add(bean);
}
//釋放資源
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
return;
}
//將list 的數(shù)據(jù)寫 給 客戶端
// list--- 要轉(zhuǎn)換成 json 的數(shù)據(jù)會好一些, 因為json格式的數(shù)據(jù), 非常的小巧
Gson gson = new Gson();
String json = gson.toJson(list);
System.out.println(json);
// response.setCharacterEncoding();
// response.setCharacterEncoding("application/json;charset=utf-8");
// response.setCharacterEncoding("charset=utf-8");
response.setContentType("application/json;charset=utf-8");
// 可以進到 tomcat 服務(wù)器的 conf目錄下的 web.xml文件中去
response.getWriter().println(json);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
服務(wù)器端代碼基本完成了,現(xiàn)在要寫客戶端的代碼
客戶端我們就用一個ListView 來展示數(shù)據(jù)就可以了:
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import org.apache.http.Header;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.itheima.newsclient.domain.NewsBean;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.image.SmartImageView;
public class MainActivity extends Activity {
private ListView mLv_news_list;
/**
* 用來封裝 所有的 要顯示的新聞信息的 list
*
*/
private List<NewsBean> mList;
/**
* 顯示新聞信息的 適配器
*
*/
private NewsAdapter mNewAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 一個布局文件 能夠顯示到界面上, 首先是要通過 一個布局填充器的 對象, 將布局文件轉(zhuǎn)換成 view對象,
setContentView(R.layout.activity_main);
initView();
initData();
}
//加載初始化的數(shù)據(jù) , 實際上是 來自于 訪問了服務(wù)器的數(shù)據(jù)
private void initData() {
// 1. new Thread , URL -- urlConnection
// 2. 開源的框架 -- AsyncHttpClient
AsyncHttpClient client = new AsyncHttpClient();
// http://188.188.7.100:8080/web_server/getall
//添加聯(lián)網(wǎng)權(quán)限
String path = getResources().getString(R.string.path);
client.get(path, new AsyncHttpResponseHandler() {
//當成功的時候會回調(diào)
@Override
public void onSuccess(int statusCode, Header[] header, byte[] responseBody) {
// responseBody就是 響應(yīng)體的內(nèi)容
String json = new String(responseBody);
//這個是一個 json格式的數(shù)據(jù)
// 將 json格式的 數(shù)據(jù)轉(zhuǎn)換成 list 集合的數(shù)據(jù)
Gson gson = new Gson();
mList = gson.fromJson(json, new TypeToken<List<NewsBean>>(){}.getType());
//list拿到后, 就可以讓 數(shù)據(jù)顯示在lv 中了
mNewAdapter = new NewsAdapter();
mLv_news_list.setAdapter(mNewAdapter);
}
//當 失敗 的時候會回調(diào)
@Override
public void onFailure(int statusCode, Header[] header, byte[] responseBody, Throwable error) {
error.printStackTrace();
}
});
}
private class NewsAdapter extends BaseAdapter{
@Override
public int getCount() {
return mList.size();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v =null;
if(convertView==null){
// 直接new
//布局通常都是 先將 布局文件寫好,然后 通過代碼來將 一個布局文件 轉(zhuǎn)換成 一個 可以顯示到屏幕上的view 對象
// 這個事兒以后 大家經(jīng)常會做...
// LayoutInflater lf = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
// lf.inflate(R.layout.item, null);
v = View.inflate(MainActivity.this, R.layout.item, null);
}else{
v= convertView;
}
NewsBean newsBean = mList.get(position);
SmartImageView iv_pic = (SmartImageView) v.findViewById(R.id.iv_pic);
TextView tv_title = (TextView) v.findViewById(R.id.tv_title);
TextView tv_desc = (TextView) v.findViewById(R.id.tv_desc);
tv_title.setText(newsBean.getTitle());
tv_desc.setText(newsBean.getDesc());
//圖片顯示 ---??
// 1. 先去寫一個服務(wù)器的代碼, 能夠 返回那個 圖片對應(yīng)的 流
// 2. 反問服務(wù)器的程序, 拿到 返回的對應(yīng)的圖片的流,然后把流 轉(zhuǎn)換成 可以顯示圖片,放到 控件上去
// http://188.188.7.100:8080/web_server/displaypic?picpath=d:\pics\4db8b928944649038c96c58d56052eab.jpg
System.out.println(newsBean.getPicpath());
// 由于 要顯示一個圖片的事兒 要經(jīng)常做, 所以 就 有人 寫好了專門用來顯示圖片的框架.
// 去github找
String path;
try {
// 這里對 參數(shù) 也要進行url 編碼
path = "http://188.188.7.100:8080/web_server/displaypic?picpath="
+URLEncoder.encode(newsBean.getPicpath(), "UTF-8");
iv_pic.setImageUrl(path);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return v;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
}
private void initView() {
mLv_news_list = (ListView) findViewById(R.id.lv_news_list);
}
}