1

Error: Property or field 'headUrl' cannot be found on null.

But I can't find null.I check my code ,still have no idea.

The result was there should be 10 news,other 9 news was normal ,the last has error,can't show show the URL correctly.

Here is the code(I don't know how to paste picture):

Home.html:

<div class="user-avatar"> <a href="/user/${vo.user.id}"> <img width="32" class="img-circle" th:src="${vo.user.headUrl}"> </a> </div> 

Class User:

private String headUrl; public User() {} public User(String name) { this.name = name; this.password = ""; this.salt = ""; this.headUrl = ""; } public String getHeadUrl() { return headUrl; } public void setHeadUrl(String headUrl) { this.headUrl = headUrl; } 

Database:

@Test public void contextLoads() { Random random = new Random(); for (int i = 1; i < 10; i++) { User user = new User(); user.setHeadUrl(String.format("http://images.nowcoder.com/head/%dt.png", random.nextInt(100))); user.setName(String.format("USER%d", i)); user.setPassword(String.format("PASSWORD--%d",i*i)); user.setSalt(String.format("SALT %d HelloWorld",i*5+20)); userDao.addUser(user); } } 

Main:

@RequestMapping(path = {"/", "/index"}, method = {RequestMethod.GET,RequestMethod.POST}) public String index(Model model){ List<News> newsList = newsService.getLatesNews(0, 0,10); List<Map> vos = new ArrayList<>(); for(News news :newsList){ Map<String, Object> vo = new HashMap<String, Object>(); vo.put("news",news); vo.put("user", userService.getUser(news.getUserId())); vos.add(vo); } model.addAttribute("vos", vos); return "home.html"; } 

Class UserService:

public class UserService { @Autowired private UserDao userDao; public User getUser(int id) return userDao.selectById(id);} 
1
  • Make sure that getUser doesn't return null. Commented Aug 2, 2017 at 15:28

1 Answer 1

1

You create a new vo (in the loop of news )and set the user but the user may be null (the userService.getUser(news.getUserId() maybe returns null).

If you want to display vo.user.headUrl even when the user is null then you can write this

vo?.user?.headUrl 

The above code with display user if it exists and it will display headUrl if it exists.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.