1

I am simply creating a CRUD Application in Spring MVC. I want to edit Student Details. I have created one form which is used to add student. How can I use the same form to populate the student details for editing it ?

Controller

@RequestMapping(value="/add", method = RequestMethod.GET)
public String addStudent(@RequestParam("studentName") String name,@RequestParam("studentId") String studId){
    System.out.println("Student Id : "+ studId);
    System.out.println("Student "+name+" added");
    list.add(name);
    return "redirect:get";
}

@RequestMapping(value="/edit/${index}", method = RequestMethod.GET)
public String editStudent(@PathVariable("index") int index, Model model){
    System.out.println("Edit Student with Index " + index);
    model.addAttribute("studentId",index);
    model.addAttribute("studentName",list.get(index));
    return "student";
}

Form

<c:url value="/students/add" var="addStudentAction"></c:url>
<form action="${addStudentAction}" method="get">
    <input type="hidden" name="studentId">
    <input type="text" name="studentName"></input>
    <input type="submit" name="submit" value="Add Student" />
</form>

I want to set studentId and studentName in form fields which are set in model in editStudent method.

Slava Semushin
  • 14,904
  • 7
  • 53
  • 69
  • Just for your information: for creating and editing it's much better to use POST method instead of GET. – Slava Semushin Jan 18 '17 at 11:26
  • The key is the usage of modelAttribute. Have a look here for instance http://www.arquitecturajava.com/spring-mvc-modelattribute/ – kimy82 Jan 18 '17 at 11:30

3 Answers3

1

What you're asking is a very basic question that ideally should be learned from the tutorials and documentation.

Here is a short list of the steps:

  • use Spring tags for rendering form (<form:form>, <form:input>, etc)
  • create an object that will represent form values and export it from the controller to the view
  • take this object as an argument in the controller's method that is handling form submission
Slava Semushin
  • 14,904
  • 7
  • 53
  • 69
0

I think you need two pages and one controller.
1. for list all students : index.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
    <h3>Student List</h3>
    <div>
        <p>
        <ul>
            <c:forEach items="${requestScope.students}" var="student">
                <li>
                    <c:out value="${student.id}"></c:out> |
                    <c:out value="${student.name}"></c:out> |
                    <a href="${pageContext.request.contextPath}/student/<c:out value='${student.id}'/>">edit</a>
                </li>
            </c:forEach>
        </ul>
        </p>
        <p><a href="${pageContext.request.contextPath}/student/new">Create Student</a></p>
    </div>
    </body>
    </html>
  1. for show or edit or create student: edit.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
    <c:if test="${student.id == null}">
        <h3>Student Create</h3>
    </c:if>
    <c:if test="${student.id != null}">
        <h3>Student Edit</h3>
    </c:if>
    <div>
        <form action="${pageContext.request.contextPath}/student/" method="post">
            <input type="hidden" name="id" value="<c:out value='${student.id}'/>"/>
            <p>Student Name: <input type="text" name="name" value="<c:out value='${student.name}'/>"></p>
            <p><input type="submit" value="submit"/></p>
        </form>
    </div>
    </body>
    </html>
    
  2. student controller

    package cn.kolbe.student;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.*;
    import org.springframework.web.servlet.ModelAndView;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.concurrent.ConcurrentHashMap;
    @Controller
    @RequestMapping("/student")
    public class StudentController {
        @GetMapping("")
        public ModelAndView index() {
            List<Student> students = new ArrayList<Student>();
            studentCache.keySet().forEach(id -> {
                students.add(studentCache.get(id));
            });
            return new ModelAndView("student/index", "students", students);
        }
        @GetMapping("/{id}")
        public ModelAndView show(@PathVariable("id")String id) {
            if (id.equals("new")) {
                return new ModelAndView("student/edit");
            } else {
                Student student = studentCache.get(Long.valueOf(id));
                return new ModelAndView("student/edit", "student", student);
            }
        }
        @PostMapping("")
        public String createOrEdit(String name, Long id) {
            Student student;
            if (id == null) {
                id = cacheId++;
                student = new Student(id, name);
                studentCache.put(id, student);
            } else {
                student = studentCache.get(id);
                student.setName(name);
            }
            return "redirect:/student";
        }
        private static ConcurrentHashMap<Long, Student> studentCache = new ConcurrentHashMap<>();
        private static Long cacheId = 1L;
    }
    
Slava Semushin
  • 14,904
  • 7
  • 53
  • 69
Kolbe
  • 18
  • 3
  • I believe that using scriptlets is a bad style and I would rather use `` instead. – Slava Semushin Jan 18 '17 at 14:28
  • Another possible issue here related to concurrency: because controller is a bean and by default it has `singleton` scope then it's possible that 2 and more threads will execute methods on the controller. Consider using `ConcurrentHashMap` instead of `HashMap`. – Slava Semushin Jan 18 '17 at 14:31
  • Another possible problem: using `${student.id}` in the HTML code is prone to XSS attacks. Consider using `` which escapes data before printing. – Slava Semushin Jan 18 '17 at 14:35
  • Hi Slava Semushin ,I agree with you. And edit the code already. Thank you! – Kolbe Jan 18 '17 at 16:03
  • Yet another issue is to replace `Long` by `AtomicLong` (http://stackoverflow.com/questions/35546956/what-is-atomiclong-in-java-used-for). – Slava Semushin Jan 18 '17 at 16:54
0

Don't use html <form> tag.

Use Spring tags for rendering form that is <form:form> ,<form:input>

Oliver
  • 1,218
  • 1
  • 17
  • 21
Sid
  • 1
  • 1
  • Welcome to Stack Overflow! Next time, please leave the unnecessarily formatting out of your answer, such as using capital and/or bold letters excessively. Highlight only your single most important sentence or points. – Oliver Feb 09 '19 at 19:36