完成後臺管理系統功能(十三)Cms系統內容的增刪改查以及大廣告位的展現

1.Cms系統內容的增刪改查

 

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<div class="easyui-panel" title="Nested Panel" data-options="width:'100%',minHeight:500,noheader:true,border:false" style="padding:10px;">
    <div class="easyui-layout" data-options="fit:true">
        <div data-options="region:'west',split:false" style="width:250px;padding:5px">
            <ul id="contentCategoryTree" class="easyui-tree" data-options="url:'/content/category/list',animate: true,method : 'GET'">
            </ul>
        </div>
        <div data-options="region:'center'" style="padding:5px">
            <table class="easyui-datagrid" id="contentList" data-options="toolbar:contentListToolbar,singleSelect:false,collapsible:
true,pagination:true,method:'get',pageSize:20,url:'/content/query/list',queryParams:{categoryId:0}"> <thead> <tr> <th data-options="field:'id',width:30">ID</th> <th data-options="field:'title',width:120">內容標題</th> <th data-options="field:'subTitle',width:100">內容子標題</th> <th data-options="field:'titleDesc',width:120">內容描述</th> <!-- <th data-options="field:'content',width:120">內容描述</th> --> <th data-options="field:'url',width:60,align:'center',formatter:JINGXI.formatUrl">內容鏈接</th> <th data-options="field:'pic',width:50,align:'center',formatter:JINGXI.formatUrl">圖片</th> <th data-options="field:'pic2',width:50,align:'center',formatter:JINGXI.formatUrl">圖片2</th> <th data-options="field:'created',width:130,align:'center',formatter:JINGXI.formatDateTime">建立日期</th> <th data-options="field:'updated',width:130,align:'center',formatter:JINGXI.formatDateTime">更新日期</th> </tr> </thead> </table> </div> </div> </div> <script type="text/javascript"> $(function(){ var tree = $("#contentCategoryTree"); var datagrid = $("#contentList"); tree.tree({ onClick : function(node){ if(tree.tree("isLeaf",node.target)){ datagrid.datagrid('reload', { categoryId :node.id }); } } }); }); var contentListToolbar = [{ text:'新增', iconCls:'icon-add', handler:function(){ var node = $("#contentCategoryTree").tree("getSelected"); if(!node || !$("#contentCategoryTree").tree("isLeaf",node.target)){ $.messager.alert('提示','新增內容必須選擇一個內容分類!'); return ; } TT.createWindow({ url : "/content-add" }); } },{ text:'編輯', iconCls:'icon-edit', handler:function(){ var ids = TT.getSelectionsIds("#contentList"); if(ids.length == 0){ $.messager.alert('提示','必須選擇一個內容才能編輯!'); return ; } if(ids.indexOf(',') > 0){ $.messager.alert('提示','只能選擇一個內容!'); return ; } TT.createWindow({ url : "/content-edit", onLoad : function(){ var data = $("#contentList").datagrid("getSelections")[0]; $("#contentEditForm").form("load",data); // 實現圖片 if(data.pic){ $("#contentEditForm [name=pic]").after("<a href='"+data.pic+"' target='_blank'><img src='"+data.pic+"' width='80' height='50'/></a>"); } if(data.pic2){ $("#contentEditForm [name=pic2]").after("<a href='"+data.pic2+"' target='_blank'><img src='"+data.pic2+"' width='80' height='50'/></a>"); } /* alert(data.content); */ contentEditEditor.html(data.content); } }); } },{ text:'刪除', iconCls:'icon-cancel', handler:function(){ var ids = TT.getSelectionsIds("#contentList"); if(ids.length == 0){ $.messager.alert('提示','未選中商品!'); return ; } $.messager.confirm('確認','肯定刪除ID爲 '+ids+' 的內容嗎?',function(r){ if (r){ var params = {"ids":ids}; $.post("/content/delete",params, function(data){ if(data.status == 200){ $.messager.alert('提示','刪除內容成功!',undefined,function(){ $("#contentList").datagrid("reload"); }); } }); } }); } }]; </script>

 

1.1 dao層

單表查詢,引用mybatis的方向工程javascript

 

1.2 service層

@Service
public class ContentServiceImpl implements ContentService {

    @Autowired
    private TbContentMapper tbContentMapper;
    
