30/09/2018, 22:23

Thêm, sửa, xoá, tìm kiếm trên web mô hình Spring MVC, Hibernate

Chào mọi người. Em có tìm hiểu trên mạng mô hình Spring MVC kết hợp Hibernate để làm một dự án web nhỏ. Em chạy thử một demo nhỏ mà cứ bị lỗi không thực hiện được chức năng nào hết, với lại cũng không hiển thị danh sách có sẵn trong csdl luôn. Ai cao thủ có thể tìm ra lỗi dùm em được không
Code của em nó đây ak.
Package Model:

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class userlevel {
	@Id
	@Column
	@GeneratedValue(strategy=GenerationType.AUTO)
	private int level_id;
	@Column
	private String levelname;
	
	public userlevel(){}
	public userlevel(int level_id, String levelname) {
		super();
		this.level_id = level_id;
		this.levelname = levelname;
	}
	public int getLevel_id() {
		return level_id;
	}
	public void setLevel_id(int level_id) {
		this.level_id = level_id;
	}
	public String getLevelname() {
		return levelname;
	}
	public void setLevelname(String levelname) {
		this.levelname = levelname;
	}
	
}

Package Dao:

import java.util.List;

import com.group03.set.portal.model.userlevel;

public interface userlevelDao {
	public void add(userlevel ulevel);
	public void edit(userlevel ulevel);
	public void delete(int ulevel_id);
	public userlevel getuserlevel(int ulevel_id);
	public List getAlluserlevel();
}

Package DaoImpl:

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.group03.set.portal.dao.userlevelDao;
import com.group03.set.portal.model.userlevel;

@Repository
public class userlevelDaoImpl implements userlevelDao {
	
	@Autowired
	private SessionFactory session;

	@Override
	public void add(userlevel ulevel) {
		session.getCurrentSession().save(ulevel);

	}

	@Override
	public void edit(userlevel ulevel) {
		session.getCurrentSession().update(ulevel);

	}

	@Override
	public void delete(int ulevel_id) {
		session.getCurrentSession().delete(getuserlevel(ulevel_id));
	}

	@Override
	public userlevel getuserlevel(int level_id) {
		return (userlevel)session.getCurrentSession().get(userlevel.class, level_id);
	}

	@Override
	public List getAlluserlevel() {
		return session.getCurrentSession().createQuery("from userlevel").list();
	}

}

Package Service:

import java.util.List;

import com.group03.set.portal.model.userlevel;

public interface userlevelService {
	public void add(userlevel ulevel);
	public void edit(userlevel ulevel);
	public void delete(int ulevel_id);
	public userlevel getuserlevel(int ulevel_id);
	public List getAlluserlevel();
}

Package ServiceImpl:

import java.util.List;

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

import com.group03.set.portal.dao.userlevelDao;
import com.group03.set.portal.model.userlevel;
import com.group03.set.portal.service.userlevelService;

@Service
public class userlevelServiceImpl implements userlevelService {

	@Autowired
	private userlevelDao ulevelDao;
	
	
	@Transactional
	public void add(userlevel ulevel) {
		ulevelDao.add(ulevel);

	}

	@Transactional
	public void edit(userlevel ulevel) {
		ulevelDao.edit(ulevel);

	}

	@Transactional
	public void delete(int ulevel_id) {
		ulevelDao.delete(ulevel_id);

	}

	@Transactional
	public userlevel getuserlevel(int ulevel_id) {
		return ulevelDao.getuserlevel(ulevel_id);
	}

	@Transactional
	public List getAlluserlevel() {
		return ulevelDao.getAlluserlevel();
	}

}

Package Controller:

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.group03.set.portal.model.userlevel;
import com.group03.set.portal.service.userlevelService;

@Controller
public class userlevelController {
	
	@Autowired
	private userlevelService ulevelService;
	
