无法从mysql直接获取数据到jsp

时间:2015-11-28 08:17:58

标签: java mysql spring hibernate crud

我使用Spring,Hibernate等在Java上创建了简单的CrUD应用程序。但是编辑操作并没有像我想象的那样工作。当我尝试edit主表中的任何一行时,我只得到空白字段,所以我无法编辑它们,我必须从头开始编写它们!这是entity class

package com.alesto.taskmgr.entity;

import javax.persistence.*;
import java.io.Serializable;


@Entity
@Table(name="tasks")
public class Task implements Serializable,Comparable<Task> {


    private static final long serialVersionUID = 100500L;
    /**
     * our data for mapping with annotations
     */
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @Column
    private String taskBody;

    @Column
    private boolean completion;

    @Column
    private boolean urgency;

    //empty constructor
    public Task() {}

    /**
     * getters and setters
     */
    public long getId() {
        return id;
    }

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

    public String getTaskBody() {
        return taskBody;
    }

    public void setTaskBody(String taskBody) {
        this.taskBody = taskBody;
    }

    public boolean isCompletion() {
        return completion;
    }

    public void setCompletion(boolean completion) {
        this.completion = completion;
    }

    public boolean isUrgency() {
        return urgency;
    }

    public void setUrgency(Boolean urgency) {
        this.urgency = urgency;
    }

    @Override
    public String toString() {
        String completed = completion == true ? "Completed" : "Active";
        String urgent = urgency == true ? "!!!" : "";

        return "("+urgent+completed+") "+this.taskBody;
    }

    @Override
    public int compareTo(Task o) {
        int n1 = this.isCompletion() ? 1 : 0;
        int n2 = o.isCompletion() ? 1 : 0;
        int n3 = n1-n2;
        if(n3 == 0) {
            return this.taskBody.compareTo(o.taskBody);
        } else {
            return n3;
        }
    }
}

我试图用Controller class

来操纵它的对象
package com.alesto.taskmgr.controller;

import com.alesto.taskmgr.entity.Task;
import com.alesto.taskmgr.service.TaskService;

import org.jboss.logging.Logger;
import org.springframework.stereotype.Controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

@Controller
public class TaskController {
    private static final Logger logger = Logger.getLogger(TaskController.class);
    private static Appearance appearance = Appearance.FULL;

    public TaskController() {
        System.out.println("TaskController()");
    }

    @Autowired
    private TaskService taskService;

    @RequestMapping("createTask")
    public ModelAndView createTask(@ModelAttribute Task task) {
        logger.info("Creating Task. Data: " + task);
        return new ModelAndView("taskForm");
    }

    @RequestMapping("editTask")
    public ModelAndView editTask(@RequestParam long id, @ModelAttribute Task task) {
        logger.info("Updating the Task for the Id "+id);
        task = taskService.getTask(id);
        return new ModelAndView("taskForm", "taskObject", task);
    }

    @RequestMapping("saveTask")
    public ModelAndView saveTask(@ModelAttribute Task task) {
        logger.info("Saving the Task. Data : " + task);
        if(task.getId() == 0){ // if task id is 0 then creating the task other updating the task
            taskService.createTask(task);
        } else {
            taskService.updateTask(task);
        }
        return redirection();
    }

    @RequestMapping("deleteTask")
    public ModelAndView deleteTask(@RequestParam long id) {
        logger.info("Deleting the Task. Id : " + id);
        taskService.deleteTask(id);
        return redirection();
    }

    public ModelAndView redirection() {
        switch(appearance) {
            case FULL:
                return new ModelAndView("redirect:getAllTasks");
            case ONLY_ACTIVE:
                return new ModelAndView("redirect:getOnlyActive");
            case ONLY_DONE:
                return new ModelAndView("redirect:getOnlyDone");
            default:
                return new ModelAndView("redirect:getAllTasks");
        }
    }

    @RequestMapping(value = {"getAllTasks", "/"})
    public ModelAndView getAllTasks() {
        logger.info("Getting the all Tasks.");
        List<Task> taskList = taskService.getAllTasks();
        Collections.sort(taskList);
        return new ModelAndView("taskList", "taskList", taskList);
    }

    @RequestMapping(value = {"getOnlyActive"})
    public ModelAndView getOnlyActive() {
        logger.info("Getting only active Tasks.");
        List<Task> taskList = taskService.getAllTasks();
        List<Task> result = new ArrayList<Task>();
        for (Task task : taskList) {
            if(!task.isCompletion()) {
                result.add(task);
            }
        }
        return new ModelAndView("taskList", "taskList", result);
    }

    @RequestMapping(value = {"getOnlyDone"})
    public ModelAndView getOnlyDone() {
        logger.info("Getting only done Tasks.");
        List<Task> taskList = taskService.getAllTasks();
        List<Task> result = new ArrayList<Task>();
        for (Task task : taskList) {
            if(task.isCompletion()) {
                result.add(task);
            }
        }
        return new ModelAndView("taskList", "taskList", result);
    }
}

这就是jsp page,我试图将mysql的数据转换为input form的默认值。

<%--suppress ALL --%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<!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=utf-8" >
  <title>Task Editor</title>
</head>
<body>
<form:form id="taskRegisterForm" modelAttribute="task" method="post" action="saveTask">

  <form:label path="taskBody" >Write or specify your task</form:label><br>
  <form:hidden path="id" value="${taskObject.id}"/>
  <form:textarea cols="100" rows="6" path="taskBody" value="${taskObject.taskBody}"/><br><hr>

  <form:label path="completion">Completion</form:label>
  <form:checkbox path="completion"  value="${taskObject.completion}"/><br>

  <form:label path="urgency">Urgency</form:label>
  <form:checkbox path="urgency" value="${taskObject.urgency}"/><br>


  <input type="submit" id="saveTask" value="Save" onclick="return submitTaskForm();"/>

</form:form>

<script type="text/javascript">
  function submitTaskForm() {
    // checking if conditions are satisfied
    var taskBody = $('#taskBody').val().trim();

    if(taskBody.length == 0) {
      alert('Please, enter at least something! :)');
      $('#taskBody').focus();
      return false;
    }

    return true;
  };
</script>

</body>
</html>

在上面的form我尝试这样的结构: value =&#34; $ {taskObject.completion}&#34; 但它没有&#39;工作。

告诉我是否有必要从项目中添加其他代码。谢谢!

0 个答案:

没有答案