Can not populate drop down list using hibernate query in spring mvc - spring

Here is my controller. In this I am using the reference data to send the List to my JSP page. Read the list into countryList which contains list of all country names populated using hibernate query
#SuppressWarnings("deprecation")
public class customerController extends SimpleFormController {
public customerController() {
setCommandClass(customer.class);
setCommandName("customer");
}
private customerDAO customerDAO;
public void setcustomerDAO(customerDAO customerDAO) {
this.customerDAO = customerDAO;
}
#Override
protected ModelAndView onSubmit(Object command) throws Exception {
customer customer = (customer) command;
customerDAO.savecustomer(customer);
return new ModelAndView("customerSuccess");
}
#Override
protected Map referenceData(HttpServletRequest request) throws Exception {
Map referenceData = new HashMap();
List countryList = customerDAO.listCountries();
referenceData.put("country", countryList);
return referenceData;
}
public ModelAndView redirect(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelMap modelMap = new ModelMap();
return new ModelAndView("customer", modelMap);
}
}
Here is my DAO implementation:
public class customerDAOImpl implements customerDAO {
private HibernateTemplate hibernateTemplate;
public void setSessionFactory(SessionFactory sessionFactory) {
this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}
#Override
public void savecustomer(customer customer) {
hibernateTemplate.saveOrUpdate(customer);
}
#Override
#SuppressWarnings("unchecked")
public List<customer> listcustomer() {
return hibernateTemplate.find("from customer");
}
#Override
#SuppressWarnings("unchecked")
public List<countries> listCountries() {
return hibernateTemplate.find("from customer.countries");
}
}
Here is my JSP code:
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<form:form commandName="customer" name="customer" method="post">
<tr>
<td align="right" class="para">Country:</td>
<td align="left"><span id="spryselect2">
<form:select path="country" id="country">
<form:options items="${country}" itemValue="country_id" itemLabel="name" />
</form:select>
<span class="selectRequiredMsg">Please select country.</span></span></td>
</tr>
But nothing is getting populated into the drop down.

Name the list of countries something representing multiple countries, like, say, "countries".
There's also a customer country property.

Related

Spring mvc jsp not rendering

Getting started with Spring MVC, when I enter my page it loads the welcome.jsp as plain text(just shows source), I know people asked this 1 million times, But I looked over many of the questions and didn't find my solution as most of them using XML and I use java.. I am still not experienced enough to switch between the two.
conf.class :
public class conf extends WebMvcConfigurerAdapter {
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Bean
public InternalResourceViewResolver jspViewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/views/");
bean.setSuffix(".jsp");
return bean;
}
}
ServletInitializer.class:
public class ServletInitializer extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Demo4Application.class,conf.class);
}
}
welCont.class (Controller) :
#Controller
#RequestMapping("/spring/")
public class welCont {
#RequestMapping(method = RequestMethod.GET)
public String wel(ModelMap model)
{
model.addAttribute("test","testme");
return "welcome";
}
}
welcome.jsp :
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h2>${test}</h2>
</body>
</html>
I think wrong thing is
#RequestMapping("/spring/")
normally "/spring/" request should go to DispatcherServlet. Not sure in spring boot.
try with this.
#Controller
public class WelCont {
#RequestMapping(value="/foldername_if_avaiable/welcome/", method=RequestMethod.GET )
public ModelAndView wel(
#RequestParam(value="id", required=false) String id,
ModelMap model,
HttpSession session,
HttpServletRequest req) throws Exception {
model.addAttribute("test","testme");
return new ModelAndView("/foldername_if_avaiable/welcome", model);
}
}
reference

Spring mvc 4 can't render jsp