	@RequestMapping("/index")
	public String setupForm(Map<String, Object> map){
		userlevel ulevel = new userlevel();
		map.put("ulevel", ulevel);
		map.put("ulevelList", ulevelService.getAlluserlevel());
		return "ulevel";
	}
	@RequestMapping(value="/userlevel.do", method=RequestMethod.POST)
	public String doActions(@ModelAttribute userlevel ulevel, BindingResult result, @RequestParam String action,Map<String, Object> map ){
		userlevel ulevelResult = new userlevel();
		switch(action.toLowerCase()){
		case "add":
			ulevelService.add(ulevel);
			ulevelResult = ulevel;
			break;
		case "edit":
			ulevelService.edit(ulevel);
			ulevelResult = ulevel;
			break;
		case "delete":
			ulevelService.delete(ulevel.getLevel_id());
			ulevelResult = new userlevel();
			break;
		case "search":
			userlevel ulevelsearch = ulevelService.getuserlevel(ulevel.getLevel_id());
			ulevelResult = ulevelsearch!=null ? ulevelsearch : new userlevel();		
			break;
		}
		map.put("ulevel", ulevelResult);
		map.put("ulevelList", ulevelService.getAlluserlevel());
		return "ulevel";
	}
	
	
}

Các file config:
jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.dialect=org.hibernate.dialect.MySQLDialect
jdbc.databaseurl=jdbc:mysql://localhost:3306/group03

spring-servlet.xml

<?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:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

	<context:annotation-config />
	<context:component-scan base-package="com.group03.set.portal" />	
		
	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
		p:location="/WEB-INF/jdbc.properties" />

	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
		p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}" />
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="configLocation">
			<value>classpath:hibernate.cfg.xml</value>
		</property>
		<property name="configurationClass">
			<value>org.hibernate.cfg.AnnotationConfiguration</value>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">${jdbc.dialect}</prop>
				<prop key="hibernate.show_sql">true</prop>
			</props>
		</property>
	</bean>
	<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
	    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
	    <property name="prefix" value="/WEB-INF/jsp/"/>
	    <property name="suffix" value=".jsp"/>
	</bean>
	<tx:annotation-driven />
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>	
</beans>

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> 
    
<hibernate-configuration>
    <session-factory>        
        <mapping class="com.group03.set.portal.model.userlevel" />
    </session-factory>         
</hibernate-configuration>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>_group_03_set_portal</display-name>
  
  <context-param>
        <param-name>contextConfigLocation</param-name> 
        <param-value>/WEB-INF/spring-servlet.xml</param-value> 
    </context-param> 
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>spring</servlet-name>
		<url-pattern>/</url-pattern>
		<url-pattern>*.html</url-pattern>
		<url-pattern>*.htm</url-pattern>
	</servlet-mapping>
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

file hiển thị thực thi: jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ include file="/WEB-INF/jsp/includes.jsp"%>
<!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>User level Management</title>
</head>
<body>
<h1>Students Data</h1>
<form:form action="userlevel.do" method="POST" commandName="ulevel">
	<table>
		<tr>
			<td>UserLevelID</td>
			<td><form:input path="level_id"/></td>
		</tr>
		<tr>
			<td>Level Name</td>
			<td><form:input path="levelname"/></td>
		</tr>
		<tr>
			<td colspan="2">
				<input type="submit" name="action" value="Add" />
				<input type="submit" name="action" value="Edit" />
				<input type="submit" name="action" value="Delete" />
				<input type="submit" name="action" value="Search" />
			</td>
		</tr>
	</table>
</form:form>
<br>
<table border="1">
	<th>Level ID</th>
	<th>Level Name</th>
	<c:forEach items="${ulevelList}" var="ulevel">
		<tr>
			<td>${ulevel.level_id}</td>
			<td>${ulevel.levelname}</td>
		</tr>
	</c:forEach>
</table>
</body>
</html>

Em làm theo đầy đủ hướng dẫn hết mà vẫn bị lỗi. Khi chạy thì chỉ được như thế này:

Nếu chỉnh lại thành:

<form:form action="userlevel.do" method="POST" commandName="ulevel">
	<table>
		<tr>
			<td>UserLevelID</td>
			<td><form:input path="level_id"/></td>
		</tr>
		<tr>
			<td>Level Name</td>
			<td><form:input path="levelname"/></td>
		</tr>
		<tr>
			<td colspan="2">
				<input type="submit" name="action" value="Add" />
				<input type="submit" name="action" value="Edit" />
				<input type="submit" name="action" value="Delete" />
				<input type="submit" name="action" value="Search" />
			</td>
		</tr>
	</table>
</form:form>

Thì nó chỉ ra được cái này mà không thêm, sửa, xoá, hay hiển thị thông tin nào hết:

Mong mọi người giúp dùm em.

Bài liên quan
0