问题提出
项目运行中,cookie的作用一般是起着一个不可或缺的权限控制或者认证的作用,但是如果是多系统交互,cookie是由别的系统生成,本系统对接的话,那么这个cookie就会
成为项目测试的一个麻烦
那么我们可以基于这个,开发一个cookie的配置页面
1、展示目前所有的cookie
2、对已有的cookie进行操作
3、可以新增对应的cookie
配置文件修改
首先在liferay-portlet.xml中添加一个
<requires-namespaced-parameters>false</requires-namespaced-parameters>
可以避免在页面传参的时候,要加namespace的尴尬
其余的配置文件,按照eclipse自带的生成方式生成就可以了
定义页面
定义init页面
init.jsp
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>
<%@ taglib uri="http://liferay.com/tld/theme" prefix="liferay-theme" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <portlet:defineObjects />
view.jsp
<%@ include file="/html/common/init.jsp" %>
<%@page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" deferredSyntaxAllowedAsLiteral="true"%> <!-- 一般不跳转到其他页面的时候,doview 等 我们使用renderRequest渲染页面 -->
<portlet:renderURL var="cookieform"></portlet:renderURL>
<!-- 查询,修改,新增,删除 -->
<portlet:resourceURL id="cookieAjax" var="oper"></portlet:resourceURL>
<portlet:actionURL var="modCookie" name="modCookie">
<portlet:param name="jspPage" value="/html/cookieoperator/view.jsp"/>
</portlet:actionURL> <!-- 获取根目录 -->
<%
String rootPath = renderRequest.getContextPath();
String title = "配置cookie"; %> <script type="text/javascript" src="<%=rootPath%>/js/jQuery/jquery-3.1.1.js"></script>
<link rel="stylesheet" type="text/css" href="<%=rootPath%>/css/cookieoperator/main.css" /> <!-- 展示所有的cookie -->
<h1>Cookie的展示</h1>
<div id="win1">
<!-- 工具栏,查询,新增,修改,删除 -->
<div id="toolbar">
<input id="select" value="查询" type="button" />
<input id="add" value="新增" type="button" />
<input id="mod" value="修改" type="button" />
<input id="del" value="删除" type="button" />
</div>
<!-- 数据展示cookie -->
<div id="data">
<table id="cookieTable" border="1">
<tr>
<td>name</td>
<td>value</td>
<!-- <td>path</td> -->
<td>domain</td>
<td>version</td>
<td>comment</td>
</tr>
<c:forEach items="${cookies1 }" var="cookie1">
<tr>
<td>${cookie1.name }</td>
<td>${cookie1.value }</td>
<%-- <td>${cookie1.path }</td> --%>
<td>${cookie1.domain }</td>
<td>${cookie1.version }</td>
<td>${cookie1.comment }</td>
</tr>
</c:forEach>
</table>
</div> </div> <div id="win2" class="dialog">
<div id="movePart">
标题进行拖拽
<input id="back2" value="返回2" type="button" />
</div>
<div id="content">
<table id="cookieTable">
<tr>
<div>
<td>
<label for="name">cookie名称:</label>
<input type="text" name="name" id="name" class="required"/>
</td>
<td>
<label for="path" style="display:none">cookie路径:</label>
<input type="hidden" name="path" id="path"/>
</td>
</div>
</tr>
<tr>
<div>
<td>
<label for="value">cookie值:</label>
</td>
<td>
<input type="text" name="value" id="value" size="100"/>
</td> </div>
</tr>
<tr>
<div>
<td>
<label for="domain">cookie域名:</label>
<input type="text" name="domain" id="domain"/>
</td>
<td>
<label for="version">cookie版本:</label>
<input type="text" name="version" id="version"/>
</td>
</div>
</tr>
<tr>
<div>
<td>
<label for="comment">cookiecomment:</label>
<input type="text" name="comment" id="comment"/>
</td>
</div>
</tr>
<tr>
<td>
<input type="button" value="提交" id="send"/>
</td>
<td>
<input type="reset" id="res" value="清空"/>
</td>
</tr>
</table>
</div>
</div> <div id="mask" class="mask"></div>
<script type="text/javascript">
<!--
function tableTrClick() {
//选中所有tr,绑定事件
$('#cookieTable tr').on('click', function(){
//选中之后改变当前元素的class,清除其他元素的颜色
$('#cookieTable tr').removeClass("selected1");
$(this).addClass("selected1");
});
} /**
* js弹出窗口层 start
*/
//获取对应标签函数
function g(id) {
return document.getElementById(id);
} function autoCenter(el) {
//获取可见窗口大小
var bodyW = document.documentElement.clientWidth;
var bodyH = document.documentElement.clientHeight;
//获取对话框宽、高
var elW = el.offsetWidth;
var elH = el.offsetHeight; el.style.left = (bodyW - elW)/2 + 'px';
el.style.top = (bodyH - elH)/2 + 'px'; } function clearForm() {
$("#name").val("");$("#value").val("");$("#path").val("");
$("#domain").val("");$("#version").val("");$("#comment").val("");
} //点击之后弹出对话框,遮罩设置
g("add").onclick = function(){
g("win2").style.display = 'block';
g("mask").style.display = 'block';
//先重置表单 cookieTable
clearForm();
autoCenter(g("win2"));
} //修改
g("mod").onclick = function(){
g("win2").style.display = 'block';
g("mask").style.display = 'block';
//填充对应的值
//name, value,path,domain,version,comment
//先重置表单 cookieTable
clearForm();
var name = $('#cookieTable tr.selected1 td:eq(0)').text();
var value = $('#cookieTable tr.selected1 td:eq(1)').text();
var path = $('#cookieTable tr.selected1 td:eq(2)').text();
var domain = $('#cookieTable tr.selected1 td:eq(3)').text();
var version = $('#cookieTable tr.selected1 td:eq(4)').text();
var comment = $('#cookieTable tr.selected1 td:eq(5)').text();
//填充对应的值
$("#name").val(name);$("#value").val(value);$("#path").val(path);
$("#domain").val(domain);$("#version").val(version);$("#comment").val(comment); autoCenter(g("win2"));
} //关闭弹出框
g("back2").onclick = function() {
g("win2").style.display = 'none';
g("mask").style.display = 'none';
} //窗口大小改变时,对话框始终居中
window.onresize = function(){
autoCenter(g('win2'));
}; //鼠标坐标
var mx = 0, my = 0;
var dx = 0, dy = 0;
var isDraging = false; //是否可以拖拽
//鼠标按下
g('movePart').addEventListener('mousedown', function(e) {
var e = e || window.event;
//获取点击的鼠标位置
mx = e.pageX;
my = e.pageY; dx = g('win2').offsetLeft;
dy = g('win2').offsetTop;
isDraging = true;
});
//鼠标移动
document.onmousemove = function(e){
var e = e || window.event;
var x = e.pageX; //移动时鼠标X坐标
var y = e.pageY; //移动时鼠标Y坐标
if(isDraging){ //判断对话框能否拖动
var moveX = dx + x - mx; //移动后对话框新的left值
var moveY = dy + y - my; //移动后对话框新的top值
g('win2').style.left = moveX +'px'; //重新设置对话框的left
g('win2').style.top = moveY +'px'; //重新设置对话框的top
};
};
//鼠标松开
g('movePart').addEventListener('mouseup',function(){
isDraging = false;
});
//-------------------------------------------js弹出窗口层 end //--------------------------删除cookie start function getCookieval_r(offset) {
//上offset的位置开始查找的,直到";"的位置。
var endstr = document.cookie.indexOf(";", offset);
if(endstr == -1) {
//如果是末尾
endstr = document.cookie.length;
} return document.cookie.substring(offset, endstr);
} function getCookie(name) {
var arg = name + "=";
var alen = arg.length;
//获取cookie串的长度
var clen = document.cookie.length;
var i = 0;
var j = 0;
//遍历
while(i < clen) {
//当前cookie名字=长度
j = i + alen;
//判断是否是要遍历的cookie
if(document.cookie.substring(i, j) == arg) {
//获取cookie值,j为名字=结尾的地方
return getCookieval_r(j);
}
i = document.cookie.indexOf(" ", i) + 1;
if(i == 0) {
break;
}
}
return '';
} function delCookie(name) {
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var cval = getCookie(name);
if(cval != null) {
document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString() + "; path=/";
}
} //--------------------------删除cookie end function operCookies() { //点击的时候,发起请求
$('#select').on('click', function(){
//获取选中数据
var selectCookieName = $('#cookieTable tr.selected1 td:eq(0)').text(); //发起请求
$.ajax({
type:"POST",
url:"<%=oper%>",
dataType:"json",
data:{"operKey":"select"},
success:function(msg){
//更新页面
//1、获取这个table
//2、清除标题以下的数据
$('#cookieTable tr:gt(0)').empty();
//3、解析json,组装数组tr
//var jsonArr = eval("(" + msg + ")");
//4、添加到table中
//从新获取table
var $table = $('#cookieTable');
//遍历json
$.each(msg, function(i, item) {
var oneRow = "<tr>";
oneRow += "<td>" + item.name + "</td>";
oneRow += "<td>" + item.value + "</td>";
//oneRow += "<td>" + item.path + "</td>";
oneRow += "<td>" + item.domain + "</td>";
oneRow += "<td>" + item.version + "</td>";
oneRow += "<td>" + item.comment + "</td>";
oneRow += "</tr>"; $table.append(oneRow);
});
//从新渲染
tableTrClick();
}
});
}); $('#del').on('click', function(){
//获取选中数据
var selectCookieName = $('#cookieTable tr.selected1 td:eq(0)').text();
var path = $('#cookieTable tr.selected1 td:eq(2)').text();
delCookie(selectCookieName);
//发起请求
$.ajax({
type:"POST",
url:"<%=oper%>",
dataType:"json",
data:{"operKey":"del","selectCookieName":selectCookieName,"path":path},
success:function(msg){
//更新页面
//1、获取这个table
//2、清除标题以下的数据
$('#cookieTable tr:gt(0)').empty();
//3、解析json,组装数组tr
//var jsonArr = eval("(" + msg + ")");
//4、添加到table中
//从新获取table
var $table = $('#cookieTable');
//遍历json
$.each(msg, function(i, item) {
var oneRow = "<tr>";
oneRow += "<td>" + item.name + "</td>";
oneRow += "<td>" + item.value + "</td>";
//oneRow += "<td>" + item.path + "</td>";
oneRow += "<td>" + item.domain + "</td>";
oneRow += "<td>" + item.version + "</td>";
oneRow += "<td>" + item.comment + "</td>";
oneRow += "</tr>"; $table.append(oneRow);
});
//从新渲染
tableTrClick();
}
});
}); $('#send').on('click', function(){
//获取选中数据
//发起请求
$.ajax({
type:"POST",
url:"<%=oper%>",
dataType:"json",
data:{"operKey":"mod","name":$("#name").val(),"value":$("#value").val(),
"path":$("#path").val(),"domain":$("#domain").val(),"version":$("#version").val(),
"comment":$("#comment").val()},
success:function(msg){
//更新页面
//1、关闭弹出层
g("win2").style.display = 'none';
g("mask").style.display = 'none';
//2、清除标题以下的数据
$('#cookieTable tr:gt(0)').empty();
//3、解析json,组装数组tr
//var jsonArr = eval("(" + msg + ")");
//4、添加到table中
//从新获取table
var $table = $('#cookieTable');
//遍历json
$.each(msg, function(i, item) {
var oneRow = "<tr>";
oneRow += "<td>" + item.name + "</td>";
oneRow += "<td>" + item.value + "</td>";
//oneRow += "<td>" + item.path + "</td>";
oneRow += "<td>" + item.domain + "</td>";
oneRow += "<td>" + item.version + "</td>";
oneRow += "<td>" + item.comment + "</td>";
oneRow += "</tr>"; $table.append(oneRow);
});
//从新渲染
tableTrClick();
}
});
}); } $(document).ready(function(){ operCookies();
tableTrClick();
}); //-->
</script>
代码逻辑实现
建立vo对象
package com.xiaof.cookie.vo; public class CookieVo {
private String name;
private String value;
private String path;
private String domain;
private int version;
private String comment;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
} @Override
public boolean equals(Object obj) {
if(obj == this)
return true; //根据name判断是否存在
if(obj instanceof CookieVo) {
CookieVo temp = (CookieVo) obj; if(temp.name.equals(name)) {
return true;
} else {
return false;
} } else {
return false;
} } @Override
public int hashCode() {
//hashcode的获取方式,主要用来在对应不同的容器中,根据hashcode来散列的对象的存放,特定容器可能影响效率
//并且在比对数据的时候,java是通过hashcode的散列码进行匹配的,故和equals一起重载
int result = 11;
result = result * 17 + (name == null ? 0 : name.hashCode());
result = result * 17 + (value == null ? 0 : value.hashCode()); return result;
} }
控制层代码逻辑
package com.xiaof.cookie; import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List; import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.junit.experimental.theories.PotentialAssignment;
import org.springframework.http.HttpRequest; import com.liferay.portal.kernel.json.JSONArray;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
import com.xiaof.cookie.vo.CookieVo; /**
* Portlet implementation class CookieOperator
*/
public class CookieOperator extends MVCPortlet { @Override
public void doView(RenderRequest renderRequest,
RenderResponse renderResponse) throws IOException, PortletException { //页面初始化的时候,获取所有的cookie
Cookie cookies[] = renderRequest.getCookies();
//传递cookies进入前台
// List<CookieVo> cookies1 = new ArrayList<CookieVo>();
// for(int i = 0; i < cookies.length; ++i) {
// CookieVo vo = new CookieVo();
// vo.setName(cookies[i].getName());
// vo.setValue(cookies[i].getValue());
// vo.setPath(cookies[i].getPath());
// vo.setDomain(cookies[i].getDomain());
// vo.setVersion(cookies[i].getVersion());
// vo.setComment(cookies[i].getComment());
// cookies1.add(vo);
// System.out.println("name=" + cookies[i].getName());
// System.out.println("value=" + cookies[i].getValue());
// System.out.println("path=" + cookies[i].getPath());
// System.out.println("version=" + cookies[i].getVersion());
// System.out.println("comment=" + cookies[i].getComment());
// System.out.println("domain=" + cookies[i].getDomain());
// } renderRequest.setAttribute("cookies1", cookies); super.doView(renderRequest, renderResponse);
} @Override
public void serveResource(ResourceRequest resourceRequest,
ResourceResponse resourceResponse) throws IOException,
PortletException {
//获取resourcid String resourceId = resourceRequest.getResourceID();
//获取原生httprequest
HttpServletRequest request = PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(resourceRequest));
HttpServletResponse response = PortalUtil.getHttpServletResponse(resourceResponse); //获取参数
if(resourceId.equals("cookieAjax")) {
//获取参数
String operKey = ParamUtil.get(resourceRequest, "operKey", "select");
//获取cookie的name
String cookieName = ParamUtil.get(resourceRequest, "selectCookieName", ""); if(operKey.equals("select")) {
//这个是查询所有的cookie
List<CookieVo> cookies1 = readCookies(request);
//返回json数据
JSONArray jsonArray = JSONFactoryUtil.createJSONArray();
//遍历组装
for(int i = 0; i < cookies1.size(); ++i) {
CookieVo cookieVo = cookies1.get(i);
JSONObject obj = JSONFactoryUtil.createJSONObject();
obj.put("name", cookieVo.getName());
obj.put("value", cookieVo.getValue());
obj.put("path", cookieVo.getPath());
obj.put("version", cookieVo.getVersion());
obj.put("comment", cookieVo.getComment());
obj.put("domain", cookieVo.getDomain());
jsonArray.put(obj);
} //最后返回
PrintWriter pw = response.getWriter();
pw.write(jsonArray.toString());
} else if(operKey.equals("mod")) {
String name = ParamUtil.get(request, "name", "");
String value = ParamUtil.get(request, "value", "");
String path = ParamUtil.get(request, "path", "");
String domain = ParamUtil.get(request, "domain", "");
int version = Integer.valueOf(ParamUtil.get(request, "version", "0") == ""?"0":"0");
String comment = ParamUtil.get(request, "comment", ""); //设置到对应的cookie
if(Validator.isNotNull(name) && Validator.isNotNull(value)) {
Cookie cookie = new Cookie(name, value);
if(Validator.isNotNull(path))
cookie.setPath(path);
if(Validator.isNotNull(domain))
cookie.setDomain(domain);
if(Validator.isNotNull(version))
cookie.setVersion(version);
if(Validator.isNotNull(comment))
cookie.setComment(comment); response.addCookie(cookie);
} //这个是查询所有的cookie
CookieVo newTemp = new CookieVo();
newTemp.setName(name); newTemp.setValue(value);newTemp.setComment(comment);
newTemp.setDomain(domain);newTemp.setPath(path);newTemp.setVersion(version);
List<CookieVo> cookies1 = readCookies(request); if(cookies1.contains(newTemp)) {
//如果包含更新值,注意是深拷贝
newTemp = cookies1.get(cookies1.indexOf(newTemp));
newTemp.setValue(value);newTemp.setComment(comment);
newTemp.setDomain(domain);newTemp.setPath(path);
newTemp.setVersion(version);
} else {
//不包含新增
cookies1.add(newTemp);
} //返回json数据
JSONArray jsonArray = JSONFactoryUtil.createJSONArray();
//遍历组装
for(int i = 0; i < cookies1.size(); ++i) {
CookieVo cookieVo = cookies1.get(i);
JSONObject obj = JSONFactoryUtil.createJSONObject(); obj.put("name", cookieVo.getName());
obj.put("value", cookieVo.getValue());
obj.put("path", cookieVo.getPath());
obj.put("version", cookieVo.getVersion());
obj.put("comment", cookieVo.getComment());
obj.put("domain", cookieVo.getDomain()); jsonArray.put(obj);
} //最后返回
PrintWriter pw = response.getWriter();
pw.write(jsonArray.toString()); } else if(operKey.equals("del")) {
//删除cookie
String name = ParamUtil.get(request, "selectCookieName", "");
// String path = ParamUtil.get(request, "path", "");
List<CookieVo> cookies1 = readCookies(request);
CookieVo newTemp = new CookieVo();
newTemp.setName(name);
cookies1.remove(newTemp);
Cookie cookies[] = request.getCookies(); for(Cookie cookie : cookies){
if(cookie.getName().equals(name)){
Cookie cookie1 = new Cookie(name, null);
cookie1.setMaxAge(0);// 立即销毁cookie
// if(Validator.isNotNull(path)) {
// cookie1.setPath(path);
// }
response.addCookie(cookie1);
break;
}
} //返回json数据
JSONArray jsonArray = JSONFactoryUtil.createJSONArray();
//遍历组装
for(int i = 0; i < cookies1.size(); ++i) {
CookieVo cookieVo = cookies1.get(i);
JSONObject obj = JSONFactoryUtil.createJSONObject(); obj.put("name", cookieVo.getName());
obj.put("value", cookieVo.getValue());
obj.put("path", cookieVo.getPath());
obj.put("version", cookieVo.getVersion());
obj.put("comment", cookieVo.getComment());
obj.put("domain", cookieVo.getDomain()); jsonArray.put(obj);
} //最后返回
PrintWriter pw = response.getWriter();
pw.write(jsonArray.toString());
}
} super.serveResource(resourceRequest, resourceResponse);
} private List<CookieVo> readCookies(HttpServletRequest request) {
List<CookieVo> cookies1 = new ArrayList<CookieVo>();
Cookie cookies[] = request.getCookies();
for(int i = 0; i < cookies.length; ++i) {
CookieVo vo = new CookieVo();
vo.setName(cookies[i].getName());
vo.setValue(cookies[i].getValue());
vo.setPath(cookies[i].getPath());
vo.setDomain(cookies[i].getDomain());
vo.setVersion(cookies[i].getVersion());
vo.setComment(cookies[i].getComment());
cookies1.add(vo);
} return cookies1;
} public void modCookie(ActionRequest request,ActionResponse response) throws IOException {
//获取表单参数,设置到cookie中
//name, value,path,domain,version,comment
HttpServletResponse httpServletResponse = PortalUtil.getHttpServletResponse(response); String jspPage = ParamUtil.getString(request, "jspPage"); String name = ParamUtil.get(request, "name", "");
String value = ParamUtil.get(request, "value", "");
String path = ParamUtil.get(request, "path", "");
String domain = ParamUtil.get(request, "domain", "");
int version = Integer.valueOf(ParamUtil.get(request, "version", "0") == ""?"0":"0");
String comment = ParamUtil.get(request, "comment", ""); //设置到对应的cookie
if(Validator.isNotNull(name) && Validator.isNotNull(value)) {
Cookie cookie = new Cookie(name, value);
if(Validator.isNotNull(path))
cookie.setPath(path);
if(Validator.isNotNull(domain))
cookie.setDomain(domain);
if(Validator.isNotNull(version))
cookie.setVersion(version);
if(Validator.isNotNull(comment))
cookie.setComment(comment); httpServletResponse.addCookie(cookie);
} response.sendRedirect("jspPage", jspPage);
} }