如何编辑Spring mvc中数据表中的每一行编辑按钮单击?

时间:2017-12-25 05:18:51

标签: javascript java spring spring-mvc bootstrap-modal

当我点击<a id="myBtn"><i class="fa fa-pencil" style="color:OliveDrab;"></i></a>时,我只在第一行点击时获得模态,这也显示为空。我通过互联网浏览了许多链接,但没有一个给出清晰的图片,如何使用spring mvc实现。以下是我的附加代码,如果有人可以帮助我,我将非常感激。

glossary.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

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

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;
    }

}

我有一个Dao,DaoImpl,Service和ServiceImpl类来获取控制器中的列表。他们的代码粘贴在以下链接上:

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

我对代码非常困惑。 Plz帮我整理一下!我也附上了这张照片。每当我点击笔图标,我想得到一个具有该行数据的模型,我可以修改。 enter image description here

1 个答案:

答案 0 :(得分:0)

删除函数$(“#myBtn”)。单击(...),将编辑类添加到标记,编辑您的函数并尝试此测试:

 $("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;
    });