9月12日

ツイートを投稿する処理の実装

MyController.java

	@RequestMapping(value = "/tweet", method = RequestMethod.POST)
	public ModelAndView tweet(ModelAndView mav,
			@ModelAttribute("tweet") @Validated Tweet tweet,
			Errors errors,
			Principal p) {
		if (errors.hasErrors()) {
			mav.setViewName("mypage");
			mav.addObject("msg", "エラーです");
			return mav;
		}

		return new ModelAndView("redirect:/mypage");
	}

どのような情報がTweetに入っているかを確認するため、TweetにtoString()メソッドを追加する。

Tweet.java

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder
			.append("Tweet [id=").append(id)
			.append(", content=").append(content)
			.append(", time=").append(time)
			.append(", profile=").append(profile)
			.append("]");
		return builder.toString();
	}

コントローラからTweetをコンソールに出力してみる。

MyContoller.java

	@RequestMapping(value = "/tweet", method = RequestMethod.POST)
	public ModelAndView tweet(ModelAndView mav,
			@ModelAttribute("tweet") @Validated Tweet tweet,
			Errors errors,
			Principal p) {
		if (errors.hasErrors()) {
			mav.setViewName("mypage");
			mav.addObject("msg", "エラーです");
			return mav;
		}
		System.out.println(tweet);
		return new ModelAndView("redirect:/mypage");
	}

Tweetに現在時刻とProfileを設定する。

	@RequestMapping(value = "/tweet", method = RequestMethod.POST)
	public ModelAndView tweet(ModelAndView mav,
			@ModelAttribute("tweet") @Validated Tweet tweet,
			Errors errors,
			Principal p) {
		if (errors.hasErrors()) {
			mav.setViewName("mypage");
			mav.addObject("msg", "エラーです");
			return mav;
		}
		Optional<Profile> data = repository.findByUsername(p.getName());
		tweet.setProfile(data.get());
		tweet.setTime(new Date());
		System.out.println(tweet);
		return new ModelAndView("redirect:/mypage");
	}

Tweetをデータベースに保存するために、リポジトリを作成する。

TweetRepository.java

package jp.abc;

import org.springframework.data.jpa.repository.JpaRepository;

public interface TweetRepository extends JpaRepository<Tweet, Long> {

}

リポジトリを作成したので、コントローラからデータベースに保存する。
リポジトリをインスタンス変数として追加し、@AutowiredアノテーションをつけてDIしてもらう。

MyController.java

@Controller
public class MyController {
	@Autowired
	private JdbcUserDetailsManager userManager;
	@Autowired
	private ProfileRepository repository;
	@Autowired
	private TweetRepository tweetRepository;
	@RequestMapping(value = "/tweet", method = RequestMethod.POST)
	public ModelAndView tweet(ModelAndView mav,
			@ModelAttribute("tweet") @Validated Tweet tweet,
			Errors errors,
			Principal p) {
		if (errors.hasErrors()) {
			mav.setViewName("mypage");
			mav.addObject("msg", "エラーです");
			return mav;
		}
		Optional<Profile> data = repository.findByUsername(p.getName());
		tweet.setProfile(data.get());
		tweet.setTime(new Date());
		System.out.println(tweet);
		tweetRepository.saveAndFlush(tweet);
		return new ModelAndView("redirect:/mypage");
	}

mypage にツイート一覧を表示できるように、コントローラからModelAndViewに渡しておく。

MyController.java

	@RequestMapping(value = "/mypage")
	public ModelAndView top(ModelAndView mav, Principal p) {
		mav.setViewName("mypage");
		mav.addObject("username", p.getName());
		Optional<Profile> data = repository.findByUsername(p.getName());
		Profile profile;
		if (!data.isPresent()) {
			profile = new Profile();
			profile.setUsername(p.getName());
			repository.saveAndFlush(profile);
		} else {
			profile = data.get();
		}
		mav.addObject("profile", profile);
		List<Tweet> list = tweetRepository.findAll();
		mav.addObject("datalist", list);
		return mav;
	}

mypage にツイート一覧を表示する。

mypage.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>login</title>
</head>
<body>
<h1>マイページ</h1>
<p>ようこそ、<span th:text="${username}"></span>さん!</p>
<p th:text="${profile.username}"></p>
<form th:action="@{/tweet}" th:object="${tweet}" method="post">
	<textarea name="content" cols="40" rows="10"></textarea>
	<br />
	<input type="submit" value="ツイートする" />
</form>
<form th:action="@{/logout}" method="post">
	<input type="submit" value="ログアウト" />
</form>

<hr />
<table>
	<tr>
		<th>名前</th><th>日時</th><th>投稿内容</th>
	</tr>
	<tr th:each="obj : ${datalist}">
		<td th:text="${obj.profile.username}"></td>
		<td th:text="${obj.time}"></td>
		<td th:text="${obj.content}"></td>
	</tr>
</table>

</body>
</html>

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください