简体   繁体   English

单击“编辑”按钮,如何在Spring MVC中编辑数据表中的每一行?

[英]How to Edit each row in the data table in Spring mvc on a edit button click?

Whenver i click on <a id="myBtn"><i class="fa fa-pencil" style="color:OliveDrab;"></i></a> i get modal only on first row click and that too appears empty.I went through many links over internet but none of them gave a clear picture as how can it be achieved using spring mvc. 每当我单击<a id="myBtn"><i class="fa fa-pencil" style="color:OliveDrab;"></i></a>我只会在第一行单击时出现模态似乎是空的。我遍历了Internet上的许多链接,但是没有一个清晰的画面显示如何使用Spring MVC来实现。 Following is my attached code, if someone could help me with this i'll be very grateful. 以下是我所附的代码,如果有人可以帮助我,我将非常感谢。

glossary.jsp : lossary.jsp

<!-- Content Wrapper. Contains page content -->
  <div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <section class="content-header">
      <h1>
        Glossary
        <small>search any term</small>
      </h1>
      <ol class="breadcrumb">
        <li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
        <li><a href="#">Tables</a></li>
        <li class="active">Data tables</li>
      </ol>
    </section>

    <!-- Main content -->
    <section class="content">
    <!--.modal -->
      <div class="modal fade" id="modal-default">
          <div class="modal-dialog">
            <div class="modal-content">
              <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">Edit Term</h4>
              </div>
              <div class="modal-body">
               <form:form method="post" id="editTermForm" action="editGlossaryTerm" commandName="editedTermObj" role="form">
              <div class="box-body">
                <div class="form-group">
                  <%-- <input type="hidden" id="termId" name="termId" value="${editedTerm.termId}" /> --%>
                  <label for="termTitle">Term</label>
                  <input class="form-control" type="text" placeholder="Title of your term..." id="termTitle" name="termTitle" value="" />
                  <br>
                  <label for="termTitle">Term Description</label>
                  <textarea class="form-control" rows="3" placeholder="Enter description..." id="termDescription" name="termDescription" ></textarea> 
                  </div>
                  </div>
                  </form:form>
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-default pull-left" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>
              </div>
            </div>
            <!-- /.modal-content -->
          </div>
          <!-- /.modal-dialog -->
        </div>
        <!-- /.modal -->
      <div class="row">
        <div class="col-xs-12">
          <div class="box">
            <div class="box-header">
              <h3 class="box-title">All related terms</h3>
            </div>
            <!-- /.box-header -->
            <div class="box-body">
            <form:form id="glossaryForm" modelAttribute="glossaryFormObj">
            <input type="hidden" id="termId" name="termId"  />
              <table id="example1" class="table table-bordered table-striped">
                <thead>
                <tr>
                  <th>S.No.</th>
                  <th>Term</th>
                  <th>Term Description</th>
                  <th>Created On</th>
                  <th>Action</th>
                </tr>
                </thead>
                <tbody>
                <c:forEach var="glossaryTerms" items="${allGlossaryTerms}" varStatus="status">
                <tr>
                    <td><c:out value="${status.count}" /></td>
                    <td><c:out value="${glossaryTerms.termTitle}" /></td>
                    <td><c:out value="${glossaryTerms.termDescription}" /></td>
                    <td ><c:out value="${glossaryTerms.termCreatedOn}" /></td>
                    <td align="center">
                    <!-- data-toggle="modal" data-target="#modal-default"  -->
                    <a  id="myBtn"><i class="fa fa-pencil" style="color:OliveDrab;"></i></a>&nbsp;&nbsp;&nbsp;
                    <a href="javascript:deleteTerm(${glossaryTerms.termId})"><i class="fa fa-trash-o" style="color:#731043;"></i></a></td>
                </tr>
            </c:forEach>
                </tbody>
                <tfoot>
                <tr>
                  <th>S.No.</th>
                  <th>Term</th>
                  <th>Term Description</th>
                  <th>Created On</th>
                  <th>Action</th>
                </tr>
                </tfoot>
              </table>
              </form:form>
            </div>
            <!-- /.box-body -->
          </div>
          <!-- /.box -->
        </div>
        <!-- /.col -->
      </div>
      <!-- /.row -->
    </section>
    <!-- /.content -->
  </div>

<script>
  $(function () {
    $('#example1').DataTable()
    $('#example2').DataTable({
      'paging'      : true,
      'lengthChange': false,
      'searching'   : false,
      'ordering'    : true,
      'info'        : true,
      'autoWidth'   : false
    })
  })

  function deleteTerm(termId){
      document.getElementById('termId').value=termId;
      document.getElementById('glossaryForm').action="deleteGlossaryRow";
      document.getElementById('glossaryForm').submit();

   }



  function editGlossaryTerm(termId){
      document.getElementById('termId').value=termId;
       document.getElementById('glossaryForm').action="editGlossaryTerm";
       document.getElementById('glossaryForm').submit();
}  

  $(document).ready(function(){
      $("#myBtn").click(function(){
          $("#modal-default").modal();

      });
  });

  $('a.edit').on('click', function() {
        var myModal = $('#modal-default');

        // now get the values from the table
        var termTitle = $(this).closest('tr').find('td.termTitle').html();
        var termDescription = $(this).closest('tr').find('td.termDescription').html();
        // and set them in the modal:
        $('.termTitle', myModal).val(termTitle);
        $('.termDescription', myModal).val(termDescription);
        // and finally show the modal
        myModal.modal({ show: true });

        return false;
    });
</script>

HomeController.java HomeController.java

package in.hkcl.hipaPdfApp;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

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

