下面列出了怎么用org.springframework.web.bind.annotation.CookieValue的API类实例代码及写法,或者点击链接到github查看源代码。
@RequestMapping({
"/",
"/login",
"repositories",
"project-requests",
"workbench",
"branches",
"settings",
"screenshots"
})
@ResponseBody
ModelAndView getIndex(
HttpServletRequest httpServletRequest,
@CookieValue(value = "locale", required = false, defaultValue = "en") String localeCookieValue) throws MalformedURLException, IOException {
ModelAndView index = new ModelAndView("index");
index.addObject("locale", getValidLocaleFromCookie(localeCookieValue));
index.addObject("ict", httpServletRequest.getHeaders("X-Mojito-Ict").hasMoreElements());
index.addObject("csrfToken", csrfTokenController.getCsrfToken(httpServletRequest));
index.addObject("username", getUsername());
index.addObject("contextPath", contextPath);
index.addObject("appConfig", objectMapper.writeValueAsStringUnchecked(reactAppConfig));
return index;
}
/**
* 详情.
*/
@RequestMapping("disk-view")
public String view(
@RequestParam("id") Long id,
@CookieValue(value = "share", required = false) String sharePassword,
Model model) {
DiskShare diskShare = diskShareManager.get(id);
if ("private".equals(diskShare.getShareType())) {
if (!diskShare.getSharePassword().equals(sharePassword)) {
return "disk/disk-code";
}
}
model.addAttribute("diskShare", diskShare);
return "disk/disk-view";
}
public static MethodParameter interfaceMethodParameter(MethodParameter parameter) {
boolean hasAnnotations =
parameter.hasParameterAnnotation(RequestParam.class) || parameter.hasParameterAnnotation(PathVariable.class)
|| parameter.hasParameterAnnotation(RequestHeader.class)
|| parameter.hasParameterAnnotation(CookieValue.class)
|| parameter.hasParameterAnnotation(RequestBody.class);
if (!hasAnnotations) {
for (Class<?> itf : parameter.getDeclaringClass().getInterfaces()) {
try {
Method method =
itf.getMethod(parameter.getMethod().getName(), parameter.getMethod().getParameterTypes());
return new InterfaceMethodParameter(method, parameter.getParameterIndex());
} catch (NoSuchMethodException e) {
continue;
}
}
}
return parameter;
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(@RequestParam("username") String username, @RequestParam("password") String password,
@RequestParam("code") String code, @CookieValue("kaptchaOwner") String kaptchaOwner, Model model, HttpServletResponse response) {
String kaptcha = null;
if (StringUtils.isNotBlank(kaptchaOwner)){
String redisKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
kaptcha = (String) redisTemplate.opsForValue().get(redisKey);
}
if (StringUtils.isBlank(kaptcha) || StringUtils.isBlank(code) || !kaptcha.equalsIgnoreCase(code)){
model.addAttribute("codeMsg", "验证码不正确~");
return "/site/login";
}
Map<String, Object> map = iUserService.login(username, password);
if (map.containsKey("ticket")) {
Cookie cookie = new Cookie("ticket", map.get(Const.ticket.TICKET).toString());
cookie.setPath(contextPath); // cookie 的生效范围
cookie.setMaxAge(Const.loginStatus.DEFAULT_EXPIRED_SECONDS);
response.addCookie(cookie);
return "redirect:/index";
}else {
model.addAttribute("usernameMsg", map.get("usernameMsg"));
model.addAttribute("passwordMsg", map.get("passwordMsg"));
return "/site/login";
}
}
@RequestMapping(value = { "{path:(?!staticResources).*$}", "{path:(?!staticResources).*$}/**" })
public Object resourceController(ModelMap model, HttpServletRequest req, HttpServletResponse res, Locale locale, @RequestParam(value = "output", defaultValue = "") String output, @CookieValue(value = "colorPair", defaultValue = "") String colorPair) throws UnsupportedEncodingException {
if (colorPair.equals("")) {
colorPair = conf.getRandomColorPair();
Cookie c = new Cookie("colorPair", colorPair);
c.setPath("/");
res.addCookie(c);
}
return resource(conf, model, req, res, locale, output, "", colorPair);
}
@SuppressWarnings("unused")
public void params(
@CookieValue("name") HttpCookie cookie,
@CookieValue(name = "name", defaultValue = "bar") String cookieString,
String stringParam,
@CookieValue Mono<String> monoCookie) {
}
@RequestMapping(value = "/404")
public String error404(HttpServletResponse res, ModelMap model, @RequestParam(value = "error", defaultValue = "") String error, @CookieValue(value = "colorPair", defaultValue = "") String colorPair, @RequestParam(value = "IRI", defaultValue = "") String IRI, @RequestParam(value = "endpoint", defaultValue = "") String endpoint) {
System.out.println("not found " + error + " -- " + IRI + " -- " + endpoint);
/* spring bug? */
model.addAttribute("IRI", IRI);
model.addAttribute("endpoint", endpoint);
model.addAttribute("error", error);
model.addAttribute("conf", conf);
colors(colorPair, res, model);
model.addAttribute("statusCode", "404");
res.setStatus(HttpServletResponse.SC_NOT_FOUND);
return "error";
}
public String handle(
@CookieValue("cookie") int cookieV,
@PathVariable("pathvar") String pathvarV,
@RequestHeader("header") String headerV,
@RequestHeader(defaultValue = "#{systemProperties.systemHeader}") String systemHeader,
@RequestHeader Map<String, Object> headerMap,
@RequestParam("dateParam") Date dateParam,
@RequestParam Map<String, Object> paramMap,
String paramByConvention,
@Value("#{request.contextPath}") String value,
@ModelAttribute("modelAttr") @Valid TestBean modelAttr,
Errors errors,
TestBean modelAttrByConvention,
Color customArg,
HttpServletRequest request,
HttpServletResponse response,
@SessionAttribute TestBean sessionAttribute,
@RequestAttribute TestBean requestAttribute,
User user,
@ModelAttribute OtherUser otherUser,
Model model,
UriComponentsBuilder builder) {
model.addAttribute("cookie", cookieV).addAttribute("pathvar", pathvarV).addAttribute("header", headerV)
.addAttribute("systemHeader", systemHeader).addAttribute("headerMap", headerMap)
.addAttribute("dateParam", dateParam).addAttribute("paramMap", paramMap)
.addAttribute("paramByConvention", paramByConvention).addAttribute("value", value)
.addAttribute("customArg", customArg).addAttribute(user)
.addAttribute("sessionAttribute", sessionAttribute)
.addAttribute("requestAttribute", requestAttribute)
.addAttribute("url", builder.path("/path").build().toUri());
assertNotNull(request);
assertNotNull(response);
return "viewName";
}
/**
* Build params parameter.
*
* @param parameterInfo the parameter info
* @param components the components
* @param requestMethod the request method
* @param jsonView the json view
* @return the parameter
*/
public Parameter buildParams(ParameterInfo parameterInfo, Components components,
RequestMethod requestMethod, JsonView jsonView) {
MethodParameter methodParameter = parameterInfo.getMethodParameter();
RequestHeader requestHeader = parameterInfo.getRequestHeader();
RequestParam requestParam = parameterInfo.getRequestParam();
PathVariable pathVar = parameterInfo.getPathVar();
CookieValue cookieValue = parameterInfo.getCookieValue();
RequestInfo requestInfo;
if (requestHeader != null) {
requestInfo = new RequestInfo(ParameterIn.HEADER.toString(), parameterInfo.getpName(), requestHeader.required(),
requestHeader.defaultValue());
return buildParam(parameterInfo, components, requestInfo, jsonView);
}
else if (requestParam != null && !parameterBuilder.isFile(parameterInfo.getMethodParameter())) {
requestInfo = new RequestInfo(ParameterIn.QUERY.toString(), parameterInfo.getpName(), requestParam.required() && !methodParameter.isOptional(),
requestParam.defaultValue());
return buildParam(parameterInfo, components, requestInfo, jsonView);
}
else if (pathVar != null) {
requestInfo = new RequestInfo(ParameterIn.PATH.toString(), parameterInfo.getpName(), !methodParameter.isOptional(), null);
return buildParam(parameterInfo, components, requestInfo, jsonView);
}
else if (cookieValue != null) {
requestInfo = new RequestInfo(ParameterIn.COOKIE.toString(), parameterInfo.getpName(), cookieValue.required(),
cookieValue.defaultValue());
return buildParam(parameterInfo, components, requestInfo, jsonView);
}
// By default
DelegatingMethodParameter delegatingMethodParameter = (DelegatingMethodParameter) methodParameter;
if (RequestMethod.GET.equals(requestMethod)
|| (parameterInfo.getParameterModel() != null && (ParameterIn.PATH.toString().equals(parameterInfo.getParameterModel().getIn())))
|| delegatingMethodParameter.isParameterObject())
return this.buildParam(QUERY_PARAM, components, parameterInfo, !methodParameter.isOptional(), null, jsonView);
return null;
}
/**
* Instantiates a new Parameter info.
*
* @param pName the p name
* @param methodParameter the method parameter
*/
public ParameterInfo(String pName, MethodParameter methodParameter) {
this.methodParameter = methodParameter;
this.requestHeader = methodParameter.getParameterAnnotation(RequestHeader.class);
this.requestParam = methodParameter.getParameterAnnotation(RequestParam.class);
this.pathVar = methodParameter.getParameterAnnotation(PathVariable.class);
this.cookieValue = methodParameter.getParameterAnnotation(CookieValue.class);
this.pName = calculateName(pName, requestHeader, requestParam, pathVar, cookieValue);
}
/**
* Calculate name string.
*
* @param pName the p name
* @param requestHeader the request header
* @param requestParam the request param
* @param pathVar the path var
* @param cookieValue the cookie value
* @return the string
*/
private String calculateName(String pName, RequestHeader requestHeader, RequestParam requestParam, PathVariable pathVar, CookieValue cookieValue) {
String name = pName;
if (requestHeader != null && StringUtils.isNotEmpty(requestHeader.value()))
name = requestHeader.value();
else if (requestParam != null && StringUtils.isNotEmpty(requestParam.value()))
name = requestParam.value();
else if (pathVar != null && StringUtils.isNotEmpty(pathVar.value()))
name = pathVar.value();
else if (cookieValue != null && StringUtils.isNotEmpty(cookieValue.value()))
name = cookieValue.value();
return name;
}
@RequestMapping("/api/translate/nl")
public ResponseEntity translateNL(
@CookieValue(value = COOKIE_NAME, defaultValue = USER_NONE) String userId,
@RequestBody TranslateNLRequest req
) {
if (userId.equals(USER_NONE) || !redisService.hasUser(userId)) {
return ResponseEntity.status(401).body(new MessageResponse("You are not connected to a Database."));
}
return ResponseEntity.ok(new TranslateResponse(
"We are still writing the code to translate your natural language input..."
));
}
@SuppressWarnings("unused")
public void params(
@CookieValue("name") HttpCookie cookie,
@CookieValue(name = "name", defaultValue = "bar") String cookieString,
String stringParam,
@CookieValue Mono<String> monoCookie) {
}
@RequestMapping(value = "/400")
public String error400(HttpServletResponse res, ModelMap model, @RequestParam(value = "IRI", defaultValue = "") String IRI, @CookieValue(value = "colorPair", defaultValue = "") String colorPair) {
System.out.println("error on " + IRI);
/* spring bug? */
model.addAttribute("IRI", IRI.replaceAll("(http://.+),http://.+", "$1"));
model.addAttribute("conf", conf);
colors(colorPair, res, model);
model.addAttribute("statusCode", "400");
res.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
return "error";
}
public String handle(
@CookieValue("cookie") int cookieV,
@PathVariable("pathvar") String pathvarV,
@RequestHeader("header") String headerV,
@RequestHeader(defaultValue = "#{systemProperties.systemHeader}") String systemHeader,
@RequestHeader Map<String, Object> headerMap,
@RequestParam("dateParam") Date dateParam,
@RequestParam Map<String, Object> paramMap,
String paramByConvention,
@Value("#{request.contextPath}") String value,
@ModelAttribute("modelAttr") @Valid TestBean modelAttr,
Errors errors,
TestBean modelAttrByConvention,
Color customArg,
HttpServletRequest request,
HttpServletResponse response,
@SessionAttribute TestBean sessionAttribute,
@RequestAttribute TestBean requestAttribute,
User user,
@ModelAttribute OtherUser otherUser,
Model model,
UriComponentsBuilder builder) {
model.addAttribute("cookie", cookieV).addAttribute("pathvar", pathvarV).addAttribute("header", headerV)
.addAttribute("systemHeader", systemHeader).addAttribute("headerMap", headerMap)
.addAttribute("dateParam", dateParam).addAttribute("paramMap", paramMap)
.addAttribute("paramByConvention", paramByConvention).addAttribute("value", value)
.addAttribute("customArg", customArg).addAttribute(user)
.addAttribute("sessionAttribute", sessionAttribute)
.addAttribute("requestAttribute", requestAttribute)
.addAttribute("url", builder.path("/path").build().toUri());
assertNotNull(request);
assertNotNull(response);
return "viewName";
}
@RequestMapping("/api/connect/user")
public ResponseEntity connectUser(
@CookieValue(value = COOKIE_NAME, defaultValue = USER_NONE) String userId,
HttpServletResponse res
) throws IOException {
if (userId.equals(USER_NONE) || !redisService.hasUser(userId)) {
return ResponseEntity.ok(new StatusMessageResponse(false, "No user session found"));
} else {
redisService.refreshUser(userId);
UserSession session = redisService.getUserSession(userId);
cookieService.setUserIdCookie(res, userId);
return ResponseEntity.ok(new ConnectResponse(true, session.getDbConnectionConfig().getUrl()));
}
}
@GetMapping("/login")
public String login(@CookieValue(value = SessionParam.SESSION_ID_COOKIE, required = false) String uuid) {
if (StringUtils.isEmpty(uuid)) {
return "management/login";
}
User u = blogContext.getSessionUser(uuid);
if (u != null && u.getDefaultRoleId() == 1) {
return "management/index";
}
return "management/login";
}
/**
* API for proctor tests with filtering functionality
*
* @param branch environment
* @param limit number of tests to return
* @param q query string to search
* @param filterType {@link FilterType}
* @param filterActive {@link FilterActive}
* @param sort {@link Sort}
* @param favoriteTestsRaw comma-separated favorite tests saved in cookie
* @return JSON of TestsResponse
*/
@ApiOperation(value = "Proctor tests with filters", response = List.class)
@GetMapping
public JsonView viewTestNames(
@RequestParam(defaultValue = "trunk") final String branch,
@RequestParam(defaultValue = "100") final int limit,
@RequestParam(defaultValue = "") final String q,
@RequestParam(defaultValue = "ALL") final FilterType filterType,
@RequestParam(defaultValue = "ALL") final FilterActive filterActive,
@RequestParam(defaultValue = "FAVORITESFIRST") final Sort sort,
@CookieValue(value = "FavoriteTests", defaultValue = "") final String favoriteTestsRaw
) throws StoreException {
final Set<String> favoriteTestNames = Sets.newHashSet(Splitter.on(",").split(favoriteTestsRaw));
final Environment environment = determineEnvironmentFromParameter(branch);
final TestMatrixDefinition testMatrixDefinition = getCurrentMatrix(environment).getTestMatrixDefinition();
final Map<String, TestDefinition> allTestMatrix = testMatrixDefinition != null
? testMatrixDefinition.getTests()
: Collections.emptyMap();
final List<String> queries = Arrays.asList(q.split("\\s+"));
final Map<String, TestDefinition> matchingTestMatrix = Maps.filterEntries(allTestMatrix,
e -> e != null && matchesAllIgnoreCase(e.getKey(), e.getValue(), filterType, queries)
&& matchesFilterActive(e.getValue().getAllocations(), filterActive)
);
final List<ProctorTest> searchResult =
toProctorTests(matchingTestMatrix, determineStoreFromEnvironment(environment))
.stream()
.sorted(getComparator(sort, favoriteTestNames))
.limit(limit)
.collect(toList());
return new JsonView(new TestsResponse(searchResult, allTestMatrix.size(), searchResult.size()));
}
@Override
public String getParameterName(CookieValue annotation) {
String value = annotation.value();
if (value.isEmpty()) {
value = annotation.name();
}
return value;
}
@GetMapping("/{token:.+}")
public ResponseEntity validateToken(@CookieValue("time") String time,
@RequestHeader("Authorization") String[] authorization, @PathVariable String token,
@RequestParam String url) {
String temp = tokens.get(token);
String auth = authorization[0];
if (auth.equals("dummy")) {
auth = authorization[1];
}
if (temp.equals(time) && auth.equals(token + time + url)) {
return ResponseEntity.ok().build();
} else {
return ResponseEntity.badRequest().build();
}
}
@ResponseStatus(value = HttpStatus.NOT_ACCEPTABLE, reason = "unhandled encoding")
@RequestMapping(value = "/406")
public String error406(HttpServletResponse res, ModelMap model, @CookieValue(value = "colorPair") String colorPair) {
System.out.println("not acceptable");
model.addAttribute("statusCode", "406");
model.addAttribute("conf", conf);
colors(colorPair, res, model);
res.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
return "error";
}
@RequestMapping("EDIT")
@RenderMapping
public void myHandle(@RequestParam("param1") String p1, @RequestParam("param2") int p2,
@RequestHeader("header1") long h1, @CookieValue("cookie1") Cookie c1,
RenderResponse response) throws IOException {
response.getWriter().write("test-" + p1 + "-" + p2 + "-" + h1 + "-" + c1.getValue());
}
@RequestMapping(value = { "/500", "/error" })
public String error500(HttpServletResponse res, ModelMap model, @RequestParam(value = "error", defaultValue = "") String error, @CookieValue(value = "colorPair", defaultValue = "") String colorPair, @RequestParam(value = "IRI", defaultValue = "") String IRI, @RequestParam(value = "endpoint", defaultValue = "") String endpoint) {
System.out.println("error on " + error + " -- " + IRI + " -- " + endpoint);
/* spring bug? */
model.addAttribute("IRI", IRI);
model.addAttribute("endpoint", endpoint);
model.addAttribute("error", error);
model.addAttribute("conf", conf);
colors(colorPair, res, model);
model.addAttribute("statusCode", "500");
res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return "error";
}
@RequestMapping(method = RequestMethod.GET)
public void handle(@CookieValue("date") Date date, Writer writer) throws IOException {
assertEquals("Invalid path variable value", new GregorianCalendar(2008, 10, 18).getTime(), date);
Calendar c = new GregorianCalendar();
c.setTime(date);
writer.write("test-" + c.get(Calendar.YEAR));
}
@Override
protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) {
CookieValue ann = parameter.getParameterAnnotation(CookieValue.class);
Assert.state(ann != null, "No CookieValue annotation");
return new CookieValueNamedValueInfo(ann);
}
private CookieValueNamedValueInfo(CookieValue annotation) {
super(annotation.name(), annotation.required(), annotation.defaultValue());
}
public void params(@CookieValue("name") Cookie cookie,
@CookieValue(name = "name", defaultValue = "bar") String cookieString) {
}
@RequestMapping("/myPath2.do")
public void myHandle(@RequestParam("param1") String p1, @RequestParam("param2") int p2,
@RequestHeader("header1") long h1, @CookieValue(name = "cookie1") Cookie c1,
HttpServletResponse response) throws IOException {
response.getWriter().write("test-" + p1 + "-" + p2 + "-" + h1 + "-" + c1.getValue());
}
@RequestMapping("/myPath2.do")
public void myHandle(@RequestParam("param1") String p1, int param2, HttpServletResponse response,
@RequestHeader("header1") String h1, @CookieValue("cookie1") String c1) throws IOException {
response.getWriter().write("test-" + p1 + "-" + param2 + "-" + h1 + "-" + c1);
}
@RequestMapping("/myPath2.do")
public void myHandle(@RequestParam("param1") T p1, int param2, @RequestHeader Integer header1,
@CookieValue int cookie1, HttpServletResponse response) throws IOException {
response.getWriter().write("test-" + p1 + "-" + param2 + "-" + header1 + "-" + cookie1);
}
如果文章对你有帮助,欢迎点击上方按钮打赏作者