使用AJAX接收後端發出的資料
2017-12-05 20-17-48 的螢幕截圖.png
前端頁面寫的内容
//使用ajax輸出從背景擷取的資訊
<script type="text/javascript">
$(document).ready(function () {
$.post("/UserServlet?method=username",
function (data) {
console.log(data[0].u_userid)
//擷取input框id,通過id輸出内容
// $("#username1").val(data[0].u_userid);
// $("#username2").val(data[0].u_username);
//通過擷取input框的name,輸出内容
$("input[name='u_userid']").val(data[0]['u_userid']);
$("input[name='u_username']").val(data[0]['u_username']);
$("input[name='u_password']").val(data[0]['u_password']);
$("input[name='u_sex']").val(data[0]['u_sex']);
// $("input[name='u_class']").val(data[0]['u_class']);
},"json"
);
});
</script>
- input框的内容
賬号:<input type="text" name="u_userid" id="username1" val="" />
姓名:<input type="text" name="u_username" id="username2" val="" />
...
servlet代碼
2017-12-05 20-39-12 的螢幕截圖.png
protected void username(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
/*UserBean userBean = new UserBean();*/
List list = (List) request.getSession().getAttribute("info");
UserBean userBean = (UserBean) list.get(0);
int u_id = userBean.getU_id();
UserBean userBean1 = userService.username(u_id);
System.out.println(userBean1);
JSONArray jsonArray = JSONArray.fromObject(userBean1);
response.getWriter().print(jsonArray);
}
service
UserService userService = new UserServiceImpl();
UserBean username(int u_id);
serviceImpl
UserDao userDao =new UserDaoImpl();
@Override
public UserBean username(int u_id) {
return userDao.username(u_id);
}
dao
UserBean username(int u_id);
- daoImpl 2017-12-05 20-47-02 的螢幕截圖.png
public UserBean username(int u_id){
//在資料庫中查詢資訊
try{
UserBean userBean = new UserBean();
Connection conn = ConnUtil.getConnextion();
String changeSql = "select * from user WHERE u_id = ?";
PreparedStatement pstm = conn.prepareStatement(changeSql);
pstm.setInt(1, u_id);
ResultSet rs = pstm.executeQuery();
if(rs.next()) {
userBean.setU_userid(rs.getString(2));
userBean.setU_username(rs.getString(3));
userBean.setU_password(rs.getString(4));
userBean.setU_sex(rs.getString(5));
userBean.setU_img(rs.getString(6));
return userBean;
}
}catch (Exception e){
System.out.println(e);
}
return null;
}
使用session接收後端發出的資料
登入成功後資料庫的資訊就就已經存在了session中,隻需要在前端顯示頁面,即引入js接收即可:
如下所示:
<%
List list = (List) request.getSession().getAttribute("info");
UserBean userBean = (UserBean) list.get(0);
%>
.
.
.
使用者名:<input type="text" value="<%=userBean.getU_userid()%>"