使用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()%>"