Search code examples
spring-mvcjspforeachjstl

dropdown list in JSP from database


I'm new to Spring, I fear this question may be duplicate, as there are numerous ways to do get resource from database to drop-down which I don't understand, so I'm asking if anyone can help me by fixing my code or with their own code which matches with mine as it'll be easy for me to learn.

My POJO

@Entity
@Table(name = "emp69")
public class Emp {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String name;
    private String designation;

....Constructor with name & designation field...

......getters method and setters method.....

My Repository

public interface EmpRepository extends JpaRepository<Employee, Integer> {
@Modifying
@Query(
        value = "select designation from employee",
        nativeQuery = true
)
List<String> designation();

}

My Data Access Object

@Service
public class EmployeeDao {
    @Autowired
    private EmpRepository repo;

    @Transactional
    public List<String> desig() {
        return repo.designation();
    }
}

My Controller

@Controller
public class EmployeeController {
    @Autowired
    EmployeeDao dao;

    @RequestMapping("/empform")
    public String showform(Model m) {
        List<String> designation= dao.designation();
        m.addAttribute("designation", designation);
        return "empform";
    }
}

My JSP page

<select>
    <c:forEach var="dd" items="${designation}">
        <option><c:set var="dd.designation">${dd.designation }</c:set></option>
    </c:forEach>
</select>

seems everything fine to me but when I execute, it gives

Property [designation] not found on type [java.lang.String]

error.

And on STS console

javax.el.PropertyNotFoundException: Property [designation] not found on type [java.lang.String]


Solution

  • Your Controller, Service & Repository part are correct but it seems like you haven't studied JSP well. I'll suggest you to take a step back from a big framework and individually learn each of its aspects first like JSP, JSTL, etc. Following this path will lead you to understanding of big frameworks and everything will be more clear.

    Anyhow here's your answer..

    <select>
        <c:forEach var="dd" items="${designation}">
            <option><c:set var="d" value="${dd}" /><c:out value="${d }"/></option>
        </c:forEach>
    </select>
    

    just replace this part in your code..

    Hope it helps