在我的 servlet 中,我有以下方法:
private void showUserReservations(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException, ServletException {
String username = null;
HttpSession session = request.getSession();
if (session.getAttribute("loggedUser") != null) {
username = (String) session.getAttribute("loggedUser");
}
// get data from DB
List<Operation> userReservations = operationsDbUtil.getUserReservations(username);
if (userReservations != null) {
request.setAttribute("AVAILABLE_DATA", userReservations);
response.getWriter().write(gson.toJson(userReservations));
}
}
我必须在我的 android应用中获取这些数据,以填充片段中的ListView。如果我在不需要会话属性的方法上运行我的android代码,则会正确获取数据。当我运行此showUserReservations()方法时,就会出现问题,因为该servlet无法检索loggingUser属性。
通过遵循本指南Shared Preferences to keep the user logged in,我使我的用户使用共享的首选项进行登录,但是,如何让servlet知道哪个用户正在发出请求?有没有办法发送保存在共享首选项中的用户名,所以这部分代码
if (session.getAttribute("loggedUser") != null) {
username = (String) session.getAttribute("loggedUser");
}
可以正常运行吗?
与servlet通信的Android代码
private String strUrl = null;
private String jsonString = null;
View view;
ListView listView;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_my_reservations, container, false);
Button btn = view.findViewById(R.id.jsonBtn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showJson(view);
}
});
return view;
}
public void showJson(View view) {
new FillListTask().execute();
}
public class FillListTask extends AsyncTask<Void, Void, String> {
@Override
protected void onPreExecute() {
strUrl = "http://xxx.xxx.x.x./xxxxxxxxxxx;
}
@Override
protected void onPostExecute(String result) {
TextView textView = view.findViewById(R.id.tvJson);
textView.setText(result);
}
@Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(strUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((jsonString = bufferedReader.readLine()) != null) {
stringBuilder.append(jsonString + "\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (IOException exception) {
System.out.println(exception.getMessage());
}
return null;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
}
像这样,我可以从不需要session属性的方法中从servlet中获取数据。