- 设计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(); }*/ } } }