I'm trying to learn Spring MVC 4 without using the web.xml but instead use the following:
public class WebAppInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
WebApplicationContext context = getContext();
servletContext.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("*.html");
}
private AnnotationConfigWebApplicationContext getContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setConfigLocation("com.bookstr.WebConfig");
return context;
}
}
and
#Configuration
#EnableWebMvc
#ComponentScan({ "com.bookstr.*" })
public class WebConfig {
}
For some reason the home.jsp file I have created and placed in the src->main->webapp folder will not be rendered when I use the following controller:
#Controller
public class HomeController {
#RequestMapping(value = "/home", method = RequestMethod.GET)
public String getHome(Model model){
model.addAttribute("home", "Hello world");
return "home";
}
}
And the JSP file is the following:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Home</title>
</head>
<body>
${home}
</body>
</html>
Update!
Folder structure as requested.
I can see that the HomeController is not getting called.
Register a ViewResolver in your WebConfig:
#Configuration
#EnableWebMvc
#ComponentScan("com.bookstr")
public class WebConfig {
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResover = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
This way, when you return the home from your controller, it will try to render the /WEB-INF/views/home.jsp view. For configuring DispatcherServlet programtically, it's easier to use AbstractAnnotationConfigDispatcherServletInitializer. For example, you simply can:
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/*.html" };
}
}

Not showing error message in form(jsp)

I have a problem with showing error message in my form(jsp form).
I create a validator, and want to see errors (if exists) in my form, but the errors not showing, what's problem?
Part of form
<form:form method="POST" action="/regStoreSuccessful" commandName="storeForm">
<table>
<tr>
<td><form:label path="name">Store name</form:label></td>
<td><form:input path="name" /></td>
<td><form:errors path="name" cssclass="error"/></td>
</tr>
Validator
public class StoreValidator implements Validator {
#Override
public boolean supports(Class<?> clazz) {
return Store.class.equals(clazz);
}
#Override
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "name.empty", "Name field is empty");
}
}
Controller
#Autowired
private StoreValidator storeValidator;
#InitBinder
protected void initBinder(WebDataBinder binder) {
binder.setValidator(storeValidator);
}
//get method
#RequestMapping(value = "/regStore", method = RequestMethod.GET)
public ModelAndView addStore() throws SQLException {
ModelAndView modelAndView = new ModelAndView("Store/regStore", "storeForm", new Store());
}
//post method
#RequestMapping(value = "/regStoreSuccessful", method = RequestMethod.POST)
public ModelAndView addStorePost(#Valid #ModelAttribute("storeForm") Store storeForm, BindingResult bindingResult, Principal principal) throws SQLException {
ModelAndView modelAndView = new ModelAndView("redirect:body");
if(bindingResult.hasErrors()) {
modelAndView.addObject("errors", bindingResult.getAllErrors());
return new ModelAndView("redirect:regStore");
}
storeService.addStore(storeForm);
return modelAndView;
}
The model attributes won't be available after redirect, you should use RedirectAttributes redirectAttrs and store errors as flash attributes, that way attributes will be available after the redirect and removed immediately after used, so change your method to
//post method
#RequestMapping(value = "/regStoreSuccessful", method = RequestMethod.POST)
public ModelAndView addStorePost(#Valid #ModelAttribute("storeForm") Store storeForm, BindingResult bindingResult, Principal principal, , RedirectAttributes redirectAttrs) throws SQLException {
ModelAndView modelAndView = new ModelAndView("redirect:body");
if(bindingResult.hasErrors()) {
redirectAttrs.addFlashAttribute("errors", bindingResult.getAllErrors());
return new ModelAndView("redirect:regStore");
}
storeService.addStore(storeForm);
return modelAndView;
}

Invalid target for Validator in spring error?

Hi all I am getting the following error whenever I am trying to invoke validator in my spring
Servlet.service() for servlet spring threw exception: java.lang.IllegalStateException: Invalid target for Validator
Please have a look and help me out in this error, previously I user the validation for login page and it is working fine but now its not working.
Here is my code snippet .
Controller
#Controller
public class NewUserRegistration
{
#Autowired
private UserService userService;
#Autowired
private NewUserValidator newUserValidator;
#InitBinder
public void initBinder(WebDataBinder binder)
{
binder.setValidator(newUserValidator);
}
#RequestMapping(value="/newUserAdd", method=RequestMethod.POST)
public String addUser(#ModelAttribute("user")#Valid User user,BindingResult result, Model model)
{
return "NewUser";
}
}
Validator
#Component
public class NewUserValidator implements Validator
{
#Override
public boolean supports(Class<?> classz)
{
return NewUserRegistration.class.equals(classz);
}
#Override
public void validate(Object obj, Errors error)
{
//Validation login for fields
}
}
JSP Page
<form:form action="newUserAdd" method="POST" modelAttribute="user">
<center>
<table>
<tr><td>User Id:</td><td><input name="userId" type="text" /></td><td><font color="red"><c:out value="${userIdError}" /></font> </td></tr>
<tr><td>Password:</td><td><input name="userPassword" type="password"/></td><td><font color="red"><c:out value="${userPasswordError}" /></font></td></tr>
<tr><td>Confirm Password:</td><td><input name="userConfirmPassword" type="password"/></td><td><font color="red"><c:out value="${userPasswordError}" /></font></td></tr>
<tr><td>Name:</td><td><input name="userName" type="text"/></td><td><font color="red"><c:out value="${userPasswordError}" /></font></td></tr>
<tr><td></td><td><input type="submit" value="Create"/></td></tr>
</table>
</center>
</form:form>
The problem is actually in Validator class you are using NewUserRegistration's object which is wrong because you want to validate your User's object not your NewUserRegistration's object.
#Override
public boolean supports(Class<?> classz)
{
return NewUserRegistration.class.equals(classz);
}
which should be
#Override
public boolean supports(Class<?> classz)
{
return User.class.equals(classz);
}

MVC, Servlets, JSP, No Output

I'm trying to learn Servlets/JSP. When I tried the following code I dont get any output. Can someone please help me? When I run the code I get only the header and I dont see the values showing up in the dropdown.
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class VacationTrackerDAO {
public static List<VactionTrackerBean> list() throws SQLException{
List<VactionTrackerBean> appr= new ArrayList<VactionTrackerBean>();
try{
DBConnection conObj=new DBConnection();
Connection dbCon= conObj.getCon();
Statement stmt=conObj.getStmt();
String queryCPList="select * from Capacity_Plan";
String queryApprList="Select First_Last_Name from Vacation_Approvers";
PreparedStatement preStmtCPList=dbCon.prepareStatement(queryCPList);//get metadat
PreparedStatement preStmtApprList=dbCon.prepareStatement(queryApprList);//get names
//ResultSet rsCPList=preStmtCPList.executeQuery();
ResultSet rsApprList=preStmtCPList.executeQuery();
//ResultSetMetaData metaCPList=rsCPList.getMetaData();
VactionTrackerBean vtBean=new VactionTrackerBean();
while(rsApprList.next()){
vtBean.setApprover((rsApprList.getString("First_Last_Name")));
appr.add(vtBean);
}
}catch(Exception e){
System.out.println("In the Vacation TrackerDAO.java class:"+e);
}
return appr;
}
}
Bean:
public class VactionTrackerBean {
private String dates;
private String approver;
public String getDate() {
return dates;
}
public void setDate(String dates) {
this.dates = dates;
}
public String getApprover() {
return approver;
}
public void setApprover(String approver) {
this.approver = approver;
}
}
Servlet:
public class VacationTracker extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try{
List<VactionTrackerBean> vacTracker=VacationTrackerDAO.list();
request.setAttribute("vacTracker", vacTracker);
request.getRequestDispatcher("WEB-INF/VacationTracker.jsp").forward(request,response);
}catch (SQLException e){
System.out.println("Error in VacationTracker.java due to VactionTrackerDA.java:"+e);
request.getRequestDispatcher("WEB-INF/Error.jsp").forward(request,response);
}
}
}
JSP Page:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Vacation Tracker</title>
</head>
<body>
<h1> Vacation Tracker </h1>
<div id="main">
<c:forEach items="${vacTracker}" var="vacTracker">
<select id="myselect" name="mydata" size="10">
<option value="${vacTracker.approver}">${vacTracker.approver}</option>
</select>
</c:forEach>
</div>
</body>
</html>
Check you are getting values in list.Put some S.O.P after while loop in DAO class.
Also,There is a mistake in code. It should be
<select id="myselect" name="mydata" size="10">
<c:forEach items="${vacTracker}" var="vacTracker">
<option value="${vacTracker.approver}">${vacTracker.approver}</option>
</c:forEach>
</select>
Otherwise, It will create new select for each item.

Resources