    @Override
    public EasyUIDataGridResult getContentList(int page, int rows, long categoryId) {
        TbContentExample example=new TbContentExample();
        PageHelper.startPage(page, rows);
        Criteria critria=example.createCriteria();
        critria.andCategoryIdEqualTo(categoryId);
        List<TbContent> list=tbContentMapper.selectByExampleWithBLOBs(example);
        EasyUIDataGridResult result=new EasyUIDataGridResult();
        result.setRows(list);
        //取記錄的總條數
        PageInfo<TbContent> pageInfo =new PageInfo<>(list);
        result.setTotal(pageInfo.getTotal());
        return result;
        
    }

    @Override
    public JingXiResult createContent(TbContent tbContent) {
        JingXiResult result=new JingXiResult();
        tbContent.setCreated(new Date());
        tbContent.setUpdated(new Date());
        int i=tbContentMapper.insert(tbContent);
        /*if(i == 1){
            try{
                HttpClientUtil.doGet("http://localhost:8082/rest" + "/cache/sync/content/89" +
                        tbContent.getCategoryId());
            }catch(Exception e){
                e.printStackTrace();
            }
            return JingXiResult.ok();
        }*/
        return result;
    }

    @Override
    public JingXiResult editContent(TbContent tbcontent) {
        JingXiResult result=new JingXiResult();
        long id=tbcontent.getId();
        tbcontent.setUpdated(new Date());
        int i=tbContentMapper.updateByPrimaryKey(tbcontent);
        if(i == 1){
            return JingXiResult.ok();
        }
        return result;
    }

    @Override
    public JingXiResult deleteContent(String ids) {
        String a[] =ids.split(",");
        for(int i=0;i<a.length;i++){
            tbContentMapper.deleteByPrimaryKey(Long.parseLong(ids));
            }
        return JingXiResult.ok();
    }

}

 

1.3 controller層

@Controller
public class ContentController {

    @Autowired
    private ContentService contentService;
    
    @RequestMapping("/content/query/list")
    @ResponseBody
    public EasyUIDataGridResult showlist(int page,int rows,long categoryId){
        EasyUIDataGridResult result=contentService.getContentList(page, rows, categoryId);
        return result;
    }
    
    @RequestMapping("/content/save")
    @ResponseBody
    public JingXiResult create(TbContent tbContent){
        JingXiResult result=contentService.createContent(tbContent);
        return result;
    }
    
    @RequestMapping("/rest/content/edit")
    @ResponseBody
    public JingXiResult edit(TbContent tbContent){
        /*System.out.println(tbContent.getTitle()+"."
                    +tbContent.getId()+"."+tbContent.getCategoryId()+"."+tbContent.getContent());*/
        JingXiResult result=contentService.editContent(tbContent);
        return result;
    }
    
    @RequestMapping("/content/delete")
    @ResponseBody
    public JingXiResult delete(String ids){
        JingXiResult result=contentService.deleteContent(ids);
        return result;
    }
}

 

 2. 大廣告位的展現

2.1 跨域問題的解決

在jingxi-portal頁面要調用jingxi-rest中的服務。html

方案一:jsonp 跨域請求 java

 

須要當首頁加載完畢後,大廣告位就應該顯示。沒有觸發事件。不是太合適。node

優勢:不須要二次請求,頁面直接加載內容數據。減小門戶系統的壓力。apache

缺點:須要延遲加載。不利於 seo 優化。編程

 

 方案二:使用httpclient實現json

優勢:有利於 seo 優化。能夠在 jingxi-portal 中對數據進行加工。缺點:系統直接須要調用服務查詢內容信息,多了一次 http 請求。跨域

系統直接服務的調用,須要使用 httpclient 來實現。jingxi-portal 和 jingxi-rest 是在同一個局域網內部。速度很是快,調用時間能夠忽略不計。mybatis

展現首頁內容功能,使用方案二實現。app

 

2.2 httpclient的使用

2.2.1 什麼是 httpclient?

HttpClient 是 Apache Jakarta Common 下的子項目,用來提供高效的、

最新的、功能豐富的支持 HTTP 協議的客戶端編程工具包,而且它支持 HTTP 協議最新的版本和建議。

 

2.2.2  httpclient的使用?

添加依賴須要把 httpclient 的 jar 包添加到工程中,只須要在工程中添加 httpclient 的依賴。