import in.hkcl.Service.BaseDataService;
import in.hkcl.dao.BaseDataDao;
import in.hkcl.model.DocumentModel;
import in.hkcl.model.GlossaryModel;
import in.hkcl.utils.ApplicationLogFactory;
import in.hkcl.utils.ApplicationLogger;
import in.hkcl.utils.CommonUtils;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
    private static ApplicationLogger logger = ApplicationLogFactory.getLogger(HomeController.class);

    @Autowired
    BaseDataDao baseDataDao;

    @Autowired
    BaseDataService baseDataService;

    List<DocumentModel>allPdfNames;

    /**
     * Simply selects the home view to render by returning its name.
     */
    @RequestMapping(value = "/dashboard", method = RequestMethod.GET)
    public String dashboard(Model model, HttpServletRequest request) {
        try {
            allPdfNames=baseDataService.getListPdfNames();
            List<String> fileNamesOnly = new ArrayList<String>();
            for(int i=0;i<allPdfNames.size();i++){
                String url=allPdfNames.get(i).getDocumentName().toString();
                String fileName = url.substring( url.lastIndexOf('/')+1, url.length() );
                String fileNameWithoutExtn = fileName.substring(0, fileName.lastIndexOf('.'));
                fileNamesOnly.add(fileNameWithoutExtn);
            }

            model.addAttribute("pdfNameList",fileNamesOnly);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "home";
    }

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home(Model model, HttpServletRequest request) {
        try {
            allPdfNames=baseDataService.getListPdfNames();
            List<String> fileNamesOnly = new ArrayList<String>();
            for(int i=0;i<allPdfNames.size();i++){
                String url=allPdfNames.get(i).getDocumentName().toString();
                String fileName = url.substring( url.lastIndexOf('/')+1, url.length() );
                String fileNameWithoutExtn = fileName.substring(0, fileName.lastIndexOf('.'));
                fileNamesOnly.add(fileNameWithoutExtn);
            }

            model.addAttribute("pdfNameList",fileNamesOnly);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "home";
    }

    @RequestMapping(value = "/glossary", method = RequestMethod.GET)
    public String glossary(Model model,HttpServletRequest request) {
        try{
            List<GlossaryModel> allGlossaryTerms=baseDataService.getGlossaryTerms();
            model.addAttribute("allGlossaryTerms", allGlossaryTerms);
        }catch(Exception e){
            e.printStackTrace();
        }
        return "glossary";
    }

    @RequestMapping(value="/deleteGlossaryRow",method={RequestMethod.POST,RequestMethod.GET})
    public String deleteGlossaryRow(@ModelAttribute("termId") Integer termId,Model model) throws Exception{
        if(CommonUtils.isNotEmpty(termId))
        {
            baseDataService.deleteGlossaryTerm(termId);
        }
        List<GlossaryModel> glossaryList=baseDataService.getGlossaryTerms();
        model.addAttribute("allGlossaryTerms", glossaryList);
        return "glossary";

    }


    @RequestMapping(value="/editGlossaryTerm", method = {RequestMethod.POST,RequestMethod.GET})
    public String editGlossaryTermById(@ModelAttribute("glossaryFormObj") GlossaryModel glossaryFormObj, HttpServletRequest request,
            Model model ){
        try{
            GlossaryModel allGlossaryTerms= baseDataService.getGlossaryTermById(glossaryFormObj.getTermId());
            model.addAttribute("allGlossaryTerms", allGlossaryTerms);
        }catch(Exception e){
            logger.logError("editGlossaryTermById", "exception while editing Term details", e);
        }
        return "glossary";
    }

}

GlossaryModel.java GlossaryModel.java

package in.hkcl.model;

import java.io.Serializable;
import java.util.Date;

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

@Entity
@Table(name="glossary")
public class GlossaryModel implements Serializable {
    private static final long serialVersionUID=1L;

    @Id
    @Column(name="termId")
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int termId;

    @Column(name="termTitle")
    private String termTitle;

    @Column(name="termDescription")
    private String termDescription;

    @Column(name="termCreatedOn")
    private Date termCreatedOn;

    @Column(name="termModifiedOn")
    private Date termModifiedOn;

    public GlossaryModel() {

    }

    public GlossaryModel(int termId, String termTitle, String termDescription, Date termCreatedOn,
            Date termModifiedOn) {
        super();
        this.termId = termId;
        this.termTitle = termTitle;
        this.termDescription = termDescription;
        this.termCreatedOn = termCreatedOn;
        this.termModifiedOn = termModifiedOn;
    }

    public int getTermId() {
        return termId;
    }

    public void setTermId(int termId) {
        this.termId = termId;
    }

    public String getTermTitle() {
        return termTitle;
    }

    public void setTermTitle(String termTitle) {
        this.termTitle = termTitle;
    }

    public String getTermDescription() {
        return termDescription;
    }

    public void setTermDescription(String termDescription) {
        this.termDescription = termDescription;
    }

    public Date getTermCreatedOn() {
        return termCreatedOn;
    }

    public void setTermCreatedOn(Date termCreatedOn) {
        this.termCreatedOn = termCreatedOn;
    }

    public Date getTermModifiedOn() {
        return termModifiedOn;
    }

    public void setTermModifiedOn(Date termModifiedOn) {
        this.termModifiedOn = termModifiedOn;
    }

}

I have a Dao,DaoImpl, Service and ServiceImpl class to fetch list in controller. 我有一个Dao,DaoImpl,Service和ServiceImpl类来获取控制器中的列表。 their code is pasted as it is on the following links : 他们的代码粘贴在以下链接上:

Dao: https://paste.ofcode.org/eDKicY6YeFeTeEerCCPSGd
DaoImpl : https://paste.ofcode.org/35qKZ2XB9NsPFjDBTP5m9Km
Service : https://paste.ofcode.org/322Zk5PnNrrW94qbc6YvUe3
ServiceImpl : https://paste.ofcode.org/NLMpZ9WJeungp5xFsCH3ez

I am very much confused with the code. 我对代码非常困惑。 Plz help me to sort this! 请帮我解决这个问题! I have attached the picture too. 我也附上了图片。 Whenever i click on pen icon i want to get a model with that row data, which i can modify. 每当我单击钢笔图标时,我都想获得一个带有该行数据的模型,我可以对其进行修改。 在此处输入图片说明

Remove function $("#myBtn").click(...), add edit class to a tag, edit your function and try this to test: 删除函数$(“#myBtn”)。click(...),将edit class添加到标签,编辑您的函数,然后尝试进行以下测试:

 $("a.edit").click(function() {
        var myModal = $('#modal-default');

        // now get the values from the table

    var parentTr = $(this).parent().parent();
    var tdVal = $('td:eq(1)',parentTr).html();
    alert(tdVal);

    /*var termTitle = $(this).closest('tr').find('td.termTitle').html();
        var termDescription = $(this).closest('tr').find('td.termDescription').html();
        // and set them in the modal:
        $('.termTitle', myModal).val(termTitle);
        $('.termDescription', myModal).val(termDescription);
        // and finally show the modal*/
        myModal.modal({ show: true });

        return false;
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM