最近,在寫一段用戶的代碼,要求使用springmvc, RowMapper,jdbcTemplate的技術,我的代碼段如下:
jsp頁面
users.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<table>
<c:if test="${not empty userlist}">
<c:forEach var="s" items="${userlist}" varStatus="status">
<thead>
<tr><td>用戶姓名</td><td>用戶密碼</td></tr>
</thead>
<tbody>
<tr><td>${s.user_name}</td><td>${s.user_pwd}</td></tr>
</tbody>
</c:forEach>
</c:if>
</table>
</body>
</html>
HelloController.java
@RequestMapping("/howareyou.do")
public String getUserbyUserId(Model model,HttpServletRequest req){
Long userid=(long) Integer.parseInt(req.getParameter("user_id"));
List<User> users = userService.findAllByUserId(userid);
model.addAttribute("userlist",users);
return "users";
}
UserServiceImplement.java
@Override
public List<User> findAllByUserId(Long user_id) {
// TODO Auto-generated method stub
String sql = "select * from user where user_id = ?";
Object[] params = new Object[] {user_id};
BeanPropertyRowMapper<User> UserRowMapper = new BeanPropertyRowMapper<User>(User.class);
List<User> users = null;
/**
* 使用接口實現類
*/
users = jdbcTemplate.query(sql, params, UserRowMapper);
/**
* 使用匿名內部類
* 如果UserRowMapper類只使用一次,單獨為其創建一個類多余,可以使用匿名類
* 省略了書寫一個實現類
*/
users = jdbcTemplate.query(sql, params,
new RowMapper<User>() {
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
/*user.setUser_id(Long.parseLong(String.valueOf(rs.getInt("user_id"))));*/
user.setUser_name(rs.getString(3));
user.setUser_pwd(rs.getString(2));
System.out.println("user_name is"+user.getUser_name());
System.out.println("user_pwd is"+user.getUser_pwd());
System.out.println("user_id is"+user.getUser_id());
return user;
}
});
return (users != null && users.size() > 0) ? users : null;
}
我用斷點進入,發現在serviceImplement層,users是有值的,分別取到一個用戶user的username和user_pwd的2個屬性,可是到了jsp層,為何出現的是com.frame.model.User@123456的輸出結果?而且,頁面沒有輸出值。請教,應該如何寫才好?謝謝!
各位,經過我的仔細排查,終於發現此代碼其實沒有錯誤,實際是因為,jsp頁面沒有導入<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 這句話的緣故。問題終於解決了。