我是靠谱客的博主 鲤鱼可乐,这篇文章主要介绍Spring+安卓项目开发。已成功一、IDEA中使用SpringBoot来管理后端的请求,IDEA中的基本框架二.Adroid搭建三.安卓中实现的前端功能,以及IDEA中处理的后端请求,现在分享给大家,希望可以做个参考。
文章目录
- 一、IDEA中使用SpringBoot来管理后端的请求,IDEA中的基本框架
- 1.Spring整合mybatis
- 1.进入达内将SSM框架需要的依赖导入
- 2.创建yml文件
- 2.创建数据库并使用逆向工程导入
- 1.建立需要的数据库
- 2.在resources文件下创建使用generatorConfig.xml文件进行逆向工程配置
- 3.封装高可用对象ServerResponse对象
- 1.封装一个ServerResponse类,用于返回状态,信息,提示
- 2.封装一个enum类ResponseCode,用于放状态码跟状态信息
- 3.建立一个DateUtil时间化工具类
- 二.Adroid搭建
- 1.安卓连上网,跟IDEA产生交互
- 1.首先需要添加两端代码在对应module的build.gradle中,让我们可用在后续使用OkHttp协议获取URL数据
- 2.在utils包下添加OkHttpCallback和OkhttpUtils文件
- 3.头文件xml中进行操作
- 4.在res中创建一个xml包,包下包含network_config.xml文件
- 2.建立一个类,其中含有Static全局变量方便后续使用
- 3.编写Baseadapter类,用来使得listview以一个layout为样例实现
- 4.碎片化管理Fragment,实现类似于ajax的效果。
- 1.创建统一管理的main
- 三.安卓中实现的前端功能,以及IDEA中处理的后端请求
- I.登录功能(对应LoginActivity与其的layout界面以及IDEA中的接口处理),以下都只展示Activity的代码
- 1.安卓端先创建好登录的界面,以下为LoginActivity代码详解
- 2.由于URL触发login.do请求,将在IDEA中处理
- 1.在Controller层中的UserController中接收login.do的request请求
- 2.Service层给调用的IUserService
- 3.impl重写IUserService
- 4.mapper层中的userMapper给调用了方法
- 5.usermapper引用了UserMapper.xml来使用数据库查找数据
- II 注册功能
- 1.创建RegisterAcitivity,用于将注册的信息传到URL上
- 2.URL触发了register请求,在IDEA中的UserController处理请求
- 3.在IUserService接口中定义了controller中的方法,并且利用impl重写使用
- 4.在mapper层接口中定义上面的各种方法,并且利用mapper.xml查找数据返回结果
- III 工作功能
- 1.进入OneFragment界面
- 2.其中有两个URL,分别请求了UserController中关于兼职跟全职的请求
- 3.Controller中调用的两个service请求在对应的IJianzhiService中定义
- 4.在impl中重写上面service的两种方法
- 5.impl中调用的mapper方法在JianzhiMapper中定义,并通过mapper.xml返回数据
- 6.mapper.xml连接数据库返回数据
- IV消息列表
- 1.编辑TowFragment界面用于显示消息列表
- 2.根据URL请求,在UserController中接收,并调用list方法处理
- 3.在service中定义findbyPhCon来根据phone跟cond查找对应的id,并根据id的大小来调用不同的findbyid方法
- 4.在impl中重写上述的三种方法
- 5.在jianzhimapper中定义上述的三种方法
- V 我的功能
- 1.编辑ThreeFragment用于显示我的界面
一、IDEA中使用SpringBoot来管理后端的请求,IDEA中的基本框架
1.Spring整合mybatis
1.进入达内将SSM框架需要的依赖导入
2.创建yml文件
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26//创建yml文件 spring: datasource: type: com.alibaba.druid.pool.DruidDataSource druid: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/shopping?serverTimezone=GMT%2B8 username: root password: root max-active: 20 max-wait: 6000 min-idle: 1 test-on-borrow: true test-on-return: true thymeleaf: mode: HTML encoding: UTF-8 cache: false mybatis: //mapper/xml对应生成的路径 mapper-locations: classpath*:com/example/androidtest/mapper/*Mapper.xml //配置文件 config-location: classpath:mybatis-config.xml shopping: host: http://img.neuedu.com
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13//在resources文件下创建mybatis-config.xml文件 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <setting name="logImpl" value="LOG4J"/> </settings> <typeAliases> </typeAliases> </configuration>
2.创建数据库并使用逆向工程导入
1.建立需要的数据库
2.在resources文件下创建使用generatorConfig.xml文件进行逆向工程配置
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <!--导入属性配置--> <!--指定特定数据库的jdbc驱动jar包的位置,需要找到自己的jar包的位置--> <classPathEntry location="D:\alijavaweb\mysql\mysql-connector-java\8.0.15\mysql-connector-java-8.0.15.jar" /> <context id="context" targetRuntime="MyBatis3"> <!-- optional,旨在创建class时,对注释进行控制 --> <commentGenerator> <property name="suppressDate" value="true"/> <property name="suppressAllComments" value="true"/> </commentGenerator> <!--jdbc的数据库连接 -->//跟yml里的配置一样 <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/shopping?serverTimezone=GMT%2B8" userId="root" password="root"> </jdbcConnection> <!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制--> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类 targetPackage 指定生成的model生成所在的包名 targetProject 指定在该项目下所在的路径 --> <!-- 生成表对应的实体类--> <javaModelGenerator targetPackage="com.example.androidtest.pojo" targetProject="./src/main/java"> <!-- 是否允许子包,即targetPackage.schemaName.tableName --> <property name="enableSubPackages" value="false"/> <!-- 是否对model添加 构造函数 --> <property name="constructorBased" value="true"/> <!-- 是否对类CHAR类型的列的数据进行trim操作 --> <property name="trimStrings" value="true"/> <!-- 建立的Model对象是否 不可改变 即生成的Model对象不会有 setter方法,只有构造方法 --> <property name="immutable" value="false"/> </javaModelGenerator> <!--mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 --> <!--生成对应的mapper.xml文件--> <sqlMapGenerator targetPackage="com.example.androidtest.mapper" targetProject="./src/main/resources"> <property name="enableSubPackages" value="false"/> </sqlMapGenerator> <!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码 type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 --> <!-- targetPackage:mapper接口dao生成的位置 --> <!--生成对应的mapper接口文件--> <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.androidtest.dao" targetProject="./src/main/java"> <!-- enableSubPackages:是否让schema作为包的后缀 --> <property name="enableSubPackages" value="false" /> </javaClientGenerator> <!--将tableName改成自己数据库表一样的名字跟数量--> <table tableName="nite_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table> <!-- <table tableName="nite_category" domainObjectName="Category" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>--> <!-- <table tableName="nite_product" domainObjectName="Product" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>--> <!-- <table tableName="nite_cart" domainObjectName="Cart" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>--> <!-- <table tableName="nite_order" domainObjectName="Order" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>--> <!-- <table tableName="nite_item" domainObjectName="Item" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>--> <!-- <table tableName="nite_shipping" domainObjectName="Shipping" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>--> <!-- geelynote mybatis插件的搭建 --> </context> </generatorConfiguration>
3.封装高可用对象ServerResponse对象
心得:为什么要用这个封装的对象呢? 原来我们返回一个比如实体类对象,比如 Jianzhi selectByid(int id);这种,但是如果用了ServerResponse这个封装的类型,我们可以多返回一个状态码来方便我们辨别正确/错误信息。
1.封装一个ServerResponse类,用于返回状态,信息,提示
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.databind.annotation.JsonNaming; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import lombok.Data; /** * 封装前端返回的统一实体类 * @param <T> */ @Data @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)//只包含非空字段 public class ServerResponse<T> { private int status; //状态 0;接口调用成功 private T data; //泛型T,当status=0,将返回的数据封装到data中 private String msg; //提示信息 private ServerResponse(){} private ServerResponse(int status){ this.status = status; } private ServerResponse(int status, T data){ this.status = status; this.data = data; } private ServerResponse(int status, T data, String msg){ this.status = status; this.data = data; this.msg = msg; } @JsonIgnore public boolean isSuccess(){ return this.status == 0; } public static ServerResponse createServerResponseBySuccess(){ return new ServerResponse(0); } /** *<T>后跟方法名表示泛型方法 */ public static <T> ServerResponse createServerResponseBySuccess(T data){ return new ServerResponse(0,data); } public static <T> ServerResponse createServerResponseBySuccess(T data,String msg){ return new ServerResponse(0,data,msg); } public static ServerResponse createServerResponseByFail(int status){ return new ServerResponse(status); } public static ServerResponse createServerResponseByFail(int status,String msg){ return new ServerResponse(status,null,msg); } }
2.封装一个enum类ResponseCode,用于放状态码跟状态信息
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37public enum ResponseCode { //状态信息放在;前面 USERNAME_NOT_EMPTY(1,"用户名不能为空"), PASSWORD_NOT_EMPTY(2,"密码不能为空"), USERNAME_NOT_EXIST(3,"用户名不存在"), PASSWORD_ERROR(4,"密码错误"), PARAMETER_NOT_EMPTY(5,"参数不能为空"), EMAIL_NOT_EMPTY(6,"邮箱不能为空"), QUESTION_NOT_EMPTY(7,"密保问题不能为空"), ANSWER_NOT_EMPTY(8,"密保答案不能为空"), PHONE_NOT_EMPTY(9,"电话不能为空"), USERNAME_EXIST(10,"用户名已存在"), EMAIL_EXIST(11,"邮箱已存在"), REGISTER_FAIL(12,"注册失败"), NEED_LOGIN(13,"未登录"), USERINFO_UPDATE_FAIL(14,"用户信息修改失败"), ; private int code; private String msg; ResponseCode(int code,String msg){ this.code = code; this.msg = msg; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
3.建立一个DateUtil时间化工具类
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26import org.apache.commons.lang.StringUtils; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import java.util.Date; /* 时间格式化工具类 */ public class DateUtil { public static final String STANDARD = "yyyy-MM-dd HH:mm:ss"; //将String转成Date public static Date string2Date(String strDate){ DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(STANDARD); DateTime dateTime = dateTimeFormatter.parseDateTime(strDate); return dateTime.toDate(); } //将Date转成String public static String date2String(Date date){ if(date == null){ return StringUtils.EMPTY; } DateTime dateTime = new DateTime(date); return dateTime.toString(STANDARD); } }
二.Adroid搭建
1.安卓连上网,跟IDEA产生交互
1.首先需要添加两端代码在对应module的build.gradle中,让我们可用在后续使用OkHttp协议获取URL数据
复制代码
1
2
3implementation'com.squareup.okhttp3:okhttp:3.10.0' implementation 'com.google.code.gson:gson:2.8.6'
2.在utils包下添加OkHttpCallback和OkhttpUtils文件
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24//OkHttpUtils文件,用于获取URL上get或者post、downFile等方法的信息 public class OkHttpUtils { private static final OkHttpClient CLIENT = new OkHttpClient(); public static void get(String url,OkHttpCallback Callback){ Callback.url = url; //构建请求头 Request request = new Request.Builder().url(url).build(); //接收服务端的响应 CLIENT.newCall(request).enqueue(Callback); } public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); public static void post(String url,String json,OkHttpCallback callback){ callback.url = url; RequestBody body = RequestBody.create(JSON,json); Request request = new Request.Builder().url(url).post(body).build(); CLIENT.newCall(request).enqueue(callback); } public static void downFile(String url,final String saveDir,OkHttpCallback callback){ callback.url = url; Request request = new Request.Builder().url(url).build(); CLIENT.newCall(request).enqueue( callback); } }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32import android.util.Log; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; //监听服务端的响应,获取服务端的正确/报错信息 public class OkHttpCallback implements Callback { private final String TAG =com.example.onlinecareer.util.OkHttpCallback.class.getSimpleName(); public String url; public String result; //接口调用成功 @Override public void onResponse(Call call, Response response) throws IOException { Log.d(TAG,"url:"+url); //成功时获取接口数据 result = response.body().string().toString(); Log.d(TAG,"请求成功:"+result); //调用onFinish输出获取的信息,可用通过重写onFinish()方法,运用hashmap获取需要的值并存储 onFinish("success",result); } public void onFailure(Call call,IOException e){ Log.d(TAG,"url:"+url); Log.d(TAG,"请求失败:"+e.toString()); //请求失败,输出失败的原因 onFinish("failure",e.toString()); } public void onFinish(String status,String msg){ Log.d(TAG,"url:"+url + "status:" + status+"msg:"+msg); } }
3.头文件xml中进行操作
复制代码
1
2
3
4
5
6
7
8<!--在头部插入--> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!--在application标签中插入--> android:networkSecurityConfig="@xml/network_config" android:usesCleartextTraffic="true"
4.在res中创建一个xml包,包下包含network_config.xml文件
复制代码
1
2
3
4
5<?xml version="1.0" encoding="utf-8"?> <network-security-config> <base-config cleartextTrafficPermitted="true" /> </network-security-config>
2.建立一个类,其中含有Static全局变量方便后续使用
复制代码
1
2
3
4
5
6
7
8
9
10
11public class CommonData { //登录状态 public static boolean isLogin=false; //登录用户数据 public static HashMap<String, Object> user_hashMap; public static HashMap<String, Object> user_hashMap1; //所有用户数据 public static ArrayList<HashMap<String, Object>> list =new ArrayList<HashMap<String,Object>>(); }
3.编写Baseadapter类,用来使得listview以一个layout为样例实现
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60public class JobAdapter extends BaseAdapter { //定义一个动态数组 private List<HashMap<String, Object>> data; private Context context; //这里的data是OneFragment传来的hashmap的数据 public JobAdapter(Context context, List<HashMap<String, Object>> data) { this.context = context; this.data = data; } @Override public int getCount() { return data.size(); } @Override public HashMap<String, Object> getItem(int position) { return data.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { //跟目标的layout关联 if (convertView == null) { convertView = View.inflate(context, R.layout.item_job, null); new ViewHolder(convertView); } //获取目标layout的控件 final ViewHolder holder = (ViewHolder) convertView.getTag(); HashMap<String, Object> hashMap=getItem(position); //将获得hashmap的数据放入控件列表中 holder.iv_job_icon.setBackgroundResource((Integer)hashMap.get("img")); holder.tv_job_name.setText(hashMap.get("name").toString()); holder.tv_job_company.setText(hashMap.get("company").toString()); holder.tv_job_time.setText(hashMap.get("time").toString()); holder.tv_job_salary.setText(hashMap.get("salary").toString()); holder.tv_job_type.setText(hashMap.get("jobType").toString()); return convertView; } //跟目标layout的控件对应 class ViewHolder { public ImageView iv_job_icon; public TextView tv_job_name; public TextView tv_job_company; public TextView tv_job_time; public TextView tv_job_salary; public TextView tv_job_type; public ViewHolder(View view) { iv_job_icon = (ImageView) view.findViewById(R.id.iv_job_icon); tv_job_name = (TextView) view.findViewById(R.id.tv_job_name); tv_job_company = (TextView) view.findViewById(R.id.tv_job_company); tv_job_time = (TextView) view.findViewById(R.id.tv_job_time); tv_job_salary = (TextView) view.findViewById(R.id.tv_job_salary); tv_job_type = (TextView) view.findViewById(R.id.tv_job_type); view.setTag(this); } } }
4.碎片化管理Fragment,实现类似于ajax的效果。
1.创建统一管理的main
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194@SuppressLint("NewApi") public class MainActivity extends Activity implements CompoundButton.OnCheckedChangeListener { private FrameLayout frameLayout; public OneFragment oneFragment; public TwoFragment twoFragment; public ThreeFragment threeFragment; public Fragment fa; private RadioButton radioButton1, radioButton2, radioButton3; private int currentTab = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initView(); initEvent(); } @Override protected void onResume() { super.onResume(); setSelect(currentTab); } private void initView() { frameLayout = (FrameLayout) findViewById(R.id.fl_content); radioButton1 = (RadioButton) findViewById(R.id.radioButton1); radioButton2 = (RadioButton) findViewById(R.id.radioButton2); radioButton3 = (RadioButton) findViewById(R.id.radioButton3); } //在刚开始点开的时候进入0代表的页面 private void initEvent() { // TODO Auto-generated method stub radioButton1.setOnCheckedChangeListener(this); radioButton2.setOnCheckedChangeListener(this); radioButton3.setOnCheckedChangeListener(this); setSelect(0); radioButton1.setCompoundDrawablesWithIntrinsicBounds( null, getApplication().getResources().getDrawable( R.drawable.home_selected), null, null); radioButton1.setTextColor(0xff2C97D4); } //设置下面三个按钮的样式,并且全部设成灰色 private void setImg() { radioButton1.setCompoundDrawablesWithIntrinsicBounds( null, getApplication().getResources().getDrawable( R.drawable.home_normal), null, null); radioButton2.setCompoundDrawablesWithIntrinsicBounds( null, getApplication().getResources().getDrawable( R.drawable.message_normal), null, null); radioButton3.setCompoundDrawablesWithIntrinsicBounds( null, getApplication().getResources().getDrawable( R.drawable.my_normal), null, null); radioButton1.setTextColor(0xff979797); radioButton2.setTextColor(0xff979797); radioButton3.setTextColor(0xff979797); } //这里是监听按钮,按下后可以给予需要的页面 @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { switch (buttonView.getId()) { case R.id.radioButton1: setImg(); currentTab = 0; radioButton1.setTextColor(0xff2C97D4); radioButton1.setCompoundDrawablesWithIntrinsicBounds( null, getApplication().getResources().getDrawable( R.drawable.home_selected), null, null); setSelect(0); break; case R.id.radioButton2: if (CommonData.isLogin) { setImg(); currentTab = 1; radioButton2.setTextColor(0xff2C97D4); radioButton2.setCompoundDrawablesWithIntrinsicBounds( null, getApplication().getResources().getDrawable( R.drawable.message_selected), null, null); setSelect(1); } else { Intent intent = new Intent(this, LoginActivity.class); startActivityForResult(intent, 1); } break; case R.id.radioButton3: setImg(); currentTab = 2; radioButton3.setTextColor(0xff2C97D4); radioButton3.setCompoundDrawablesWithIntrinsicBounds( null, getApplication().getResources().getDrawable( R.drawable.my_selected), null, null); setSelect(2); break; } } } //这是刚开始登录的时候传了个ok来,然后通过判断它来获得页面是否登录,登录则给进入1代表的界面 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { String result = data.getExtras().getString("result");// 得到新Activity // 关闭后返回的数据 if (result.equals("ok")) { setImg(); currentTab = 1; radioButton2.setTextColor(0xff2C97D4); radioButton2.setCompoundDrawablesWithIntrinsicBounds( null, getApplication().getResources().getDrawable( R.drawable.message_selected), null, null); setSelect(1); } else { if (currentTab == 0) { radioButton1.setChecked(true); radioButton1.setTextColor(0xff2C97D4); radioButton1.setCompoundDrawablesWithIntrinsicBounds( null, getApplication().getResources().getDrawable( R.drawable.home_selected), null, null); setSelect(0); } else if (currentTab == 2) { radioButton3.setChecked(true); radioButton3.setTextColor(0xff2C97D4); radioButton3.setCompoundDrawablesWithIntrinsicBounds( null, getApplication().getResources().getDrawable( R.drawable.my_selected), null, null); setSelect(2); } } } //该方法让界面上不需要的内容隐藏,需要的显示出来 public void setSelect(int i) { FragmentManager fm = getFragmentManager(); FragmentTransaction transaction = fm.beginTransaction(); switch (i) { case 0: hideFragment(transaction, twoFragment); hideFragment(transaction, threeFragment); if (oneFragment == null) { oneFragment = new OneFragment(); transaction.add(R.id.fl_content, oneFragment, "oneFragment"); } else { transaction.show(oneFragment); } break; case 1: hideFragment(transaction, oneFragment); hideFragment(transaction, threeFragment); if (twoFragment == null) { twoFragment = new TwoFragment(); transaction.add(R.id.fl_content, twoFragment, "twoFragment"); } else { transaction.show(twoFragment); } break; case 2: hideFragment(transaction, oneFragment); hideFragment(transaction, twoFragment); if (threeFragment == null) { threeFragment = new ThreeFragment(); transaction.add(R.id.fl_content, threeFragment, "threeFragment"); } else { transaction.show(threeFragment); } break; } transaction.commit(); } //隐藏fragment private void hideFragment(FragmentTransaction transaction, Fragment fragment) { if (fragment != null) { transaction.hide(fragment); } } /** * 点击退出键退出界面的时候不会关闭,应用下次进入的时候不用重启 */ @Override public boolean dispatchKeyEvent(KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) { // 具体的操作代码 moveTaskToBack(true); return true; } return super.dispatchKeyEvent(event); } }
三.安卓中实现的前端功能,以及IDEA中处理的后端请求
I.登录功能(对应LoginActivity与其的layout界面以及IDEA中的接口处理),以下都只展示Activity的代码
心得:在Spring中,一般是先定义mapper层,然后.xml取数据库查找返回需要的数据。再定Service层,impl重写service方法,在其中调用mapper层的方法拿去数据。最后在controller使用service方法处理请求
1.安卓端先创建好登录的界面,以下为LoginActivity代码详解
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77public class LoginActivity extends Activity implements View.OnClickListener { private TextView tv_back, tv_title, tv_register; private EditText et_account, et_password; private Button btn_login; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); initView(); } private void initView() { tv_title = (TextView) findViewById(R.id.tv_title); tv_title.setText(R.string.login); tv_back = (TextView) findViewById(R.id.tv_back); tv_register = (TextView) findViewById(R.id.tv_register); btn_login = (Button) findViewById(R.id.btn_login); tv_back.setOnClickListener(this); tv_register.setOnClickListener(this); btn_login.setOnClickListener(this); et_account = (EditText) findViewById(R.id.et_account); et_password = (EditText) findViewById(R.id.et_password); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.tv_register: Intent intent=new Intent(this,RegisterActivity.class); startActivity(intent); break; case R.id.btn_login: String username=et_account.getText().toString(); String psd=et_password.getText().toString(); //通过OkHttoUtils.get的方法获取URL传来的json数据,json数据会存在onFinish方法的msg中 //此处的URL去访问了这个网址,触发了IDEA中的request请求,在IDEA中的UserController中处理 OkHttpUtils.get("http://172.21.254.44:8080/portal/user/login.do?username="+username+"&password="+psd, new OkHttpCallback(){ @Override public void onFinish(String status, String msg) { super.onFinish(status, msg); //解析msg Looper.prepare(); Gson gson = new Gson(); //通过gson.from方法返回需要的类型的数据 ServerResponse<User> serverResponse = gson.fromJson(msg, new TypeToken<ServerResponse<User>>(){}.getType()); System.out.println(serverResponse.getData().getId()); if (serverResponse == null) { Toast.makeText(LoginActivity.this,"用户名或密码不正确",Toast.LENGTH_SHORT).show(); }else{ //用hashMap静态全局变量转发获取的值。 HashMap<String,Object> hashMap = new HashMap<String,Object>(); hashMap.put("id",serverResponse.getData().getId()); hashMap.put("name",serverResponse.getData().getUsername()); hashMap.put("password",serverResponse.getData().getPassword()); hashMap.put("phone",serverResponse.getData().getPhone()); hashMap.put("major",serverResponse.getData().getIp()); hashMap.put("sex",serverResponse.getData().getQuestion()); hashMap.put("age",serverResponse.getData().getAnswer()); hashMap.put("school",serverResponse.getData().getEmail()); System.out.println(serverResponse.getData().getId()); //标志登录状态 CommonData.isLogin=true; //将获取的数据存入CommonData的全局变量中 CommonData.user_hashMap1=hashMap; Intent intent = new Intent(LoginActivity.this,MainActivity.class); intent.putExtra("result", "ok"); setResult(RESULT_OK, intent); startActivity(intent); } Looper.loop(); } }); break; } } }
2.由于URL触发login.do请求,将在IDEA中处理
1.在Controller层中的UserController中接收login.do的request请求
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19@RestController//标注为Controller并且返回json数据 @RequestMapping("/portal/")//所有请求以/portal开头 public class UserController { @Autowired IUserService userService; @Resource IJianzhiService iJianzhiService; @RequestMapping(value = "user/login.do") public ServerResponse login(String username, String password, HttpSession session){ //调用Service层的userSerivce的loginLogic方法返回User对象的数据 ServerResponse serverResponse = userService.loginLogic(username,password); if(serverResponse.isSuccess()){ session.setAttribute(Const.CURRENT_USER,serverResponse.getData()); } //return返回带有User对象数据跟状态0的数据 return serverResponse; } }
2.Service层给调用的IUserService
复制代码
1
2
3
4public interface IUserService { public ServerResponse loginLogic(String username,String password); }
3.impl重写IUserService
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54@Service public class UserService implements IUserService { @Autowired private UserMapper userMapper; @Override public ServerResponse loginLogic(String username,String password){ //step1:用户名和密码的非空判断 /** * 通过commons-lang依赖中的封装方法也可以进行空判断 * 其中方法有StringUtils.isBlank,StringUtils.isEmpty */ if(StringUtils.isBlank(username)){ //return+ServerResponse中返回的失败信息 return ServerResponse.createServerResponseByFail (ResponseCode.USERNAME_NOT_EMPTY.getCode() ,ResponseCode.USERNAME_NOT_EMPTY.getMsg()); } if(StringUtils.isBlank(password)){ return ServerResponse.createServerResponseByFail(ResponseCode.PASSWORD_NOT_EMPTY.getCode(),ResponseCode.PASSWORD_NOT_EMPTY.getMsg()); } //step2:查看用户名是否存在 Integer count = userMapper.findByUsername(username); if(count == 0){ return ServerResponse.createServerResponseByFail (ResponseCode.USERNAME_NOT_EXIST.getCode(), ResponseCode.USERNAME_NOT_EXIST.getMsg());} //step3:调用usermapper的方法根据用户名和密码查询该用户的信息。 User user = userMapper.findByUsernameAndPassword(username,password); if(user == null){ return ServerResponse.createServerResponseByFail (ResponseCode.PASSWORD_ERROR.getCode(), ResponseCode.PASSWORD_ERROR.getMsg());} //step4:返回结果,对应以下的方法获取了状态0,以及user对象中携带的json数据 return ServerResponse.createServerResponseBySuccess(convert(user)); /*public static <T> ServerResponse createServerResponseBySuccess(T data){ return new ServerResponse(0,data);}*/ } //另外封装的UserVO对象返回的数据,给网页显示,可不给关键信息显示到前端给人看到。 private UserVO convert(User user){ UserVO userVO = new UserVO(); userVO.setId(user.getId()); userVO.setQuestion(user.getQuestion()); userVO.setAnswer(user.getAnswer()); userVO.setUsername(user.getUsername()); userVO.setPassword(user.getPassword()); userVO.setEmail(user.getEmail()); userVO.setPhone(user.getPhone()); userVO.setIp(user.getIp()); userVO.setCreateTime(DateUtil.date2String(user.getCreateTime())); userVO.setUpdateTime(DateUtil.date2String(user.getUpdateTime())); return userVO; } }
4.mapper层中的userMapper给调用了方法
复制代码
1
2
3
4
5
6public interface UserMapper { int findByUsername(@Param("username") String username); User findByUsernameAndPassword(@Param("username") String username,@Param("password") String password); }
5.usermapper引用了UserMapper.xml来使用数据库查找数据
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--将对应的mapper对应上--> <mapper namespace="com.example.androidtest.dao.UserMapper"> <!--其中paramterType为输入数据类型,resultType为输出的数据类型--> <!--id对应方法名--> <select id="findByUsername" parameterType="String" resultType="int"> select count(*) from nite_user where username = #{username} </select> <select id="findByUsernameAndPassword" parameterType="map" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from nite_user where username = #{username} and password = #{password} </select> </mapper>
II 注册功能
思路:1.安卓端建立注册页面,当点击了注册按钮之后,可以把需要的信息通过实例化对象获取,并用URL get请求来给予后端 2.后端处理URL请求,存入数据库。
1.创建RegisterAcitivity,用于将注册的信息传到URL上
< E m p t y M a t h B l o c k > <Empty space Math space Block> <Empty Math Block>
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96@SuppressLint("NewApi") public class RegisterActivity extends Activity implements View.OnClickListener { private TextView tv_back, tv_title; private EditText et_phone, et_password, et_re_password,et_name; private Button btn_register; RadioButton rb_nan,rb_nv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); initView(); } private void initView() { tv_title = (TextView) findViewById(R.id.tv_title); tv_title.setText(R.string.register); tv_back = (TextView) findViewById(R.id.tv_back); btn_register = (Button) findViewById(R.id.btn_register); rb_nan = findViewById(R.id.rb_man); rb_nv = findViewById(R.id.rb_woman); tv_back.setOnClickListener(this); btn_register.setOnClickListener(this); et_phone = (EditText) findViewById(R.id.et_phone); et_password = (EditText) findViewById(R.id.et_password); et_re_password = (EditText) findViewById(R.id.et_re_password); et_name = findViewById(R.id.et_name); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.tv_back: Intent intent = new Intent(this,LoginActivity.class); startActivity(intent); break; case R.id.btn_register: String name = et_name.getText().toString(); String phone = et_phone.getText().toString(); String psd= et_password.getText().toString(); String psd1 = et_re_password.getText().toString(); if(phone.equals("")||psd.equals("")||psd1.equals("")||name.equals("")){ Toast.makeText(RegisterActivity.this,"填写信息不完整", Toast.LENGTH_LONG).show(); }else if(!psd.equals(psd1)){ Toast.makeText(RegisterActivity.this,"密码不一致", Toast.LENGTH_LONG).show(); }else { //将输入的姓名、密码、电话传到URL请求中,让IDEA中的UserController中的方法来获取并处理 OkHttpUtils.get("http://172.21.254.44:8080/portal/user/register.do?username="+name+"&password="+psd+"&phone"+phone, new OkHttpCallback(){ @Override public void onFinish(String status, String msg) { super.onFinish(status, msg); //解析msg Gson gson = new Gson(); ServerResponse<User> serverResponse = gson.fromJson(msg, new TypeToken<ServerResponse<User>>(){}.getType()); int status1 = serverResponse.getStatus(); if(status1 == 0){ Looper.prepare(); //子线程弹窗需添加 Toast.makeText(RegisterActivity.this,"注册成功",Toast.LENGTH_SHORT).show(); Looper.loop(); //子线程弹窗需添加 } } }); Intent intent1 = new Intent(RegisterActivity.this,LoginActivity.class); startActivity(intent1); } break; } } //用户是否已存在 private boolean isExist(SQLiteDatabase db, String tel) { // DBHelper helper=new DBHelper(this); // db=helper.getReadableDatabase(); String sql = "select * from user_table where tel = '" + tel + "'"; Cursor cursor = db.rawQuery(sql, new String[0]); // db.close(); if (cursor.getCount() != 0) { Toast.makeText(RegisterActivity.this, "用户已经存在,不能重复注册!", Toast.LENGTH_SHORT).show(); cursor.close(); return true; }else{ cursor.close(); return false; } } // 验证电话号码 public boolean isMobileNumber(String mobiles) { Pattern p = Pattern .compile("^((13[0-9])|(14[5,7])|(15[^4,\D])|(18[0-9])|(17[0,6,7,8]))\d{8}$"); Matcher m = p.matcher(mobiles); return m.matches(); } }
2.URL触发了register请求,在IDEA中的UserController处理请求
复制代码
1
2
3
4
5@RequestMapping(value = "user/register.do") public ServerResponse register(User user){ return userService.registerLogic(user); }
3.在IUserService接口中定义了controller中的方法,并且利用impl重写使用
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38@Override public ServerResponse registerLogic(User user){ //step1:用户名和密码等一些列数据的非空判断 if(user == null){ return ServerResponse.createServerResponseByFail(ResponseCode.PARAMETER_NOT_EMPTY.getCode(),ResponseCode.PARAMETER_NOT_EMPTY.getMsg()); } String username = user.getUsername(); String password = user.getPassword(); String email = user.getEmail(); String question = user.getQuestion(); String answer = user.getAnswer(); String phone = user.getPhone(); if(StringUtils.isBlank(username)){ return ServerResponse.createServerResponseByFail(ResponseCode.USERNAME_NOT_EMPTY.getCode(),ResponseCode.USERNAME_NOT_EMPTY.getMsg()); } if(StringUtils.isBlank(password)){ return ServerResponse.createServerResponseByFail(ResponseCode.PASSWORD_NOT_EMPTY.getCode(),ResponseCode.PASSWORD_NOT_EMPTY.getMsg()); } //step2 判断用户名是否存在 Integer count = userMapper.findByUsername(username); if(count > 0){ return ServerResponse.createServerResponseByFail(ResponseCode.USERNAME_EXIST.getCode(),ResponseCode.USERNAME_EXIST.getMsg()); } //step3 判断邮箱是否存在 Integer email_count = userMapper.findByEmail(email); if(email_count > 0){ return ServerResponse.createServerResponseByFail(ResponseCode.EMAIL_EXIST.getCode(),ResponseCode.EMAIL_EXIST.getMsg()); } //step4 注册 //可加密 user.setRole(Const.CUSTOM); Integer result = userMapper.insert(user); if(result == 0){ return ServerResponse.createServerResponseByFail(ResponseCode.REGISTER_FAIL.getCode(),ResponseCode.REGISTER_FAIL.getMsg()); } return ServerResponse.createServerResponseBySuccess(); }
4.在mapper层接口中定义上面的各种方法,并且利用mapper.xml查找数据返回结果
III 工作功能
因为进入LoginActivity登录会转入MainActivity判断,刚开始默认进入0代表的Fragment界面。
1.进入OneFragment界面
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128@SuppressLint("NewApi") public class OneFragment extends Fragment implements OnClickListener { private View rootView; private TextView tv_part_job,tv_full_time; private ListView lv_job; private JobAdapter adapter; //创建两个hashmap的list类型用于存放全职跟兼职的数据 private List<HashMap<String, Object>> part_job_Data; private List<HashMap<String, Object>> full_job_Data; private int job_type=0;//0代表兼职,1代表全职 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (rootView == null) { rootView = inflater.inflate(R.layout.fragment_one, container, false); } return rootView; } public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initData(); initView(); //进入职位详情 lv_job.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapter, View arg1, int position, long arg3) { Intent intent=new Intent(getActivity(), JobDetailActivity.class); Bundle data = new Bundle(); data.putSerializable("job", (HashMap<String, Object>)adapter.getItemAtPosition(position)); intent.putExtras(data); startActivity(intent); } }); } private void initData(){ part_job_Data=new ArrayList<HashMap<String, Object>>(); full_job_Data=new ArrayList<HashMap<String, Object>>(); //通过URL去UserController中使用findjianzhi方法获取数据库中的兼职数据并返回。 OkHttpUtils.get("http://172.21.254.44:8080/portal/findjianzhi.do" , new OkHttpCallback() { @Override public void onFinish(String status, String msg) { super.onFinish(status, msg); //解析数据 Gson gson = new Gson(); List<Jianzhi> job = gson.fromJson(msg, new TypeToken<List<Jianzhi>>() {}.getType()); //Looper.prepare(); for (int i = 0; i < job.size(); i++) { HashMap<String, Object> hashMap = new HashMap<String, Object>(); hashMap.put("id", job.get(i).getId()); hashMap.put("img", R.drawable.ic_launcher); hashMap.put("name",job.get(i).getPartjobname()); hashMap.put("jobType", "兼职"); hashMap.put("company", job.get(i).getPartjobcompany()); hashMap.put("time", job.get(i).getPartjobtime()); hashMap.put("salary", job.get(i).getPartjobsalary()); hashMap.put("people", job.get(i).getPartjobpeople()); hashMap.put("address", job.get(i).getPartjobaddress()); hashMap.put("payWay", job.get(i).getPartjobpayway()); part_job_Data.add(hashMap); } //Looper.loop(); } }); //通过URL去UserController中使用findquanzhi方法获取数据库中的兼职数据并返回。 OkHttpUtils.get("http://172.21.254.44:8080/portal/findquanzhi.do" , new OkHttpCallback() { @Override public void onFinish(String status, String msg) { super.onFinish(status, msg); //解析数据 Gson gson = new Gson(); List<Jianzhi> job = gson.fromJson(msg, new TypeToken<List<Jianzhi>>() {}.getType()); //Looper.prepare(); for (int i = 0; i < job.size(); i++) { HashMap<String, Object> hashMap = new HashMap<String, Object>(); hashMap.put("id", job.get(i).getId()); hashMap.put("img", R.drawable.ic_launcher); hashMap.put("name", job.get(i).getPartjobname()); hashMap.put("jobType", "全职"); hashMap.put("company", job.get(i).getPartjobcompany()); hashMap.put("time", job.get(i).getPartjobtime().toString()); hashMap.put("salary", job.get(i).getPartjobsalary()); hashMap.put("people", job.get(i).getPartjobpeople()); hashMap.put("address", job.get(i).getPartjobaddress()); hashMap.put("payWay", job.get(i).getPartjobpayway()); full_job_Data.add(hashMap); } //Looper.loop(); } }); } private void initView() { tv_part_job=(TextView) rootView.findViewById(R.id.tv_part_job); tv_full_time=(TextView) rootView.findViewById(R.id.tv_full_time); lv_job=(ListView) rootView.findViewById(R.id.lv_job); tv_part_job.setOnClickListener(this); tv_full_time.setOnClickListener(this); //刚开始进入OneFragment时,先通过adapter将兼职的信息放入listview中 adapter=new JobAdapter(getActivity(), part_job_Data); lv_job.setAdapter(adapter); } //通过点击事件来切换兼职跟全职信息 @Override public void onClick(View v) { setTextColor(); switch (v.getId()) { case R.id.tv_part_job: tv_part_job.setTextColor(getResources().getColor(R.color.basecolor)); job_type=0; //运用adapter让listview跟item联系起来。 adapter=new JobAdapter(getActivity(), part_job_Data); lv_job.setAdapter(adapter); break; case R.id.tv_full_time: tv_full_time.setTextColor(getResources().getColor(R.color.basecolor)); job_type=1; adapter=new JobAdapter(getActivity(), full_job_Data); lv_job.setAdapter(adapter); break; } } //改变字体的背景颜色 public void setTextColor() { tv_part_job.setTextColor(getResources().getColor(R.color.text_color_primary)); tv_full_time.setTextColor(getResources().getColor(R.color.text_color_primary)); } }
2.其中有两个URL,分别请求了UserController中关于兼职跟全职的请求
复制代码
1
2
3
4
5
6
7
8
9
10
11@RequestMapping(value = "findjianzhi.do") public List<Jianzhi> findjianzhi(){ List<Jianzhi> jianzhi = iJianzhiService.FindAll(); return jianzhi; } @RequestMapping(value = "findquanzhi.do") public List<Jianzhi> findquanzhi(){ List<Jianzhi> quanzhi = iJianzhiService.FindQz(); return quanzhi; }
3.Controller中调用的两个service请求在对应的IJianzhiService中定义
复制代码
1
2
3List<Jianzhi> FindAll(); List<Jianzhi> FindQz();
4.在impl中重写上面service的两种方法
复制代码
1
2
3
4
5
6
7
8
9
10
11
12@Override public List<Jianzhi> FindAll() { List<Jianzhi> jianzhi = jianzhiMapper.findbyall(); return jianzhi; } @Override public List<Jianzhi> FindQz() { List<Jianzhi> quanzhi = jianzhiMapper.findbyqz(); return quanzhi; }
5.impl中调用的mapper方法在JianzhiMapper中定义,并通过mapper.xml返回数据
复制代码
1
2
3List<Jianzhi> findbyall(); List<Jianzhi> findbyqz();
6.mapper.xml连接数据库返回数据
复制代码
1
2
3
4
5
6
7
8
9
10
11<select id="findbyall" resultType="com.example.androidtest.pojo.Jianzhi" parameterType="string"> select id,partjobname,partjobimg,partjobcompany,partjobtime ,partjobsalary,partjobpeople,partjobaddress,partjobpayway from jianzhi </select> <select id="findbyqz" resultType="com.example.androidtest.pojo.Jianzhi" parameterType="string"> select id,partjobname,partjobimg,partjobcompany,partjobtime,partjobsalary,partjobpeople ,partjobaddress,partjobpayway from quanzhi </select>
IV消息列表
1.编辑TowFragment界面用于显示消息列表
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176@SuppressLint("NewApi") public class TwoFragment extends Fragment implements View.OnClickListener { private View rootView; private TextView tv_start, tv_going, tv_over; private ListView lv_task; private JobAdapter adapter; //用于显示三种消息的三个list private List<HashMap<String, Object>> start_Data; private List<HashMap<String, Object>> going_Data; private List<HashMap<String, Object>> over_Data; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (rootView == null) { rootView = inflater .inflate(R.layout.fragment_two, container, false); } return rootView; } public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initData(); initView(); lv_task.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { } }); } private void initData(){ start_Data=new ArrayList<HashMap<String,Object>>(); //已录用 going_Data=new ArrayList<HashMap<String,Object>>(); //未录用 over_Data=new ArrayList<HashMap<String,Object>>(); //已报名 //调用不同的cond的URL请求,将三种cond放入三个list中。 OkHttpUtils.get("http://172.21.254.44:8080/portal/list.do?phone="+ CommonData.user_hashMap1.get("phone")+"&cond=已录用" , new OkHttpCallback() { @Override public void onFinish(String status, String msg) { super.onFinish(status, msg); //解析数据 Gson gson = new Gson(); List<Jianzhi> job = gson.fromJson(msg, new TypeToken<List<Jianzhi>>() {}.getType()); //Looper.prepare(); if (job.size() > 0) { for (int i = 0; i < job.size(); i++) { HashMap<String, Object> hashMap = new HashMap<String, Object>(); hashMap.put("id", job.get(i).getId()); hashMap.put("img", R.drawable.ic_launcher); hashMap.put("name", job.get(i).getPartjobname()); if (job.get(i).getId() < 100) { hashMap.put("jobType", "兼职"); } else { hashMap.put("jobType", "全职"); } hashMap.put("company", job.get(i).getPartjobcompany()); hashMap.put("time", job.get(i).getPartjobtime()); hashMap.put("salary", job.get(i).getPartjobsalary()); hashMap.put("people", job.get(i).getPartjobpeople()); hashMap.put("address", job.get(i).getPartjobaddress()); hashMap.put("payWay", job.get(i).getPartjobpayway()); start_Data.add(hashMap); } //Looper.loop(); } } }); OkHttpUtils.get("http://172.21.254.44:8080/portal/list.do?phone="+ CommonData.user_hashMap1.get("phone")+"&cond=未录用" , new OkHttpCallback() { @Override public void onFinish(String status, String msg) { super.onFinish(status, msg); //解析数据 Gson gson = new Gson(); List<Jianzhi> job = gson.fromJson(msg, new TypeToken<List<Jianzhi>>() {}.getType()); //Looper.prepare(); if (job.size() > 0) { for (int i = 0; i < job.size(); i++) { HashMap<String, Object> hashMap = new HashMap<String, Object>(); hashMap.put("id", job.get(i).getId()); hashMap.put("img", R.drawable.ic_launcher); hashMap.put("name", job.get(i).getPartjobname()); if (job.get(i).getId() < 100) { hashMap.put("jobType", "兼职"); } else { hashMap.put("jobType", "全职"); } hashMap.put("company", job.get(i).getPartjobcompany()); hashMap.put("time", job.get(i).getPartjobtime()); hashMap.put("salary", job.get(i).getPartjobsalary()); hashMap.put("people", job.get(i).getPartjobpeople()); hashMap.put("address", job.get(i).getPartjobaddress()); hashMap.put("payWay", job.get(i).getPartjobpayway()); going_Data.add(hashMap); } //Looper.loop(); } } }); OkHttpUtils.get("http://172.21.254.44:8080/portal/list.do?phone="+ CommonData.user_hashMap1.get("phone")+"&cond=已报名" , new OkHttpCallback() { @Override public void onFinish(String status, String msg) { super.onFinish(status, msg); //解析数据 Gson gson = new Gson(); List<Jianzhi> job = gson.fromJson(msg, new TypeToken<List<Jianzhi>>() {}.getType()); //Looper.prepare(); if (job.size() > 0) { for (int i = 0; i < job.size(); i++) { HashMap<String, Object> hashMap = new HashMap<String, Object>(); hashMap.put("id", job.get(i).getId()); hashMap.put("img", R.drawable.ic_launcher); hashMap.put("name", job.get(i).getPartjobname()); if (job.get(i).getId() < 100) { hashMap.put("jobType", "兼职"); } else { hashMap.put("jobType", "全职"); } hashMap.put("company", job.get(i).getPartjobcompany()); hashMap.put("time", job.get(i).getPartjobtime()); hashMap.put("salary", job.get(i).getPartjobsalary()); hashMap.put("people", job.get(i).getPartjobpeople()); hashMap.put("address", job.get(i).getPartjobaddress()); hashMap.put("payWay", job.get(i).getPartjobpayway()); over_Data.add(hashMap); } //Looper.loop(); } } }); } private void initView() { tv_start = (TextView) rootView.findViewById(R.id.tv_start); tv_going = (TextView) rootView.findViewById(R.id.tv_going); tv_over = (TextView) rootView.findViewById(R.id.tv_over); lv_task = (ListView) rootView.findViewById(R.id.lv_task); tv_start.setOnClickListener(this); tv_going.setOnClickListener(this); tv_over.setOnClickListener(this); adapter=new JobAdapter(getActivity(), start_Data); lv_task.setAdapter(adapter); // System.out.println(CommonData.user_hashMap1.get("phone")); } @Override public void onClick(View v) { setTextColor(); switch (v.getId()) { case R.id.tv_start: adapter=new JobAdapter(getActivity(), start_Data); lv_task.setAdapter(adapter); tv_start.setTextColor(getResources().getColor(R.color.basecolor)); break; case R.id.tv_going: adapter=new JobAdapter(getActivity(), going_Data); lv_task.setAdapter(adapter); tv_going.setTextColor(getResources().getColor(R.color.basecolor)); break; case R.id.tv_over: adapter=new JobAdapter(getActivity(), over_Data); lv_task.setAdapter(adapter); tv_over.setTextColor(getResources().getColor(R.color.basecolor)); break; } } //改变字体的背景颜色 public void setTextColor() { tv_start.setTextColor(getResources().getColor(R.color.text_color_primary)); tv_going.setTextColor(getResources().getColor(R.color.text_color_primary)); tv_over.setTextColor(getResources().getColor(R.color.text_color_primary)); } }
2.根据URL请求,在UserController中接收,并调用list方法处理
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20/* 利用findPhCon方法返回一个关于id的列表,然后遍历这个列表里的id,根据id去寻找对应的工作。 */ @RequestMapping(value = "list.do") public List<Jianzhi> list(String phone,String cond){ List<Integer> list1 = iJianzhiService.findbyPhCon(phone,cond); ArrayList<Jianzhi> arrayList = new ArrayList<Jianzhi>(); for(int i=0;i<list1.size();i++){ if(list1.get(i)<100){ Jianzhi jianzhi = iJianzhiService.selectByid(list1.get(i)); arrayList.add(jianzhi); }else{ Jianzhi quanzhi = iJianzhiService.selectByquanzhi(list1.get(i)); arrayList.add(quanzhi); } } return arrayList; }
3.在service中定义findbyPhCon来根据phone跟cond查找对应的id,并根据id的大小来调用不同的findbyid方法
复制代码
1
2
3
4
5
6
7
8//通过电话号码跟录取信息来获取id列表 List<Integer> findbyPhCon(String phone,String cond); //通过id找兼职 Jianzhi selectByid(int id); //通过id找全职 Jianzhi selectByquanzhi(int id);
4.在impl中重写上述的三种方法
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17@Override public List<Integer> findbyPhCon(String phone,String cond) { Userwork userwork = new Userwork(phone,cond); List<Integer> id = jianzhiMapper.findbyPhCon(userwork); return id; } @Override public Jianzhi selectByid(int id) { return jianzhiMapper.selectByid(id) ; } @Override public Jianzhi selectByquanzhi(int id) { return jianzhiMapper.selectByquanzhi(id) ; }
5.在jianzhimapper中定义上述的三种方法
复制代码
1
2
3
4
5
6
7
8//根据电话跟是否录用来找id List<Integer> findbyPhCon(Userwork userwork); //根据id来找工作 Jianzhi selectByid(int id); Jianzhi selectByquanzhi(int id);
V 我的功能
1.编辑ThreeFragment用于显示我的界面
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72@SuppressLint("NewApi") public class ThreeFragment extends Fragment implements View.OnClickListener { private View rootView; private TextView tv_person, tv_about, tv_loginout, tv_nickName; private ImageView iv_head; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (rootView == null) { rootView = inflater.inflate(R.layout.fragment_three, container, false); } return rootView; } public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initView(); } @Override public void onResume() { // TODO Auto-generated method stub super.onResume(); if (CommonData.isLogin) //如果登录了就将名字显示出来 tv_nickName.setText(CommonData.user_hashMap1.get("name").toString()); } private void initView() { tv_person = (TextView) rootView.findViewById(R.id.tv_person); tv_about = (TextView) rootView.findViewById(R.id.tv_about); tv_loginout = (TextView) rootView.findViewById(R.id.tv_loginout); tv_nickName = (TextView) rootView.findViewById(R.id.tv_nickName); iv_head=(ImageView)rootView.findViewById(R.id.iv_head); tv_person.setOnClickListener(this); tv_about.setOnClickListener(this); tv_loginout.setOnClickListener(this); iv_head.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.iv_head: if(CommonData.isLogin){ Intent intent = new Intent(getActivity(), PersonActivity.class); startActivity(intent); }else{ Intent intent=new Intent(getActivity(), LoginActivity.class); startActivity(intent); // Toast.makeText(getActivity(), "用户还未登录!", Toast.LENGTH_SHORT).show(); } break; case R.id.tv_person: if(CommonData.isLogin){ Intent intent = new Intent(getActivity(), PersonActivity.class); startActivity(intent); }else{ Toast.makeText(getActivity(), "用户还未登录!", Toast.LENGTH_SHORT).show(); } break; case R.id.tv_about: Intent intent = new Intent(getActivity(), AboutActivity.class); startActivity(intent); break; case R.id.tv_loginout: CommonData.isLogin = false; CommonData.user_hashMap=null; tv_nickName.setText("未登录"); Toast.makeText(getActivity(), "退出登录!", Toast.LENGTH_SHORT).show(); break; } } }
最后
以上就是鲤鱼可乐最近收集整理的关于Spring+安卓项目开发。已成功一、IDEA中使用SpringBoot来管理后端的请求,IDEA中的基本框架二.Adroid搭建三.安卓中实现的前端功能,以及IDEA中处理的后端请求的全部内容,更多相关Spring+安卓项目开发。已成功一、IDEA中使用SpringBoot来管理后端内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复