build.gradle
dependencies {
compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile('org.springframework.boot:spring-boot-starter-thymeleaf')
compile('org.springframework.boot:spring-boot-starter-web')
providedRuntime('org.springframework.boot:spring-boot-starter-tomcat')
compile('mysql:mysql-connector-java')
}
It is convenient to pack in a session to carry around login information
@SessionScope
@Component
public class AccountModel {
private String id;
private String name;
}
@Controller
public class MainController {
@Autowired
private AccountModel accountModel;
/**
* Login process
* @param model
* @param id
* @param post
* @return
*/
@RequestMapping("login")
public String login(Model model,@RequestParam("id") String id,@RequestParam("pass") String pass) {
accountModel.setId(id);
// TODO password check
return "shop";
}
}
<form method="post" th:action="@{login}">
<input type="text" name="id" />
<input type="text" name="pass" />
<button> Login </ button>
</form>
With this, you can check it every time you log in for the first time. If you do not check and retain the session information at the time of purchase, you can move to the personal information registration screen.
See below for the naming rules for methods that are automatically implemented in SpringDataJPA. [Spring Data JPA] Naming rules for automatically implemented methods
@Entity
@Table(name="item")
public class Item {
@Id
@GeneratedValue
private int id;
private String name;
private int price;
}
public interface ItemRepos extends JpaRepository<Item, Integer> {
/**
* select * from item where name like %{name}%
* @param name
* @return
*/
public List<Item> findByNameContains(String name);
}
@Controller
public class MainController {
@Autowired
private ItemRepos itemRepos;
/**
* Search process
* @param model
* @param name
* @return
*/
@RequestMapping("search")
public String search(Model model,@RequestParam("name") String name) {
List<Item> itemList = itemRepos.findByNameContains(name);
model.addAttribute("itemList", itemList);
return "shop";
}
}
<form method="post" th:action="@{search}">
<input type="text" name="name"/>
<button> Search </ button>
</form>
JpaRepository # save performs update if pk is duplicated, insert if not
/**
* registration process
* @param model
* @param name
* @param price
* @return
*/
@RequestMapping("submit")
public String submit(Model model,@RequestParam("name") String name,@RequestParam("price") String price) {
Item item = new Item();
item.setName(name);
item.setPrice(Integer.valueOf(price));
itemRepos.save(item);
return "shop";
}
Since we are assuming training this time, we have not implemented detailed parts, but there are many points to consider such as input value check and separation of processing layer.
Recommended Posts