2.2.3 Httpclient 封裝成工具類

其餘項目也可能會用到 httpclient,因此把工具類放到 jingxi-common 中。

package com.jingxi.common.util;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClientUtil {

    public static String doGet(String url, Map<String, String> param) {

        // 建立Httpclient對象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 建立uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 建立http GET請求
            HttpGet httpGet = new HttpGet(uri);

            // 執行請求
            response = httpclient.execute(httpGet);
            // 判斷返回狀態是否爲200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doGet(String url) {
        return doGet(url, null);
    }

    public static String doPost(String url, Map<String, String> param) {
        // 建立Httpclient對象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 建立Http Post請求
            HttpPost httpPost = new HttpPost(url);
            // 建立參數列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模擬表單
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }
            // 執行http請求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return resultString;
    }

    public static String doPost(String url) {
        return doPost(url, null);
    }
    
    public static String doPostJson(String url, String json) {
        // 建立Httpclient對象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 建立Http Post請求
            HttpPost httpPost = new HttpPost(url);
            // 建立請求內容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 執行http請求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return resultString;
    }
}

 

3. jingxi-rest服務的發佈

需求分析:根據內容的分類 id 查詢內容列表,從 tb_content 表中查詢,服務是一個 restFul 形式的服務,使用 http 協議傳遞 json 格式的數據。

3.1 Dao 層:

從 tb_content 表中查詢,根據內容分類 id 查詢,使用逆向工程生成的代碼。

3.2 service層:

@Service 
public class ContentServiceImpl implements ContentService { 
 
     @Autowired 
     private TbContentMapper contentMapper; 
     @Override 
     public List<TbContent> getContentList(long contentCid) { 
          //根據內容分類 id 查詢內容列表 
          TbContentExample example = new TbContentExample();           
      Criteria criteria = example.createCriteria();
      criteria.andCategoryIdEqualTo(contentCid);
//執行查詢 List<TbContent> list = contentMapper.selectByExample(example); return list; } }

 

3.3 controller層

@Controller
public class ContentController {

    @Autowired
    private ContentService contentService;
    
    @RequestMapping("/content/list/{contentCategoryId}")
    @ResponseBody
    public JingXiResult getContentList(@PathVariable Long contentCategoryId){
        
        try{
            List<TbContent> list=contentService.getContentList(contentCategoryId);
            return JingXiResult.ok(list);
            
        }catch(Exception e){
            e.printStackTrace();
            return JingXiResult.build(500,ExceptionUtil.getStackTrace(e));
        }
        
    }

 

 4 在jingxi-portal調用jingxi-rest服務

4.1 在jingxi-protal中添加屬性文件

 

 4.2 Service 層:

根據內容分類 id 查詢分類的內容列表,須要使用 httpclient 調用 jingxi-rest 的服務獲得一個 json 字符串,把內容列表轉換成 jsp 頁面要求的 json 格式。返回一個 json 字符串。

 

@Service 
public class ContentServiceImpl implements ContentService { 
 
     @Value("${REST_BASE_URL}")      
   private String REST_BASE_URL;
   @Value("${REST_INDEX_AD_URL}")
private String REST_INDEX_AD_URL; @Override public String getContentList() { //調用服務層的服務 String result = HttpClientUtil.doGet(REST_BASE_URL + REST_INDEX_AD_URL); //把字符串轉換成TaotaoResult try { JingXiResult jingXiResult = JingXiResult.formatToList(result, TbContent.class); //取內容列表 List<TbContent> list = (List<TbContent>) jingXiResult.getData(); List<Map> resultList = new ArrayList<>(); //建立一個jsp頁碼要求的pojo列表
      for (TbContent tbContent : list) {
Map map = new HashMap<>(); map.put("src", tbContent.getPic());
   map.put("height", 240); map.put("width", 670);        map.put("srcB", tbContent.getPic2());
map.put("widthB", 550);
map.put("heightB", 240);
map.put("href", tbContent.getUrl());
map.put("alt", tbContent.getSubTitle());
resultList.add(map); }
return JsonUtils.objectToJson(resultList); } catch (Exception e) { e.printStackTrace(); } return null; } }

 

4.3 Controller 層:

展現首頁返回一個邏輯視圖,須要把首頁大廣告位的 json 數據傳遞給 jsp。

 

效果:

相關文章
相關標籤/搜索