1. 程式人生 > >初步接觸Java遇到的問題

初步接觸Java遇到的問題

注意:框架原因使用eclipse時需要先把jre改為jdk

 

使用一個框架首先要clean和install在強制更新

修改總框架的資料庫使用者和密碼

然後更改mybatis.xml檔案裡的掃描dao的資訊再改servlet.xml

裡邊的<context:component-scan base-package=””>

1.當網頁請求不到地址時兩種情況①頁面地址寫錯②沒有掃描到包

2.用註解是自動掃描掃描到的

3.分頁的步驟:①在dao中繼承GenericDao<T, Serializable>Serializable序列化ID意思在bean裡邊寫  T是model給誰分頁就寫誰的model

                    ②在bean中繼承序列化 通過序列化ID知dao中的序列化為*

                   ③寫sql語句

                             <!--搜素查詢 Servant 當前頁結果列表-->

                        <select

id="searchPage" parameterType="com.eigpay.framework.student.webapp.searcher.StudentSearcherPage"               

                            resultMap="StudentMap">

                   select *from Student

                   <where>

                                     flag = 0

                             <if test="stuName != null" >

                         and name like CONCAT('%',#{stuName},'%')

                             </if>

                                   </where>

                        </select>

              注意:            如果mapper中程式碼寫錯的話會導致頁面不能登入

                    ④在searcher包裡寫一個*SearcherPage並繼承Page<要分頁的Model>並將parameterType的內容改為*SearcherPage地址 id不變

                    ⑤在Service中寫入Page<Student> studentSearcherPage(StudentSearcherPage studentSearcherPage);

                            在Service下的impl中寫

                            @Override

                            public Page<Student> studentSearcherPage(StudentSearcherPage studentSearcherPage) {

                            // TODO Auto-generated method stub

                                studentSearcherPage.setPageSize(9);//表示每頁存入幾條

                                //返回的結果集

                                studentSearcherPage.setResult(stuDao.searchPage(studentSearcherPage));

                            return studentSearcherPage;

                            }

                            ⑥在controller中寫入程式碼

                            @RequestMapping("list")

                                          public ModelAndView list(@ModelAttribute("studentSearcherPage")StudentSearcherPage studentSearcherPage){

                                                        return new ModelAndView("student/selectAll_list")

                                                          .addObject("studentSearcherPage", studentSearcherPage)//為了將頁碼、頁數查詢條件等返回給前臺頁面

                                                          .addObject("pageObj", stuService.studentSearcherPage(studentSearcherPage));//將查詢的結果集返回給前臺頁面

                           

                                          }            

                            ⑦修改前臺頁面       items="${pageObj.result}"  list存到了result裡邊

4.框架網頁建菜單①新增資源②角色管理(給角色分配選單)③配子選單(路徑:先寫父級路徑 URL:後臺程式登入網頁地址如(/StudentCol/list))④角色管理(給角色分配選單)

5.實現修改新增一個jsp步驟:

         ①修改jsp頁面         

              ②後臺

    注意:由於前臺頁面用的是form:form表單action="${ctx}/*"所以後臺不能隨便跳頁面

              @RequestMapping("manage")

              public ModelAndView manage(@ModelAttribute("Student")Student stu){

                            return new ModelAndView("student/student_manage")

                                                        .addObject("student", stu);

                           

              }                 

6.下拉框實現(死的下拉框):在需要下拉框的jsp寫如

(<select name="sex" class="form-control" id="sex" validata-options="validType:'Require',msg:'不能為空'">

         <option value="">----請選擇----</option>

         <option value="男">男</option>

         <option value="女">女</option>

 </select>)

7.下拉框實現(活的下拉框):

         ①新建一個表

              ②在mapper中寫查詢表的sql

              ③寫程式碼

              ④前臺

              <label for="roleID" class="col-sm-2 control-label">院 系</label>

           <div class="col-sm-10">

           <select name="dept" value="${student.dept}" class="dept" id="dept" validata-options="validType:'Require',msg:'不能為空'">

            <option value="">---請選擇---</option>

                        <c:forEach items="${dept}" var="dept">

                        <option value="${dept.deptName}" <c:if test="${dept.deptName == student.dept}"> selected </c:if> >${dept.deptName}</option>

                </c:forEach>

             </select>

            </div>                                             

出現的錯誤:

一、Invalid bound statement (not found)錯誤      

原因:1.<mapper  namespace="me.tspace.pm.dao.UserDao">

mapper的namespace寫的不對!!!注意系修改。

2.UserDao的方法在UserDao.xml中沒有,然後執行UserDao的方法會報此(查詢的名稱與xml中的沒有對上)

3. UserDao的方法返回值是List<User>,而select元素沒有正確配置ResultMap,或者只配置ResultType!

4. 如果你確認沒有以上問題,請任意修改下對應的xml檔案,比如刪除一個空行,儲存.問題解決…

        

檔案匯出

一、  controller繼承Basecontroller和admin的pom檔案寫

  <dependency>

                              <groupId>eigpay-sdk</groupId>

                              <artifactId>excel</artifactId>

                              <version>1.4</version>

                </dependency>

二、  Basecontroller中寫

   /**

     * excel匯出

     *

     * @param fileName  檔名稱

     * @param sheetName sheet頁名稱

     * @param excelPojos excel資料

     * @param request

     * @param response

     * @throws Exception

     */

    public void downLoadExcel(String fileName, String sheetName, List<?> excelPojos,HttpServletRequest request,HttpServletResponse response) throws Exception {

        ArrayList<List<?>> datas = new ArrayList<>();

        datas.add(excelPojos);

        Component component = ExcelComponentsFactory.produce();

        ExcelExportSetting excelExportSetting = new ExcelExportSetting();

        excelExportSetting.setData(datas);

        excelExportSetting.setExcelFileType(ExcelFileType.XLSX);

        excelExportSetting.setSheetName(new String[] { sheetName });

 

        File path = new File("." + File.separator + "file");

        if (!path.exists())

            path.mkdirs();

        String filePathAndName = "." + File.separator + "file" + File.separator + fileName;

        File file = new File(filePathAndName);

        if (file.exists())

            file.delete();

        excelExportSetting.setExcelFilePath(filePathAndName);

        component.exportList2Excel(excelExportSetting);

 

        response.setContentType("text/html;charset=utf-8");

        request.setCharacterEncoding("UTF-8");

        java.io.BufferedInputStream bis = null;

        java.io.BufferedOutputStream bos = null;

        try {

            long fileLength = file.length();

            response.setContentType("application/x-msdownload;");

            response.setHeader("Content-disposition",

                "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));

            response.setHeader("Content-Length", String.valueOf(fileLength));

            bis = new BufferedInputStream(new FileInputStream(filePathAndName));

            bos = new BufferedOutputStream(response.getOutputStream());

            byte[] buff = new byte[2048];

            int bytesRead;

            while (-1 != (bytesRead = bis.read(buff, 0, buff.length)))

                bos.write(buff, 0, bytesRead);

        } catch (Exception e) {

            throw new Exception(e);

        } finally {

            if (bis != null) {

                bis.close();

                bis = null;

            }

            if (bos != null) {

                bos.flush();

                bos.close();

                bos = null;

            }

        }

}

包含日期的匯出

三、寫一個關於匯出所需要的model類

                       

四、  controller中寫

               /**

     * 匯出專案資訊表

     * @throws Exception

     * @return /projectInfoManage/projectInfo/exportprojectBasicInfo

     */

    @RequestMapping(value = "/exportprojectBasicInfo", method = RequestMethod.POST)

    private void exportprojectBasicInfo(ProjectStaticManagePageSearcher seacher, HttpServletRequest request,HttpServletResponse response) throws Exception {

        //1.查專案資訊資料列表

        List<ProjectInfo> ProjectInfoList = projectStaticInfoDao.getExcelData(seacher);

        //2.data pojos to excel pojos

        List<Object> ProjectInfo = projectStaticManage.downloadProjectInfo(ProjectInfoList);

        //3.生成檔名

        StringBuffer stringBuffer = new StringBuffer("專案資訊-");

        stringBuffer.append(new SimpleDateFormat("yyyyMMdd").format(new Date()));

        stringBuffer.append(".xlsx");

        String fileName = stringBuffer.toString();

        //4.調方法

        super.downLoadExcel(fileName, "專案資訊", ProjectInfo, request, response);

    }

五、ManageImpl中寫

   @Override

    public void downloadExcel(HttpServletRequest request, HttpServletResponse response,ProjectStaticManagePageSearcher seacher) {

       

                            List<ProjectInfo> data = projectStaticInfoDao.getExcelData(seacher);

        String[] title = { "專案編號", "專案名稱", "開工日期", "狀態"};

        HSSFWorkbook workbook = new HSSFWorkbook();

        HSSFCellStyle cellStyle = workbook.createCellStyle();

        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        String filename = "專案資訊表.xls";

        response.setContentType("application/vnd.ms-excel");

        try {

                response.setHeader( "Content-Disposition", "attachment;filename=" + new String( filename.getBytes("GB2312"), "ISO-8859-1" ) );

        } catch (UnsupportedEncodingException e1) {

            // TODO Auto-generated catch block

            e1.printStackTrace();

        }

        //response.setHeader("Content-disposition", "attachment;filename=" + filename);  

        HSSFSheet sheet = workbook.createSheet(filename);

 

        HSSFRow row = sheet.createRow(0);

        HSSFCell cell = null;

        int i = 0;

        for (; i < title.length; i++) {

            cell = row.createCell(i);

            cell.setCellValue(title[i]);

        }

        i = 1;

        for (ProjectInfo item : data)

        {

            row = sheet.createRow(i);

            cell = row.createCell(0);

            cell.setCellValue(item.getProjectCode());

            cell = row.createCell(1);

            cell.setCellValue(item.getProjectName());

            cell = row.createCell(2);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd ");

            if(item.getStartDate() !=null)

            {

            cell.setCellValue(sdf.format(item.getStartDate()));

            } else {

                        cell.setCellValue(" ");

            }

           

            cell = row.createCell(3);

            cell.setCellValue(item.getProjectStatus());

            i++;

        }

        sheet.setColumnWidth(0, (short) 250 * 30);

        sheet.setColumnWidth(1, (short) 250 * 40);

        sheet.setColumnWidth(2, (short) 250 * 15);

        try {

            ServletOutputStream stream = response.getOutputStream();

            workbook.write(stream);

            stream.close();

        } catch (IOException e) {

            e.printStackTrace();

        }

 

    }

六、分別在dao,mapper,service中寫上相應程式碼mapper中用分頁查詢的就可以

七、在需要匯出的jsp頁面寫

     $("#export").click(

                 function(){

                      $("#pageForm").attr('action',"${ctx}/Controller/exportprojectBasicInfo");

                      $("#pageForm").submit();

                      $("#pageForm").attr('action',"${ctx}/Controller/list");} );

匯出按鈕那裡用id=” export”觸發

彈框:

1按鈕

<a data-toggle="modal" data-target="#invoice_ajaxload" href="${ctx}/projectBidInfo/jumpMoreAction/ajaxLoad?bidCode=${bidInfo.bidCode}">更多操作</a>

2彈框程式碼(放在<form:from>之後)

<div class="modal fade" id="invoice_ajaxload">

              <div class="modal-dialog">

                            <div class="modal-content"></div>

              </div>

</div>

3js程式碼

              $(function() {

$("#invoice_ajaxload").on("hidden.bs.modal", function(e) {

                                          $(this).removeData();

                            })

});

3/**

               * 跳轉到更多操作顯示頁面

               * @return

               */

              @RequestMapping("jumpMoreAction/ajaxLoad")

              public ModelAndView jumpMoreAction(HttpServletRequest request, String bidCode){

                            System.out.println(bidCode);

                           

                            return new ModelAndView("projectInfoManage/moreAction_manage")

                                                        .addObject("bidCode", bidCode);}

正則表示式校驗姓名

      /* 姓名的校驗 */

   function checkcontact()

      {

           var checkContact= document.getElementById("contact");

           var contactValue=$(".contact").val();

      $(".contact").each(function(){

               if($(this).val() != "") {

                 if (!iscontact(contactValue))

                  {

                   alert("請輸入漢字或者字母!");

                   document.getElementById("contact").value = "";

                   throw SyntaxError();

                  }

               }       

            });

      return true;

      }

 

      function iscontact(str){

          var reg = /^[a-zA-Z\u4e00-\u9fa5\s]{1,20}$/;

          return reg.test(str);

      }

用onchange觸發

Ajax校驗唯一性

<!-- 客戶名稱唯一校驗 -->

一、前臺

<script type="text/javascript">

      $("#custName").change(function check() {

           var custName = $("#custName").val();

           var name = '${name}';

           if (name == custName) {

                 $("#custName").val(name);

           } else {

                 $.ajax({

                      type : 'post',

                      url : '${ctx}/SaleCustomorController/ajax/checkcustName',

                      dataType : 'json',

                      data : {

                            custName : custName

                      },

                      success : function(data) {

                            if (data.info == "repeat") {

                                  alert("已存在客戶名稱!請重新填寫!");

                                  $("#custName").val("");

                                  $("#custName").select();

                            }

                      }

                 })

           }

 

      });

</script>

custName是id裡的

二、後臺(走一個查詢需校驗的內容方法)

/**

       * 查重 客戶名稱

       */

      @RequestMapping(value="ajax/checkcustName",method = { RequestMethod.GET, RequestMethod.POST })

      public void checkcustName(HttpServletResponse response,String custName){

           Map<String, Object> map = new  HashMap<String, Object>();

           List<String> name = scManager.searchcustName();

           String msg = "unrepeat";

           for (int i = 0; i < name.size(); i++) {

                 if(custName!=null){

                      //如果存在,直接跳出迴圈,不再執行,減少時間

                      if(custName.contentEquals(name.get(i))){

                            msg = "repeat";

break;}}}ResponseUtil.renderJsonResult(response, new JsonResult(true, msg));}

sql中修改一個表資料另一個表資料同步更新

           update 表一,表二 set 同步的資料(如sale_contact_costomor.contact_company = sale_customor.cust_name,)

           where 兩個表關聯的資料

模糊查詢

Sql語句加上<if test="custName != null" >

                     and cust_name like CONCAT('%',#{custName},'%')

                    </if>

查詢角色

//查詢登入人的id

           id = getCurrentSessionObject().getUser().getId();

           List<ServantRole> list = srDao.listRoleByUserId(id);//這是通過id查出來的list

           //定義變數

           String isHaveRole = "F";

           for (ServantRole servantRole : list) {

                 if("銷售leader".equals(servantRole.getDescription())

                            || "銷售Owner".equals(servantRole.getDescription())){

                     

                      isHaveRole = "T";

                      break;

                 }

           }

前臺傳後臺中文出現亂碼問題

中文 = new String(request.getParameter("中文").getBytes("ISO-8859-1"),

"utf-8");

可下拉可輸入的輸入框及內容拼接

<form:input cssClass="form-control" placeholder="請下拉選擇或按照下拉格式輸入" list="url_list" path="projectName" id="projectName" maxlength="60"/>

                                       <datalist id="url_list">

                                             <c:forEach items="${project}" var="list">

                                             <option value="${list.projectCode}:${list.projectName}"></option>

                                             </c:forEach>

                                       </datalist>

 

再輸入框中填入日曆

 

 

一、 哪個jsp需要寫入日曆就在這個jsp引入的model中寫入並填充get,set方法

private String startQueryDate;

private String endQueryDate;

代表輸入框中的起止時間,在jsp頁面中<from:from>下面填入

<form:hidden path="startQueryDate" id="startQueryDate"/>

<form:hidden path="endQueryDate"  id="endQueryDate"/>

代表再輸入狂顯示出時間,接著再寫

<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">

                            <div class="form-group ">

                                  <div class="col-lg-12 col-sm-12">

                                       <%-- <input class="form-control" value="${tQuitRecordPageSearcher.effectDate }" placeholder="離職日期"

                                             onfocus="WdatePicker({isShowWeek:true})" name="effectDate"> --%>

                                              <!--  日曆部分 -->

                                              <div id="reportrange"

                                                        style="font-size: 12px; background: #fff; cursor: pointer; padding: 3px 8px;

                                                         border: 1px solid #e7e7eb;">

                                                        <i class="glyphicon glyphicon-calendar fa fa-calendar"> </i> <span>

                                                        </span> <b class="caret"> </b>

                                             </div>

                                             <!--  日曆部分 結束 -->

                                  </div>

                            </div>

                      </div>

最後在js裡面寫,日曆完成

$(function () {

           

            var startQueryDate = $("#startQueryDate").val();

                 if (startQueryDate != "") {

                      daterangepicker_optionSet.startDate=startQueryDate;

                      daterangepicker_optionSet.endDate=$("#endQueryDate").val();

                 }

                 var cb = function(start, end, label) {

                      $('#reportrange span').html(start.format('YYYY-MM-DD') + ' - '+ end.format('YYYY-MM-DD'));

                 }

 

                 $('#reportrange span').html(daterangepicker_optionSet.startDate + ' - '+daterangepicker_optionSet.endDate);

                

                 $('#reportrange').daterangepicker(daterangepicker_optionSet, cb);

                

                 $('#reportrange').on('apply.daterangepicker',function(ev, picker) {

                      // 在這裡進行業務查詢操作

                      $("#startQueryDate").val(picker.startDate.format('YYYY-MM-DD'));

                      $("#endQueryDate").val(picker.endDate.format('YYYY-MM-DD'));

                      $("#pageNo").val(1);

                  $("#pageForm").submit();

                 });

            $("#query").click(function () {

                  $("#pageNo").val(1);

                  $("#pageForm").submit();

              });

              $("#reset").click(function () {

                  $("input").val('');

                  $("select").val("-1");

              })

          });              

在輸入框顯示時間(2)

在jsp頁面寫入

<div class="form-group">

                                        <label class="col-sm-2 control-label" >提出日期</label>

                                        <div class="col-sm-10">

                                             <input  class="form-control" name="proposedDate" id="proposedDate" value="<fmt:formatDate value='${tAppointManagerRecord.proposedDate}'

                                             pattern="yyyy-MM-dd"/>"  onfocus="WdatePicker({isShowWeek:true})" />

                                        </div>

                                    </div>

   完成。