- 設計my_tab_content.xml即“我的”Tab對應的頁面
- 採用相對佈局RelativeLayout,頂部是LinearLayout用於放頭像和用戶信息或者登陸、註冊按鈕
- 主要內容部分是ScrollView,放“我的”頁面的主要功能,在這裏我暫時分爲兩個區分別是“關於設置”和“關於我的”,在設置下有賬號管理、更新簽名、修改密碼三項;我的下面有趣事分享、日記分享、我的收藏和關於I分享這四個模塊,後期的功能也可以在這裏補充
- 設置頭部除了頭像剩餘的LinearLayout都爲隱藏狀態(如左下圖),在tab事件發生時根據登陸狀態做相應的隱藏和顯示(如右下圖)
——my_tab_content.xml頁面代碼初步如下
<?xml version="1.0" encoding="UTF-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/empty_cart_view" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ffefebe7" > <LinearLayout android:background="@color/white" android:id="@+id/top_relative" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <ImageView android:id="@+id/images_head" android:layout_width="80dp" android:layout_height="80dp" android:layout_marginBottom="10dp" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_marginTop="10dp" android:scaleType="fitCenter" android:src="@drawable/tab_icon_one"/> <LinearLayout android:id="@+id/login_top" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:orientation="vertical" android:weightSum="1" android:visibility="gone"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="20dp" android:layout_weight="0.3" android:orientation="horizontal"> <TextView android:id="@+id/textView8" android:layout_width="70dp" android:layout_height="wrap_content" android:text="暱稱:" android:textSize="18sp"/> <TextView android:id="@+id/t_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:text="丫an梅" android:textSize="18sp" android:textStyle="bold"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="0.3" android:orientation="horizontal"> <TextView android:id="@+id/textView9" android:layout_width="70dp" android:layout_height="wrap_content" android:text="心情:" android:textSize="18sp"/> <TextView android:id="@+id/t_number" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="0.44" android:text="人生的意義在於嘗試和守護" android:textSize="18sp" android:textStyle="bold"/> </LinearLayout> </LinearLayout> <LinearLayout android:id="@+id/un_login_top" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:orientation="vertical" android:weightSum="1" android:visibility="gone"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:layout_weight="0.3" android:orientation="horizontal"> <Button android:id="@+id/pop_login" android:layout_width="70dp" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:background="@drawable/button_radius" android:text="登錄" android:gravity="center" /> <Button android:id="@+id/pop_register" android:layout_width="70dp" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:background="@drawable/button_radius" android:text="註冊" android:gravity="center" /> </LinearLayout> </LinearLayout> </LinearLayout> <ScrollView android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@+id/top_relative" android:fadingEdge="none" > <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_vertical" android:orientation="vertical" android:paddingBottom="60.0dip" android:paddingTop="10.0dip" android:layout_marginTop="10dp"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginBottom="10.0dip" android:layout_marginTop="10.0dip" android:gravity="center_vertical" android:paddingLeft="10.0dip" android:text="相關設置" android:textColor="#ff888888" android:textSize="16.0sp" /> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" > <TableLayout android:id="@+id/MorePageTableLayout_Follow" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingLeft="1.0dip" android:shrinkColumns="0" android:stretchColumns="0" > <TableRow android:id="@+id/more_page_row1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginLeft="2.0dip" android:layout_marginRight="2.0dip" android:background="@drawable/small_bc" android:paddingBottom="16.0dip" android:paddingTop="16.0dip" > <TextView android:id="@+id/test_text_view" android:layout_width="wrap_content" android:layout_height="fill_parent" android:drawableLeft="@drawable/my_tab_list1" android:drawablePadding="10.0dip" android:gravity="center_vertical" android:includeFontPadding="false" android:paddingLeft="24.0dip" android:text="賬號管理" android:textColor="#ff333333" android:textSize="16.0sp" /> <ImageView android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_gravity="right" android:gravity="center_vertical" android:paddingRight="20.0dip" android:src="@drawable/next_right" /> </TableRow> <TableRow android:id="@+id/more_page_row2" android:layout_width="fill_parent" android:layout_marginLeft="2.0dip" android:layout_marginRight="2.0dip" android:background="@drawable/small_bc" android:paddingBottom="16.0dip" android:paddingTop="16.0dip" > <TextView android:layout_width="wrap_content" android:layout_height="fill_parent" android:drawableLeft="@drawable/my_tab_list2" android:drawablePadding="10.0dip" android:gravity="center_vertical" android:includeFontPadding="false" android:paddingLeft="24.0dip" android:text="更新心情" android:textColor="#ff333333" android:textSize="16.0sp" /> <ImageView android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_gravity="right" android:gravity="center_vertical" android:paddingRight="20.0dip" android:src="@drawable/next_right" /> </TableRow> <TableRow android:id="@+id/more_page_row3" android:layout_width="fill_parent" android:layout_marginLeft="2.0dip" android:layout_marginRight="2.0dip" android:background="@drawable/small_bc" android:paddingBottom="16.0dip" android:paddingTop="16.0dip" > <TextView android:layout_width="wrap_content" android:layout_height="fill_parent" android:drawableLeft="@drawable/my_tab_list3" android:drawablePadding="10.0dip" android:gravity="center_vertical" android:includeFontPadding="false" android:paddingLeft="24.0dip" android:text="修改密碼" android:textColor="#ff333333" android:textSize="16.0sp" /> <ImageView android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_gravity="right" android:gravity="center_vertical" android:paddingRight="20.0dip" android:src="@drawable/next_right" /> </TableRow> </TableLayout> </LinearLayout> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginBottom="10.0dip" android:layout_marginTop="10.0dip" android:gravity="center_vertical" android:paddingLeft="10.0dip" android:text="關於我的" android:textColor="#ff888888" android:textSize="16.0sp" /> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" > <TableLayout android:id="@+id/MorePageTableLayout_Client" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingLeft="1.0dip" android:shrinkColumns="0" android:stretchColumns="0" > <TableRow android:id="@+id/more_page_row4" android:layout_width="fill_parent" android:layout_marginLeft="2.0dip" android:layout_marginRight="2.0dip" android:background="@drawable/small_bc" android:paddingBottom="16.0dip" android:paddingTop="16.0dip" > <TextView android:layout_width="wrap_content" android:layout_height="fill_parent" android:drawableLeft="@drawable/my_tab_list4" android:drawablePadding="10.0dip" android:gravity="center_vertical" android:includeFontPadding="false" android:paddingLeft="24.0dip" android:text="趣事分享" android:textColor="#ff333333" android:textSize="16.0sp" /> <ImageView android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_gravity="right" android:gravity="center_vertical" android:paddingRight="20.0dip" android:src="@drawable/next_right" /> </TableRow> <TableRow android:id="@+id/more_page_row5" android:layout_width="fill_parent" android:layout_marginLeft="2.0dip" android:layout_marginRight="2.0dip" android:background="@drawable/small_bc" android:paddingBottom="16.0dip" android:paddingTop="16.0dip" > <TextView android:layout_width="wrap_content" android:layout_height="fill_parent" android:drawableLeft="@drawable/my_tab_list5" android:drawablePadding="10.0dip" android:gravity="center_vertical" android:includeFontPadding="false" android:paddingLeft="24.0dip" android:text="日記分享" android:textColor="#ff333333" android:textSize="16.0sp" /> <ImageView android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_gravity="right" android:gravity="center_vertical" android:paddingRight="20.0dip" android:src="@drawable/next_right" /> </TableRow> <TableRow android:id="@+id/more_page_row6" android:layout_width="fill_parent" android:layout_marginLeft="2.0dip" android:layout_marginRight="2.0dip" android:background="@drawable/small_bc" android:paddingBottom="16.0dip" android:paddingTop="16.0dip" > <TextView android:layout_width="wrap_content" android:layout_height="fill_parent" android:drawableLeft="@drawable/my_tab_list6" android:drawablePadding="10.0dip" android:gravity="center_vertical" android:includeFontPadding="false" android:paddingLeft="24.0dip" android:text="我的收藏" android:textColor="#ff333333" android:textSize="16.0sp" /> <ImageView android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_gravity="right" android:gravity="center_vertical" android:paddingRight="20.0dip" android:src="@drawable/next_right" /> </TableRow> <TableRow android:id="@+id/more_page_row7" android:layout_width="fill_parent" android:layout_marginLeft="2.0dip" android:layout_marginRight="2.0dip" android:background="@drawable/small_bc" android:paddingBottom="16.0dip" android:paddingTop="16.0dip" > <TextView android:layout_width="wrap_content" android:layout_height="fill_parent" android:drawableLeft="@drawable/my_tab_list7" android:drawablePadding="10.0dip" android:gravity="center_vertical" android:includeFontPadding="false" android:paddingLeft="24.0dip" android:text="關於 i 分享" android:textColor="#ff333333" android:textSize="16.0sp" /> <ImageView android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_gravity="right" android:gravity="center_vertical" android:paddingRight="20.0dip" android:src="@drawable/next_right" /> </TableRow> </TableLayout> </LinearLayout> </LinearLayout> </ScrollView> </RelativeLayout>
- 創建註冊界面activity_register.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="com.example.discover.RegisterActivity" android:background="#eeeeee" > <RelativeLayout android:id="@+id/rl_top" android:layout_width="match_parent" android:layout_height="70dp" android:background="@color/color_minefragment_top" > <TextView android:id="@+id/tv_register" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAlignment="center" android:text="用戶註冊" android:textColor="#fff" android:textSize="20dp" android:layout_centerVertical="true" android:layout_marginLeft="20dp" /> </RelativeLayout> <LinearLayout android:id="@+id/ll_body" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:layout_below="@+id/rl_top" android:layout_marginTop="60dp" android:layout_marginLeft="50dp" android:layout_marginRight="50dp" > <!-- 第一個文本編輯框 輸入用戶名 --> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:id="@+id/tv_username" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="用戶名:"/> <EditText android:id="@+id/et_username" android:layout_width="match_parent" android:layout_height="50dp" android:hint="請輸入用戶名" android:gravity="center_vertical" android:layout_marginLeft="10dp" /> </LinearLayout> <!-- 第二個文本編輯框 輸入密碼 --> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:id="@+id/tv_password1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="密 碼:"/> <EditText android:id="@+id/et_password1" android:layout_width="match_parent" android:layout_height="50dp" android:gravity="center_vertical" android:layout_marginLeft="10dp" android:inputType="textPassword" android:hint="請輸入密碼" /> </LinearLayout> <!-- 第三個文本編輯框 再次輸入密碼 --> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:id="@+id/tv_password2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="密 碼:"/> <EditText android:id="@+id/et_password2" android:layout_width="match_parent" android:layout_height="50dp" android:hint="請再次輸入密碼" android:gravity="center_vertical" android:layout_marginLeft="10dp" android:inputType="textPassword" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:id="@+id/tv_signature" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="籤 名:"/> <EditText android:id="@+id/et_signature" android:layout_width="match_parent" android:layout_height="50dp" android:hint="輸入你的個性簽名" android:gravity="center_vertical" android:layout_marginLeft="10dp" android:inputType="textPassword" /> </LinearLayout> <!-- 註冊按鈕 --> <!-- <Button android:id="@+id/bt_register" android:layout_width="match_parent" android:layout_height="50dp" android:layout_marginLeft="80dp" android:layout_marginRight="80dp" android:background="@drawable/selector_loginactivity_button" android:textColor="#fff" android:text="註冊" android:layout_marginTop="40dp" />--> <RelativeLayout android:layout_width="match_parent" android:layout_height="50dp" android:id="@+id/rl_bottom" android:layout_marginTop="20dp" android:layout_marginBottom="30dp" > <TextView android:id="@+id/test1_view_info" android:layout_centerInParent="true" android:text="註冊即代表同意《用戶協議》" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </RelativeLayout> </LinearLayout> </RelativeLayout>
- 創建登錄頁面activity_login.xml
<?xml version="1.0" encoding="utf-8"?> <!-- 這裏把整個Activity_login的佈局設置成相對佈局, 因爲相對佈局比較靈活 --> <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" android:background="#eeeeee"> <!-- 整體是相對佈局, --> <RelativeLayout android:id="@+id/rl_login_top" android:layout_width="match_parent" android:layout_height="70dp" android:background="@color/color_minefragment_top" > <TextView android:id="@+id/tv_login" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAlignment="center" android:text="用戶登錄" android:textColor="#fff" android:textSize="20dp" android:layout_centerVertical="true" android:layout_marginLeft="20dp" /> </RelativeLayout> <!-- LinerLayout必須指明orientation 方向 要麼垂直vertical 要麼水平 horizontal 這裏顯然是垂直vertical --> <LinearLayout android:id="@+id/ll_login_two" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:layout_below="@+id/rl_login_top" android:layout_marginTop="120dp" android:layout_marginLeft="50dp" android:layout_marginRight="50dp" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:id="@+id/tv_login_username" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="用戶名:"/> <EditText android:id="@+id/et_login_username" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="手機號/郵箱/用戶名"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:id="@+id/tv_login_password" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="密 碼:"/> <EditText android:id="@+id/et_login_password" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="登錄密碼" android:inputType="textPassword"/> </LinearLayout> </LinearLayout> <!--<Button android:id="@+id/bt_login" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/ll_login_two" android:layout_marginTop="20dp" android:layout_marginLeft="100dp" android:layout_marginRight="100dp" android:background="@drawable/selector_loginactivity_button" android:text="登錄" android:textColor="#fff" android:gravity="center" android:onClick="onClick" />--> <TextView android:id="@+id/tv_login_forget" android:text="忘記密碼?" android:textColor="#f00" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginVertical="50dp" android:layout_below="@+id/ll_login_two" android:layout_alignLeft="@+id/ll_login_two" /> <TextView android:id="@+id/tv_logina_check" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="還沒有註冊?" android:textColor="#f00" android:layout_marginRight="10dp" android:layout_marginVertical="50dp" android:layout_below="@+id/ll_login_two" android:layout_alignRight="@+id/ll_login_two" /> <TextView android:id="@+id/test2_view_info" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/tv_login_forget" android:layout_centerInParent="true" android:layout_marginVertical="30dp" android:text="測試信息反饋" android:textColor="#B3B3B3" android:gravity="center" /> </RelativeLayout>
- 處理登錄、註冊相關邏輯——MyTabFragment.java
- 定義方法changStatus()對登錄狀態顯示不同的UI ,用SharePreferences記錄用戶的登錄狀態,如果已經登錄則顯示用戶頭像和相關信息,否則顯示註冊登錄按鈕
//根據狀態顯示或隱藏“我的”頁面中頭部信息 public void changeStatus(){ //獲取最新的登錄狀態,SharePreferences爲永久存儲,需要手動退出 SharedPreferences sp = mActivity.getSharedPreferences("save", Context.MODE_PRIVATE); isLogin = sp.getBoolean("isLogin",false); if(isLogin){ Bitmap one; userName = sp.getString("name",""); signature = sp.getString("sign",""); headImg = sp.getString("headImg",""); //設置用戶暱稱、頭像、心情 my_name.setText(userName); my_sign.setText(userName); //通過網絡鏈接獲取圖片 try { one= LoadImgByNet.getBitmap(imgBaseUrl+"my_tab_list1.png"); my_head_img.setImageBitmap(one); }catch(IOException e){ e.printStackTrace(); } //已經登錄時設置用戶相關信息爲顯示狀態 //username = this.getActivity().getSharedPreferences("config", Context.MODE_PRIVATE).getString("fname", ""); login_top.setVisibility(View.VISIBLE); un_login_top.setVisibility(View.GONE); }else{ //尚未登錄,設置登錄、註冊按鈕爲顯示狀態 un_login_top.setVisibility(View.VISIBLE); login_top.setVisibility(View.GONE); } }
2.在myeclipse中創建項目iShareService爲android應用搭建web後臺服務
- 創建org.utils包,在包下面創建class文件JdbcUtils.java,在文件中做數據庫連接處理
package org.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;public class JdbcUtils {
private static String url ="jdbc:mysql://127.0.0.1/ishare?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true";
private static String username="root";
private static String password="";
private static String driverName="com.mysql.jdbc.Driver";
// static靜態代碼塊裏面代碼,會在類加載到內存的時候立刻執行
static {
//1.註冊驅動
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 獲取連接
* @return
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
//2.獲取連接
Connection connection = DriverManager.getConnection(url, username, password);
return connection;
}
public static void close(Connection connection,PreparedStatement prepareStatement,ResultSet resultSet) {
//5.釋放資源 connection prepareStatement resultSet
if(resultSet!=null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(prepareStatement!=null) {
try {
prepareStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection!=null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void statementClose(Connection connection,Statement statement,ResultSet resultSet) {
//5.釋放資源 connection prepareStatement resultSet
if(resultSet!=null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement!=null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection!=null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
- Navicat連接我的mySql數據庫,創建數據庫ishare,在數據庫中創建user表,表的設計如下
- 創建myServlet.data包,在包下面創建Servlet用於接收用戶註冊請求——Register.java,第一步做數據測試,不封裝返回的用戶信息
package myServlet.data;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.utils.JdbcUtils;
public class Register extends HttpServlet{/**
* 註冊
*/
private static final long serialVersionUID = 1L;
//處理中文字符串
public String handleString(String s) {
try {
byte bb[]=s.getBytes("ISO8859-1");
s=new String(bb,"UTF-8");
}catch(Exception e){}
return s;
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String username = handleString(request.getParameter("username"));
String password = handleString(request.getParameter("password"));
String signature = handleString(request.getParameter("signature"));
String userlogimage = "userImg.png"; /* 默認頭像*/
out.print(username+"--"+password+"--"+signature);
Connection connection = null;
PreparedStatement prepareStatement = null;
try {
connection = JdbcUtils.getConnection();
//3.獲取statement
//String sql ="insert into user(name,phone,password,gender,province,city,create_time,update_time) value(?,?,?,?,?,?,?,?) ";
String sql ="INSERT INTO user VALUES(?,?,?,?)";
prepareStatement = connection.prepareStatement(sql);
prepareStatement.setString(1, username);
prepareStatement.setString(2, password);
prepareStatement.setString(3, signature);
prepareStatement.setString(4, userlogimage);
//4.執行sql
prepareStatement.execute();
out.print("register succeeded!");
} catch (Exception e) {
e.printStackTrace();
out.print("該用戶名已被使用,請更換名字!"+e);
}finally {
//5.釋放資源 connection prepareStatement
JdbcUtils.close(connection, prepareStatement, null);
}
out.flush();
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
- 在myServlet.data下創建Servlet處理登錄請求——Login.java ,第一步做數據測試,不封裝返回的用戶信息
package myServlet.data;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.utils.JdbcUtils;/**
* Servlet implementation class Login
*/
@WebServlet("/Login")
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
super.init(config);
}
//處理中文字符串
public String handleString(String s) {
try {
byte bb[]=s.getBytes("ISO8859-1");
s=new String(bb,"UTF-8");
}catch(Exception e){}
return s;
}/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String username = request.getParameter("username").trim();
String password = request.getParameter("password").trim();
String signature = "在這裏寫下你的心情吧!";
username = handleString(username);
password = handleString(password);
if(username == null) {
username = "";
}
if(password == null) {
password = "";
}
Connection connection = null;
PreparedStatement prepareStatement = null;
ResultSet rs = null;
String backnews="";
boolean boo = false;
boo = username.length()>0&&password.length()>0;
try {
connection = JdbcUtils.getConnection();
//3.獲取statement
//String sql ="insert into user(logname,password,phone,address,realname) value(?,?,?,?,?) ";
String sql ="select * from user where username=? and password=?";
prepareStatement = connection.prepareStatement(sql);
prepareStatement.setString(1, username);
prepareStatement.setString(2, password);
if(boo) {
//4.執行sql
boolean m =false;
rs = prepareStatement.executeQuery();
while(rs.next()) {
signature = rs.getString(4);
m = true;
}
if(m==true) {
//登錄成功
success(request,response,username,signature,backnews);
/*RequestDispatcher dispatcher = request.getRequestDispatcher("/pages/login.jsp");
dispatcher.forward(request, response);*/
}else {
backnews="你輸入的用戶名或密碼有誤!";
fail(request,response,username,backnews);
}
}else {
backnews="請輸入用戶名和密碼";
fail(request,response,username,backnews);
}
} catch (Exception e) {
backnews=""+e.toString();
e.printStackTrace();
fail(request,response,username,backnews);
}finally {
//5.釋放資源 connection prepareStatement
JdbcUtils.close(connection, prepareStatement, rs);
}
out.flush();
out.close();
}/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
public void success(HttpServletRequest request, HttpServletResponse response,String logname,String signature,String backnews) {
try {
PrintWriter out = response.getWriter();
out.print("Login succeeded!");
out.print(backnews);
out.print(logname);
out.print(signature);
}catch(IOException e) {
e.printStackTrace();
}
}
public void fail(HttpServletRequest request, HttpServletResponse response,String logname,String backnews) {
response.setContentType("text/html;charset=utf-8");
try {
PrintWriter out = response.getWriter();
out.println(backnews);
}catch(IOException e) {
e.printStackTrace();
}
}}
3. 因爲要通過網絡獲取到用戶頭像資源,所以需要創建LoadImgByNet.java文件,對網絡圖片資源進行處理,代碼如下:
package com.example.discover; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class LoadImgByNet { public static Bitmap getBitmap(String path) throws IOException { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); if (conn.getResponseCode() == 200){ InputStream inputStream = conn.getInputStream(); Bitmap bitmap = BitmapFactory.decodeStream(inputStream); return bitmap; } return null; } }
4.在Android項目的MyTabFragment.java中給註冊、登錄按鈕綁定事件
- 因爲要進行網絡請求所以要設置線程策略setVersion,以及在AndroidMainfest.xml中設置網絡訪問權限(<uses-permission android:name="android.permission.INTERNET"/>)
- 點擊註冊按鈕,彈出註冊框(關聯外部的佈局R.layout.activity_register),給對話款添加“註冊”按鈕,實現該註冊按鈕時需要處理對話框自動關閉的問題
- 點擊登錄按鈕,彈出登錄框(關聯外部的佈局R.layout.activity_login),同上述的註冊按鈕做相同處理。另外在登錄成功之後還需要修改登錄狀態並進行UI更新,這部分操作放在方法loginSuccess()中
- 處理對話框的取消按鈕事件
package com.example.discover; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.os.Bundle; import android.os.StrictMode; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TableRow; import android.widget.TextView; import android.widget.Toast; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class MyTabFragment extends Fragment{ TableRow account_set_bt; //第一個功能 View myLayout; //“我的”頁面 Button pop_register,pop_login; //彈出對話框的按鈕 ImageView my_head_img; //用戶頭像 TextView my_name,my_sign; //用戶暱稱和心情 /*Button go_login,go_register;*/ String userName,passWord,signature,headImg; //存放用戶基本信息 RelativeLayout login,register; //註冊、登錄頁面 LinearLayout login_top,un_login_top; //“我的”頁面頂部兩種狀態下的佈局 Activity mActivity; //存放當前的activity TextView test3; //用於返回測試信息 String baseUrl = "http://10.0.2.2:8080/iShareService/servlet/"; //web服務器的地址 String imgBaseUrl = "http://10.0.2.2:8080/iShareService/images/"; //圖片資源 boolean isLogin; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { myLayout = inflater.inflate(R.layout.my_tab_content, container, false); return myLayout; } //APP如果在主線程中請求網絡操作,將會拋出異常,所以需要用線程來操作網絡請求 void setVersion() { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .detectNetwork() .penaltyLog() .build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() //探測SQLite數據庫操作 .penaltyLog() //打印logcat .penaltyDeath() .build()); } //綁定點擊事件 @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mActivity = this.getActivity(); // 設置線程策略 setVersion(); login_top = ( LinearLayout)getActivity().findViewById(R.id.login_top); //“我的”頁面頂部登錄後顯示的用戶信息 un_login_top = (LinearLayout)getActivity().findViewById(R.id.un_login_top); //“我的”頁面未登錄時顯示的登錄、註冊按鈕 my_head_img = ( ImageView) getActivity().findViewById(R.id.images_head); //我的頭像 my_name = (TextView) getActivity().findViewById(R.id.t_name); //我的暱稱 my_sign = (TextView) getActivity().findViewById(R.id.t_sign); //我的簽名 account_set_bt =(TableRow)getActivity().findViewById(R.id.more_page_row1); //"我的"界面第一個功能 account_set_bt.setOnClickListener(new mClick()); pop_register = (Button)getActivity().findViewById(R.id.pop_register); //彈出註冊對話框的按鈕 pop_login = (Button)getActivity().findViewById(R.id.pop_login); //彈出登錄對話框的按鈕 test3 = (TextView) getActivity().findViewById(R.id.test3_info); //測試 //根據登錄狀態顯示不同的UI ,用SharePreferences判斷用戶是否登錄 changeStatus(); /* SharedPreferences sp = mActivity.getSharedPreferences("save", Context.MODE_PRIVATE); isLogin = sp.getBoolean("isLogin",false); if(isLogin){ //已經登錄時設置用戶相關信息爲顯示狀態 //username = this.getActivity().getSharedPreferences("config", Context.MODE_PRIVATE).getString("fname", ""); login_top.setVisibility(View.VISIBLE); }else{ //尚未登錄,設置登錄、註冊按鈕爲顯示狀態 un_login_top.setVisibility(View.VISIBLE); // 設置線程策略 setVersion(); }*/ pop_register.setOnClickListener(new popClick()); //彈出註冊登錄對話框事件 pop_login.setOnClickListener(new popClick()); } //“我的”頁面中相關點擊事件 class mClick implements View.OnClickListener { public void onClick(View v) { if(isLogin) { if (v == account_set_bt) { //點擊了賬號管理 Intent account_manage_intent = new Intent(); account_manage_intent.setClass(mActivity, AccountManagement.class); //創建intent對象,並制定跳轉頁面 startActivity(account_manage_intent); //跳轉到賬號管理頁面 /*TextView textView = (TextView) getActivity().findViewById(R.id.test_text_view); //用於放測試的提示信息 Toast.makeText(getActivity(), textView.getText(), Toast.LENGTH_LONG).show();*/ } }else{ Toast.makeText(getActivity(), "請先登錄!", Toast.LENGTH_LONG).show(); } } } //登錄、註冊彈框 class popClick implements View.OnClickListener { AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); public void onClick(View v) { if (v == pop_register) { register= (RelativeLayout) getLayoutInflater().inflate(R.layout.activity_register, null); //從另外的佈局關聯組件 builder.setTitle("用戶註冊").setMessage("請輸入用戶名和密碼").setView(login); builder.setTitle("i 分享").setView(register); builder.setNegativeButton("取消", new exitClick()); /*dialog.setPositiveButton("註冊", new registerClick());*/ builder.setPositiveButton("註冊", null); //不監聽,防止被關閉 builder.setIcon(R.drawable.app_icon); final AlertDialog dialog = builder.create(); dialog.show(); //不會自動關閉對話框,可手動關閉 dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Toast.makeText(getActivity(),"保存",Toast.LENGTH_SHORT).show(); StringBuilder stringBuilder = new StringBuilder(); BufferedReader buffer = null; HttpURLConnection connGET = null; EditText txtUserName,txtUserPass1,txtUserPass2,txtSignature; TextView test1; String passWord2; txtUserName = (EditText)register.findViewById(R.id.et_username); txtUserPass1 = (EditText)register.findViewById(R.id.et_password1); txtUserPass2 = (EditText)register.findViewById(R.id.et_password2); txtSignature= (EditText)register.findViewById(R.id.et_signature); test1 = (TextView)register.findViewById(R.id.test1_view_info); userName = txtUserName.getText().toString(); passWord = txtUserPass1.getText().toString(); passWord2 = txtUserPass2.getText().toString(); signature = txtSignature.getText().toString(); //從密碼框中取值比較 if(!passWord.equals(passWord2)){ test1.setText("兩次密碼不一致!"); Toast.makeText(getActivity(), "兩次密碼不一致", Toast.LENGTH_LONG).show(); return; } try { String registerUrl = baseUrl+"Register?username="+userName+"&password="+passWord+"&signature="+signature; URL url = new URL(registerUrl); connGET = (HttpURLConnection) url.openConnection(); connGET.setConnectTimeout(5000); connGET.setRequestMethod("GET"); if (connGET.getResponseCode() == 200) { buffer = new BufferedReader(new InputStreamReader(connGET.getInputStream())); for (String s = buffer.readLine(); s != null; s = buffer.readLine()) { stringBuilder.append(s); } test1.setText(stringBuilder); dialog.dismiss(); //註冊成功,手動關閉對話框 buffer.close(); }else{ test1.setText("非200.."+connGET.getResponseCode() ); } } catch (Exception e) { e.printStackTrace(); test1.setText("get 提交 err.." + e.toString()); } Toast.makeText(getActivity(), test1.getText(), Toast.LENGTH_LONG).show(); test3.setText(userName+"——"+passWord+"——"+passWord2+"——"+signature+"——"+baseUrl+"Register?username="+userName+"&password="+passWord+"&signature="+signature+"_"+test1.getText()); } }); } else if (v == pop_login) { login = (RelativeLayout) getLayoutInflater().inflate(R.layout.activity_login, null); //從另外的佈局關聯組件 builder.setTitle("i 分享").setView(login); builder.setNegativeButton("取消", new exitClick()); builder.setPositiveButton("登錄", null); builder.setIcon(R.drawable.app_icon); final AlertDialog dialog2 = builder.create(); dialog2.show(); //不會自動關閉對話框,可手動關閉 dialog2.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Toast.makeText(getActivity(),"保存",Toast.LENGTH_SHORT).show(); StringBuilder stringBuilder = new StringBuilder(); BufferedReader buffer = null; HttpURLConnection connGET = null; EditText txtUserName2,txtUserPass2; TextView test2; txtUserName2 = (EditText)login.findViewById(R.id.et_login_username); txtUserPass2 = (EditText)login.findViewById(R.id.et_login_password); test2 = (TextView)login.findViewById(R.id.test2_view_info); userName = txtUserName2.getText().toString(); passWord = txtUserPass2.getText().toString(); //從密碼框中取值比較 if(userName.length()==0||passWord.length()==0){ test2.setText("用戶名和密碼不能爲空!"); Toast.makeText(getActivity(), "用戶名和密碼不能爲空!", Toast.LENGTH_LONG).show(); return; } try { String LoginUrl = baseUrl+"Login?username="+userName+"&password="+passWord; URL url = new URL(LoginUrl); connGET = (HttpURLConnection) url.openConnection(); connGET.setConnectTimeout(5000); connGET.setRequestMethod("GET"); if (connGET.getResponseCode() == 200) { buffer = new BufferedReader(new InputStreamReader(connGET.getInputStream())); for (String s = buffer.readLine(); s != null; s = buffer.readLine()) { stringBuilder.append(s); } test2.setText(stringBuilder); //獲取到登錄的用戶暱稱、簽名和頭像 signature = stringBuilder.toString(); headImg = stringBuilder.toString(); loginSuccess(userName,signature,headImg); dialog2.dismiss(); //登錄成功,手動關閉對話框 buffer.close(); }else{ test2.setText("非200.."+connGET.getResponseCode() ); } } catch (Exception e) { e.printStackTrace(); test2.setText("get 提交 err.." + e.toString()); } Toast.makeText(getActivity(), test2.getText(), Toast.LENGTH_LONG).show(); test3.setText(userName+"——"+passWord); //dialog2.dismiss() } }); } } } //登錄成功後的界面以及狀態更改 public void loginSuccess(String name,String sign,String headImg){ //登錄成功後更改登錄狀態爲已登錄 SharedPreferences sp = mActivity.getSharedPreferences("save", Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.putBoolean("isLogin", true); editor.putString("name", name); editor.putString("sign", sign); editor.putString("img", headImg); editor.commit(); //UI更新 changeStatus(); } //根據狀態顯示或隱藏“我的”頁面中頭部信息 public void changeStatus(){ //獲取最新的登錄狀態,SharePreferences爲永久存儲,需要手動退出 SharedPreferences sp = mActivity.getSharedPreferences("save", Context.MODE_PRIVATE); isLogin = sp.getBoolean("isLogin",false); if(isLogin){ Bitmap one; userName = sp.getString("name",""); signature = sp.getString("sign",""); headImg = sp.getString("headImg",""); //設置用戶暱稱、頭像、心情 my_name.setText(userName); my_sign.setText(userName); //通過網絡鏈接獲取圖片 try { one= LoadImgByNet.getBitmap(imgBaseUrl+"my_tab_list1.png"); my_head_img.setImageBitmap(one); }catch(IOException e){ e.printStackTrace(); } //已經登錄時設置用戶相關信息爲顯示狀態 //username = this.getActivity().getSharedPreferences("config", Context.MODE_PRIVATE).getString("fname", ""); login_top.setVisibility(View.VISIBLE); un_login_top.setVisibility(View.GONE); }else{ //尚未登錄,設置登錄、註冊按鈕爲顯示狀態 un_login_top.setVisibility(View.VISIBLE); login_top.setVisibility(View.GONE); } } //註冊對話框的“註冊”按鈕 /*class registerClick implements DialogInterface.OnClickListener{ StringBuilder stringBuilder = new StringBuilder(); BufferedReader buffer = null; HttpURLConnection connGET = null; EditText txtUserName,txtUserPass1,txtUserPass2,txtSignature; TextView test1; String passWord2; public void onClick(DialogInterface dialog,int which){ txtUserName = (EditText)register.findViewById(R.id.et_username); txtUserPass1 = (EditText)register.findViewById(R.id.et_password1); txtUserPass2 = (EditText)register.findViewById(R.id.et_password2); txtSignature= (EditText)register.findViewById(R.id.et_signature); test1 = (TextView)register.findViewById(R.id.test1_view_info); userName = txtUserName.getText().toString(); passWord = txtUserPass1.getText().toString(); passWord2 = txtUserPass2.getText().toString(); signature = txtSignature.getText().toString(); //從密碼框中取值比較 if(!passWord.equals(passWord2)){ test1.setText("兩次密碼不一致!"); Toast.makeText(getActivity(), "兩次密碼不一致", Toast.LENGTH_LONG).show(); return; } try { String registerUrl = baseUrl+"Register?username="+userName+"&password="+passWord+"&signature="+signatstringbuilder用法ure; URL url = new URL(registerUrl); connGET = (HttpURLConnection) url.openConnection(); connGET.setConnectTimeout(5000); connGET.setRequestMethod("GET"); if (connGET.getResponseCode() == 200) { buffer = new BufferedReader(new InputStreamReader(connGET.getInputStream())); for (String s = buffer.readLine(); s != null; s = buffer.readLine()) { stringBuilder.append(s); } test1.setText(stringBuilder); buffer.close(); }else{ test1.setText("非200.."+connGET.getResponseCode() ); } } catch (Exception e) { e.printStackTrace(); test1.setText("get 提交 err.." + e.toString()); } Toast.makeText(getActivity(), test1.getText(), Toast.LENGTH_LONG).show(); //dialog.dismiss(); test3.setText(userName+"——"+passWord+"——"+passWord2+"——"+signature+"——"+baseUrl+"Register?username="+userName+"&password="+passWord+"&signature="+signature+"_"+test1.getText()); } }*/ //輸入對話框的“退出”按鈕事件 class exitClick implements DialogInterface.OnClickListener{ public void onClick(DialogInterface dialog,int which){ dialog.cancel(); //關閉對話框 /* try { Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing"); field.setAccessible(true); field.set(dialog, true); } catch (Exception e) { e.printStackTrace(); }*/ } } }