Lỗi khi hiển thị dữ liệu lên trang JSP?

Trước Mình có lập 1 post nhưng không hiểu sao không sử được nữa! Nên Mình xin phép up lại bài để hỏi m.n ! Mong AD xóa giùm mình bài cũ với ạ !
Mình Xin Cảm ơn !

Project :


Lớp POJO :

package com.SpringMVC.model;

public class Company {
	private int id;
	private String name;
	private String location;

	public Company(int id, String name, String location) {
		super();
		this.id = id;
		this.name = name;
		this.location = location;
	}

	@Override
	public String toString() {
		return "Company [ Id = " + id + ", Name = " + name + ", location = " + location + "]";
	}

	public Company(String name, String location) {
		super();
		this.name = name;
		this.location = location;
	}

	public Company() {
		super();
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getLocation() {
		return location;
	}

	public void setLocation(String location) {
		this.location = location;
	}

}

Lớp DAO :

package com.SpringMVC.dao;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.SpringMVC.model.Company;

@Repository
@Qualifier("companyDao")
public class CompanyDaoImpl implements CompanyDao {

	JdbcTemplate jdbcTemplate;
	DataSource dataSource;

	@Autowired
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
		jdbcTemplate = new JdbcTemplate(this.dataSource);
	}

	// Insert values to Company table
	public void insertCompany(Company company) {

		String sql = "Insert into company values (" + company.getId() + ",'" + company.getName() + "','"
				+ company.getLocation() + "')";
		jdbcTemplate.update(sql);

	}

	// Update values for Company record by id
	public void updateCompany(Company machine, int id) {

		String sql = "Update company Set name = ? , location = ? Where id = ? ";
		jdbcTemplate.update(sql, machine.getName(), machine.getLocation(), id);

	}

	// Delete values from Company by id
	public void deleteCompany(int id) {

		String sql = "Delete from company where id = ?";
		jdbcTemplate.update(sql, id);

	}

	// Get All Company from table
	@SuppressWarnings("unchecked")
	public List<Company> getAllCompany() {

		List<Company> listCompany = new ArrayList<Company>();
		String sql = "Select * from company";
		listCompany = (List<Company>) jdbcTemplate.queryForObject(sql,
				(ResultSet rs, int rowNum) -> new Company(rs.getInt(1), rs.getString(2), rs.getString(3)));

		return listCompany;
	}

	// Find Company by Id
	public Company findById(int id) {

		String sql = "Select * From company Where id = ?";
		Company company = (Company) jdbcTemplate.query(sql, new Object[] { id },
				new BeanPropertyRowMapper<Company>(Company.class));

		return company;
	}

	// Count Company From Table
	public int countCompany() {

		String sql = "Select count(*) from company";

		return jdbcTemplate.queryForObject(sql, Integer.class);
	}

}

Lớp Service :

package com.SpringMVC.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.SpringMVC.dao.CompanyDao;
import com.SpringMVC.model.Company;

@Service("companyService")
public class CompanyServiceImpl implements CompanyService {

	@Autowired
	private CompanyDao companyDao;

	@Override
	public void insertCompany(Company company) {
		companyDao.insertCompany(company);
	}

	@Override
	public void updateCompany(Company machine, int id) {
		companyDao.updateCompany(machine, id);
	}

	@Override
	public void deleteCompany(int id) {
		companyDao.deleteCompany(id);
	}

	@Override
	public List<Company> getAllCompany() {
		return companyDao.getAllCompany();
	}

	@Override
	public Company findById(int id) {
		return companyDao.findById(id);
	}

	@Override
	public int countCompany() {
		return companyDao.countCompany();
	}

}

Lớp Controller :

package com.SpringMVC.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.SpringMVC.dao.CompanyDao;
import com.SpringMVC.model.Company;

@Controller
public class CompanyController {

	@Autowired
	private CompanyDao companyDao;

//	@RequestMapping("/compform")
//	public String showForm(Model m) {
//		m.addAttribute("command", new Company());
//		return "comp-form";
//	}

	@RequestMapping("/compview")
	public String viewComp(Model m) {
		List<Company> list = companyDao.getAllCompany();
		m.addAttribute("list", list);
		return "comp-view";
	}

}

Trang Hiển Thị :

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Company View</title>
</head>
<body>
	<div align="center">
		<h2>Company List</h2>
		<table>
			<tr>
				<th>Id</th>
				<th>Name</th>
				<th>Location</th>
			</tr>
			<c:forEach var="l" items="${list}">
				<tr>
					<td><c:out value="${l.id}" /></td>
					<td><c:out value="${l.nam}" /></td>
					<td><c:out value="${l.location}" /></td>
				</tr>
			</c:forEach>
		</table>
	</div>
</body>
</html>

Cấu Hình :

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

	<context:component-scan
		base-package="com.SpringMVC"></context:component-scan>

	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/view/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>

	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName"
			value="org.apache.derby.jdbc.ClientDriver"></property>
		<property name="url"
			value="jdbc:derby://localhost:1527/education;create=true"></property>
	</bean>

	 <!-- <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> </bean> 

	 <bean id="employeeDao" class="com.SpringMVC.dao.CompanyDaoImpl"> </bean> -->

</beans>

Lỗi :

1.   org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'companyController': Unsatisfied dependency expressed through field 'companyDao'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'companyDaoImpl': Unsatisfied dependency expressed through method 'setJdbcTemplate' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.jdbc.core.JdbcTemplate' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
2.   org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'companyDaoImpl': Unsatisfied dependency expressed through method 'setJdbcTemplate' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.jdbc.core.JdbcTemplate' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
3.  org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jdbcTemplate' defined in ServletContext resource [/WEB-INF/spring-servlet.xml]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'dataSource' is required

Cách sử dụng của JdbcTemplate là mình tạo object, chứ không phải cấu hình nó bạn à.

Ở trong lớp CompanyDaoImpl bạn vừa autowire jdbcTemplate, và ngay sau đó bạn ignore nó và lại tạo thêm một new JdbcTemplate:

@Autowired
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
	this.jdbcTemplate = jdbcTemplate;
	jdbcTemplate = new JdbcTemplate(this.dataSource);
}

Bạn thử đổi code như sau đi:

@Autowired
public void setJdbcTemplate(DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
}

Bạn muốn học hỏi thêm về cách sử dụng Spring+Jdbc thì có thể tham khảo trang này:
https://docs.spring.io/spring/docs/5.0.0.BUILD-SNAPSHOT/spring-framework-reference/html/jdbc.html

1 Like
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?