效果:
添加页面:
成功则跳转add页面,返回 save success
失败返回 save failed
查询全部页面
实现
项目结构
MainController代码
@Controller
@RequestMapping("/user")
public class MainController {
@Autowired
CityService cityService;
@RequestMapping("/list")
public String list(ModelMap map) {
List<City> cities = cityService.findAll();
map.addAttribute("list", cities);
return "list";
}
@RequestMapping("/add")
public String add(@RequestParam("id") Integer id, @RequestParam("name") String name, ModelMap map) {
String success = cityService.add(id,name);
map.addAttribute("flag", success);
System.out.println(success);
return "add";
}
@RequestMapping("/addPage")
public String addPage() {
return "add";
}
}
CityDao代码
@Repository
public class CityDao {
static Map<Integer, City> dataMap = Collections.synchronizedMap(new HashMap<Integer, City>());
public List<City> findAll() {
return new ArrayList<>(dataMap.values());
}
public void save(City city) throws Exception {
City data = dataMap.get(city.getId());
if (data != null) {
throw new Exception("Data is already exist");
} else {
dataMap.put(city.getId(), city);
}
}
}
City代码
public class City {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
CityService代码
@Service
public class CityService {
@Autowired
private CityDao cityDao = new CityDao();
public List<City> findAll() {
return cityDao.findAll();
}
public String add(Integer id, String name) {
City city = new City();
city.setId(id);
city.setName(name);
try {
cityDao.save(city);
return "save success";
} catch (Exception e) {
return "save failed";
}
}
}
add.html代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<span th:text="${flag}"></span>
<form action="add" method="post">
id: <input type="text" name="id">
name: <input type="text" name="name">
<input type="submit" value="提交">
</form>
</body>
</html>
list.html代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
</tr>
<tr th:each="var : ${list}">
<td th:text="${var.id}"></td>
<td th:text="${var.name}"></td>
</tr>
</table>
</body>
</html>