Ниже представлен контроллер todo, который я использую для добавления, удаления и обновления todo.Это простое приложение с весенней загрузкой, для которого я использую sprint boot starter web.
TodoController
package com.Mayur.Controller;
import com.Mayur.Model.Todo;
import com.Mayur.Service.ToDoService;
import com.Mayur.Service.ValidationCheck;
import org.apache.log4j.Logger;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
@Controller
@SessionAttributes("name")
public class ToDoController {
private final static Logger log = Logger.getLogger(ToDoController.class);
@Autowired
ToDoService todd;
@InitBinder
public void init(WebDataBinder web)
{
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
web.registerCustomEditor(Date.class,new CustomDateEditor(sdf,false));
}
@RequestMapping(value = "/listtodos")
public String listTodos(ModelMap m) {
List<Todo> todos = todd.retrieveToDo();
String kk =(String)m.get("name");
m.put("l",kk);
m.put("td",todos);
return "listtodos";
}
@RequestMapping(value ="/addTodo")
public String addTodo(ModelMap map){
map.put("todo",new Todo(0,(String)map.get("name"),"",new Date(),false));
return "addTodo";
}
@RequestMapping(value ="/addTodo",method = RequestMethod.POST)
public String addTodoNew(ModelMap map, @Valid Todo tod, BindingResult bindingResult){
System.out.println("server restarted");
if(bindingResult.hasErrors())
{
return "/addTodo";
}
System.out.println("Tod is :"+tod);
List<Todo> tdlist= todd.addTodo(tod);
map.put("addList",tdlist);
return "redirect:/listtodos";
}
@RequestMapping(value="/delete")
public String delete(@RequestParam int id,ModelMap m)
{
List<Todo> tdlist = todd.retrieveToDo();
log.info(tdlist);
tdlist.removeIf(i->i.getId()==id);
m.put("td",tdlist);
m.put("message","Deleted Sucessfully");
log.info(tdlist);
return "listtodos";
}
@RequestMapping(value="/update")
public String updateTodo(@RequestParam int id,Model m)
{
m.addAttribute("registerId",id);
return "updateTodo";
}
@RequestMapping(value="/updateTodos")
public String updateTodos(@RequestParam String name,Model m)
{
m.addAttribute("paramcheck",name);
log.info("parameter is : "+name);
return "updateTodos";
}
@RequestMapping(value="/updateTodos",method = RequestMethod.POST)
public String finalUpdate(@RequestParam int id,@RequestParam String name,@RequestParam Object updateField, ModelMap mp)
{
List<Todo> to = todd.retrieveToDo();
List<Todo> newTodo=to.stream().filter(i->i.getId()==id).map(v->{
if(name.equalsIgnoreCase("Desc"))
{
v.setDesc((String)updateField);
}
else if(name.equalsIgnoreCase("user"))
{
v.setUser((String)updateField);
}
else if(name.equalsIgnoreCase("status"))
{
v.setDone(updateField.equals("active")?true:false);
}
return v;
}).collect(Collectors.toList());
log.debug("list :"+newTodo);
System.out.println("list "+newTodo);
System.out.println("coming to update todo controller");
mp.put("td",newTodo);
return "redirect:/listtodos";
}
}
Ниже приведена страница jsp, где я отображаю весь список задач.
listtodos. jsp
<%@ include file="common/header.jspf"%>
<%@ include file="common/navigation.jspf"%>
<div class ="container">
<font color ="blue">${message}</font>
<table class ="table table-striped">
<tr>
<th style ="color:blue">User Id</th>
<th style ="color:blue">User Name</th>
<th style ="color:blue">Description</th>
<th style ="color:blue">Date</th>
<th style ="color:blue">Status</th>
<th style ="color:blue">Delete</th>
<th style ="color:blue">Update</th>
</tr>
<tr>
<c:forEach items = "${td}" var="s">
<td>${s.getId()}</td>
<td>${s.getUser()}</td>
<td>${s.getDesc()}</td>
<td><d:formatDate value ="${s.getDate()}" pattern="dd/MM/yyyy"/></td>
<td>${s.isDone()}</td>
<td><a type="button" class="btn btn-warning" href="/delete?id=${s.getId()}"/>Delete</td>
<td><a type ="button" class="btn btn-success" href="/update?id=${s.getId()}"/>Update</td>
</tr>
</c:forEach>
</table>
<div><a href ="/addTodo">Add new todo </a></div>
<%--<div><a href ="/deleteTodo">Delete Todo</a></div>--%>
<%@ include file="common/footer.jspf"%>
Обновление задачи, где я даю пользователю выбор, что он хочет обновить и идентификатор задачи, который я передаю из списка задач. jsp
UpdateTodo. jsp
<html>
<title>
Login Application
</title>
<link href="webjars/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<body>
<div class="container">
What do you want to update :
<a type ="button" href="/updateTodos?name=user&id=${registerId}">User</a>
<a type ="button" href="/updateTodos?name=desc&id=${registerId}">Description</a>
<a type ="button" href="/updateTodos?name=date&id=${registerId}">Date</a>
<a type ="button" href="/updateTodos?name=status&id=${registerId}">Status</a>
</div>
<script src="webjars/jquery/1.9.1/jquery.min.js"></script>
<script src="webjars/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>
update todos jsp where i am actually updating something in the todo
updateTodos. jsp
<html>
<title>
Login Application
</title>
<link href="webjars/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<body>
<script>
console.log("coming to jsp");
</script
<form method="post">
<div class="container">
<fieldset class="form-group">
<label>Enter the ${paramcheck}:</label>
<input type="text" name="updateField"/><br>
<input type="submit" value="update"/>
</fieldset>
</div>
<script src="webjars/jquery/1.9.1/jquery.min.js"></script>
<script src="webjars/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</form>
</body>
</html>
Below is pom.xml i am using for this project
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.Mayur</groupId>
<artifactId>SpringLoginApplication</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.3.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>default</scope>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.6</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap-datepicker</artifactId>
<version>1.0.1</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>1.9.1</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.26.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
</dependencies>
</project>
Но когда я нажимаю на обновление. Это не касается моего запроса на обновление в контроллере todo.