dlinx90
dlinx90

Reputation: 875

How to populate dropdown box in Spring MVC

I have been trying to find out how to populate a dropdown box in Spring MVC. There are a few threads out there on this subject but none of them that I have found have helped me so I'm hoping someone here can help me out.

Here is my controller:

@Controller
@RequestMapping("/document-revision") 
public class DocumentRevisionController {


@Autowired
private DocumentRevisionService documentRevisionService;
private DocumentService documentService;

@RequestMapping(value="/list", method=RequestMethod.GET) 
public String getDocumentRevisionList(Model model) {
    List<DocumentRevision> documentRevisions = documentRevisionService.retrieveAllDocumentRevisions();
    model.addAttribute("documentRevisions", documentRevisions);

    return "document-revision";
}

@RequestMapping(value="/add", method=RequestMethod.GET)
public String getDocumentRevision(Model model) {
    DocumentRevision documentRevision = new DocumentRevision();
    model.addAttribute("documentRevisionAttribute", documentRevision);
    return "new-documnent-revision";
}


@RequestMapping(value="/add", method=RequestMethod.POST)
public String postDocumentRevision(@ModelAttribute("documentRevisionAttribute") @Valid DocumentRevision documentRevision, BindingResult result) {

    if(result.hasErrors()){
        return "new-document-revision";
    }

    documentRevisionService.createDocumentRevision(documentRevision);
    return "redirect:/testapp/document-revision/list";  
}

}

and here is the jsp page:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
        <style>
        .error { color: red; }
        </style>
</head>
<body>

    <h1>Create New Document Revision</h1>

    <c:url var="saveUrl" value="/testapp/document-revision/add" />
    <form:form modelAttribute="documentRevisionAttribute" method="POST" action="${saveUrl}">
        <table>
            <tr>
                <td>DocumentNumber</td>
                <td><form:select path="document_number">
                    <form:option value="NONE" label="--- Select ---" />
                    <form:options items="${documentNumberList}" />
                    </form:select>
                </td>
                <td><form:errors path="document_number" cssClass="error" /></td>
            </tr>


            <tr>
                <td><form:label path="documentRState">Document R-State</form:label></td>
                <td><form:input path="documentRState"/></td>
                <td><form:errors path="documentRState" cssClass="error"/></td>
            </tr>

        </table>

        <input type="submit" value="Save" />
    </form:form>

</body>
</html>

I have tried adding a @ModelAttribute method which retrieves the document numbers,

        @ModelAttribute
    public List<Document> documentNumberList(){
        return documentService.retrieveAllDocumentNumbers();
    }

but it gave me errors. Is there anyone who knows how it should be done?

Thank you for your time

/D

Edit I thought I'd clarify that my wish is to have a dropdown box for the document numbers which are retrieved by the documentService.

Edit 2 Here is the error log as requested:

java.lang.NullPointerException
testapp.controller.DocumentRevisionController.documentNumberList(DocumentRevisionController.java:33)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:212)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
org.springframework.web.method.annotation.ModelFactory.invokeModelAttributeMethods(ModelFactory.java:123)
org.springframework.web.method.annotation.ModelFactory.initModel(ModelFactory.java:97)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:614)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:900)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:827)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

Solution I thought I would add the complete controller code that works in case there are others who could benefit from it:

@Controller
@RequestMapping("/document-revision") 
public class DocumentRevisionController {


@Autowired
private DocumentRevisionService documentRevisionService;

@Autowired
    private DocumentService documentService;

@RequestMapping(value="/list", method=RequestMethod.GET) 
public String getDocumentRevisionList(Model model) {
    List<DocumentRevision> documentRevisions = documentRevisionService.retrieveAllDocumentRevisions();
    model.addAttribute("documentRevisions", documentRevisions);

    return "document-revision";
}

@RequestMapping(value="/add", method=RequestMethod.GET)
public String getDocumentRevision(Model model) {
    DocumentRevision documentRevision = new DocumentRevision();
    model.addAttribute("documentRevisionAttribute", documentRevision);
    model.addAttribute("documentNumberList", documentService.retrieveAllDocumentNumbers());

    return "new-documnent-revision";
}


@RequestMapping(value="/add", method=RequestMethod.POST)
public String postDocumentRevision(@ModelAttribute("documentRevisionAttribute") @Valid DocumentRevision documentRevision, BindingResult result) {

    if(result.hasErrors()){
        return "new-document-revision";
    }

    documentRevisionService.createDocumentRevision(documentRevision);
    return "redirect:/testapp/document-revision/list";  
}

}

Upvotes: 11

Views: 53701

Answers (3)

user2335476
user2335476

Reputation: 81

I have solved this kind of problem today by myself. This is very simple and easy to understand. In Spring MVC 3.0 controller just place this code -

 @ModelAttribute("creditCardTypes")
 public Map<String,String> populateCreditCardTypes() {
        Map<String,String> creditCardTypes = new LinkedHashMap<String,String>();
        creditCardTypes.put("VS", "Visa");creditCardTypes.put("MC", "MasterCard");
        creditCardTypes.put("AE", "American Express");
        creditCardTypes.put("DS", "Discover");creditCardTypes.put("DC", "Diner's Club");                
        return creditCardTypes;
    }

Now "creditCardTypes" attribute will be avaiable in the page loading or page submitting scope , means it will available whatever the requestmapping url would be.

In jsp , place this code inside the - Credit card types:

<form:select path="creditCardType">
    <option value="Select" label="Select a card type"></option>
    <form:options items="${creditCardTypes}" />
</form:select> 

here , path="creditCardType" means the attribute in the Spring MVC model/command object, items="${creditCardTypes}" means all the populated credit card types will be available in "creditCardTypes" ModelAttribute. Thats it !!!

Upvotes: 8

Sanath
Sanath

Reputation: 4886

@ModelAttribute("numberList")
public List<Document> documentNumberList(){
    List<LabelValue> selectItems = new ArrayList<LabelValue>();
    List<Document> docList = documentService.retrieveAllDocumentNumbers();
    for (Document doc : docList) {
     selectItems.add(new LabelValue(doc.id,doc.value));
}
    return selectItems;
}

FYI LabelValue class is a simple DTO that we use to carry the drop down label and value items. It will have a label and value attribute, and the corresponding getters/setters.

LabelValue.java

 private String lable;
 private String value;

 //getters/setters

---- JSP -----

<tr>
    <td>DocumentNumber</td>
    <td><form:select id="docNo" path="document_number">
           <form:option value="NONE" label="--- Select ---" />
           <form:options items="${numberList}" itemValue="value" itemLabel="lable"/>
         </form:select>
    </td>
    <td><form:errors path="document_number" cssClass="error" /></td>
</tr>

hope this helps..

Upvotes: 9

Eugene Kuleshov
Eugene Kuleshov

Reputation: 31795

Not sure what Controller method is called to show your view with documentNumberList, but you need to add that collection to the model passed to this view:

model.addAttribute("documentNumberList", documentService.retrieveAllDocumentNumbers());

Though from your exception stack trace you also missed an @Autowired on documentService field.

Upvotes: 8

Related Questions