當前位置: 首頁>>代碼示例>>Java>>正文


Java ServletUriComponentsBuilder類代碼示例

本文整理匯總了Java中org.springframework.web.servlet.support.ServletUriComponentsBuilder的典型用法代碼示例。如果您正苦於以下問題:Java ServletUriComponentsBuilder類的具體用法?Java ServletUriComponentsBuilder怎麽用?Java ServletUriComponentsBuilder使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


ServletUriComponentsBuilder類屬於org.springframework.web.servlet.support包,在下文中一共展示了ServletUriComponentsBuilder類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: saveMedic

import org.springframework.web.servlet.support.ServletUriComponentsBuilder; //導入依賴的package包/類
@PostMapping
public ResponseEntity<?> saveMedic(@RequestBody Medic medic, BindingResult result) {
	medicValidator.validate(medic, result);

	if (result.hasErrors()) {
		return new ResponseEntity<>(result.getAllErrors(), HttpStatus.NOT_ACCEPTABLE);
	}
	
	Medic newMedic = medicService.save(medic);

	if (newMedic != null) {
		final URI location = ServletUriComponentsBuilder.fromCurrentServletMapping().path("/v1/medics/{id}").build()
				.expand(newMedic.getId()).toUri();

		final HttpHeaders headers = new HttpHeaders();
		headers.setLocation(location);

		return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
	}

	return new ResponseEntity<Void>(HttpStatus.SERVICE_UNAVAILABLE);
}
 
開發者ID:JUGIstanbul,項目名稱:second-opinion-api,代碼行數:23,代碼來源:MedicController.java

示例2: createUserProject

import org.springframework.web.servlet.support.ServletUriComponentsBuilder; //導入依賴的package包/類
@CrossOrigin
@RequestMapping(value = "/{id}/users/{userId}", method = RequestMethod.POST)
@ApiOperation(value = "Create a relation between user and project")
@ApiResponses(value = {
        @ApiResponse(code = 404, message = "ID of project or user invalid")
})
//TODO: Replace explicit user{id} with AuthN user id.
public ResponseEntity<?> createUserProject(@ApiParam(value = "ID of user", required = true)
                                              @PathVariable("userId") Integer userId,
                                           @ApiParam(value = "ID of project", required = true)
                                              @PathVariable("id") Integer projectId) {
    try {
        projectService.saveUserProject(userId, projectId);
        URI location = ServletUriComponentsBuilder.fromCurrentRequest()
                                                  .path("/{id}/users/{userId}")
                                                  .buildAndExpand(projectId, userId).toUri();
        return ResponseEntity.created(location).build();
    }catch (NullPointerException | UserProjectException e){
        throw new NotFoundException("ID of project or user invalid");
    }
}
 
開發者ID:Code4SocialGood,項目名稱:C4SG-Obsolete,代碼行數:22,代碼來源:ProjectController.java

示例3: createUser

import org.springframework.web.servlet.support.ServletUriComponentsBuilder; //導入依賴的package包/類
@PostMapping(value = {""})
public ResponseEntity<Void> createUser(
    @RequestBody @Valid UserForm form,
    HttpServletRequest req) {
    log.debug("user [email protected]" + form);

    User saved = this.userService.createUser(form);

    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(
        ServletUriComponentsBuilder
            .fromContextPath(req)
            .path("/users/{username}")
            .buildAndExpand(saved.getId()).toUri()
    );

    return new ResponseEntity<>(headers, HttpStatus.CREATED);
}
 
開發者ID:hantsy,項目名稱:spring-microservice-sample,代碼行數:19,代碼來源:UserController.java

示例4: createPost

import org.springframework.web.servlet.support.ServletUriComponentsBuilder; //導入依賴的package包/類
@PostMapping()
public ResponseEntity<Void> createPost(@RequestBody @Valid PostForm post, HttpServletRequest request) {

    log.debug("create a new [email protected]" + post);

    Post saved = this.postService.createPost(post);

    log.debug("saved post id is @" + saved.getId());
    URI loacationHeader = ServletUriComponentsBuilder
        .fromContextPath(request)
        .path("/posts/{slug}")
        .buildAndExpand(saved.getSlug())
        .toUri();

    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(loacationHeader);

    return new ResponseEntity<>(headers, HttpStatus.CREATED);
}
 
開發者ID:hantsy,項目名稱:spring-microservice-sample,代碼行數:20,代碼來源:PostController.java

示例5: createComment

import org.springframework.web.servlet.support.ServletUriComponentsBuilder; //導入依賴的package包/類
@PostMapping(value = "/{slug}/comments")
public ResponseEntity<Void> createComment(
    @PathVariable("slug") @NotNull String slug, @RequestBody CommentForm comment, HttpServletRequest request) {

    log.debug("new comment of [email protected]" + slug + ", comment" + comment);

    Comment _comment = Comment.builder()
        .post(new Slug(slug))
        .content(comment.getContent())
        .build();

    Comment saved = this.commentRepository.save(_comment);

    log.debug("saved comment @" + saved.getId());

    URI location = ServletUriComponentsBuilder
        .fromContextPath(request)
        .path("/posts/{slug}/comments/{id}")
        .buildAndExpand(slug, saved.getId())
        .toUri();

     return ResponseEntity.created(location).build();
}
 
開發者ID:hantsy,項目名稱:spring-microservice-sample,代碼行數:24,代碼來源:PostController.java

示例6: createPlugin

import org.springframework.web.servlet.support.ServletUriComponentsBuilder; //導入依賴的package包/類
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<Void> createPlugin(@RequestBody PluginIdContainer pluginIdContainer) {
    if (null != pluginRepository.findByPluginNameEquals(pluginIdContainer.getPluginId())) {
        return new ResponseEntity<>(HttpStatus.CONFLICT);
    }

    PluginEntity pluginEntity = new PluginEntity(pluginIdContainer.getPluginId(), pluginIdContainer.getDefaultVersion(),
            pluginIdContainer.getDocumentationLink(), new ArrayList<>());
    pluginEntity = pluginRepository.save(pluginEntity);

    for (PluginVersion pluginVersion : pluginIdContainer.getVersions().values()) {
        pluginEntity.getVersions().add(Transformer.fromPluginVersion(pluginEntity, pluginVersion));
    }

    pluginRepository.save(pluginEntity);

    URI uri = ServletUriComponentsBuilder
            .fromCurrentRequest().path("/{id}")
            .buildAndExpand(pluginIdContainer.getPluginId()).toUri();

    return ResponseEntity.created(uri).build();
}
 
開發者ID:linkedin,項目名稱:custom-gradle-plugin-portal,代碼行數:23,代碼來源:PluginsResource.java

示例7: addVersion

import org.springframework.web.servlet.support.ServletUriComponentsBuilder; //導入依賴的package包/類
@RequestMapping(value = "/{id:.+}", method = RequestMethod.POST)
public ResponseEntity<Void> addVersion(@PathVariable("id") String id,
                                       @RequestBody PluginVersion version) {
    PluginEntity plugin = pluginRepository.findByPluginNameEquals(id);

    if (null == plugin) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    if (null != versionRepository.findByPluginEntityAndPluginVersionEquals(plugin, version.getVersion())) {
        return new ResponseEntity<>(HttpStatus.CONFLICT);
    }

    PluginVersionEntity versionEntity = Transformer.fromPluginVersion(plugin, version);
    plugin.getVersions().add(versionEntity);
    pluginRepository.save(plugin);

    URI uri = ServletUriComponentsBuilder
            .fromCurrentRequest().path("/{id}")
            .buildAndExpand(version.getVersion()).toUri();

    return ResponseEntity.created(uri).build();
}
 
開發者ID:linkedin,項目名稱:custom-gradle-plugin-portal,代碼行數:24,代碼來源:PluginsResource.java

示例8: getLocaleUrl

import org.springframework.web.servlet.support.ServletUriComponentsBuilder; //導入依賴的package包/類
public String getLocaleUrl(String locale) throws Exception {
    UriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentRequest().replaceQueryParam("locale", locale);
    RequestAttributes attributes = org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes();
    if (attributes instanceof ServletRequestAttributes) {
        int statusCode = ((ServletRequestAttributes) attributes).getResponse().getStatus();
        switch (statusCode) {
            case 200:
                break;
            case 404:
                builder.replacePath("" + statusCode);
                break;
            default:
                builder.replacePath("error");
        }
    }
    URI serverUri = new URI(this.casConfigurationProperties.getServer().getName());
    if ("https".equalsIgnoreCase(serverUri.getScheme())) {
        builder.port((serverUri.getPort() == -1) ? 443 : serverUri.getPort());
    }
    return builder.scheme(serverUri.getScheme()).host(serverUri.getHost()).build(true).toUriString();
}
 
開發者ID:e-gov,項目名稱:TARA-Server,代碼行數:22,代碼來源:TaraProperties.java

示例9: setup

import org.springframework.web.servlet.support.ServletUriComponentsBuilder; //導入依賴的package包/類
@BeforeClass
public static void setup() {
	UriComponentsBuilder builder = ServletUriComponentsBuilder.fromUriString("dummy");
	linkHeaderBuilder = new HateoasLinkHeaderBuilder(builder);

	Pageable nextPageable = mock(Pageable.class);
	when(nextPageable.getPageNumber()).thenReturn(4);

	Pageable prevPageable = mock(Pageable.class);
	when(prevPageable.getPageNumber()).thenReturn(2);

	page = mock(Page.class);
	when(page.nextPageable()).thenReturn(nextPageable);
	when(page.previousPageable()).thenReturn(prevPageable);
	when(page.getTotalPages()).thenReturn(6);
}
 
開發者ID:cmateosl,項目名稱:role-api,代碼行數:17,代碼來源:HateoasLinkHeaderBuilderTest.java

示例10: createUserOrganization

import org.springframework.web.servlet.support.ServletUriComponentsBuilder; //導入依賴的package包/類
@CrossOrigin
@RequestMapping(value = "/{id}/users/{userId}", method = RequestMethod.POST)
@ApiOperation(value = "Create a relation between user and organization")
@ApiResponses(value = { @ApiResponse(code = 404, message = "ID of organization or user invalid") })
// TODO: Replace explicit user{id} with AuthN user id.
public ResponseEntity<?> createUserOrganization(
		@ApiParam(value = "ID of user", required = true) @PathVariable("userId") Integer userId,
		@ApiParam(value = "ID of organization", required = true) @PathVariable("id") Integer organizationId) {
	
   	System.out.println("************** OrganizationController.createUserOrganization()" 
               + ": userId=" + userId  
               + "; organizationId=" + organizationId  
               + " **************");
   	
	try {
		organizationService.saveUserOrganization(userId, organizationId);
		URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}/users/{userId}")
				.buildAndExpand(organizationId, userId).toUri();
		return ResponseEntity.created(location).build();
	} catch (NullPointerException | UserOrganizationException e) {
		throw new NotFoundException("ID of organization or user invalid, or relationship already exist");
	}
}
 
開發者ID:Code4SocialGood,項目名稱:c4sg-services,代碼行數:24,代碼來源:OrganizationController.java

示例11: postUser

import org.springframework.web.servlet.support.ServletUriComponentsBuilder; //導入依賴的package包/類
@ApiOperation(value = "新增用戶")
@PostMapping
public ResponseEntity<?> postUser(@RequestBody User user) {
    Optional<User> result = userService.getUserByName(user.getUsername());

    if (!result.isPresent()) {
        userService.addUser(user);
        URI location = ServletUriComponentsBuilder
                .fromCurrentRequest()
                .path("/{id}")
                .buildAndExpand(user.getId())
                .toUri();
        return ResponseEntity.created(location).body(user);
    } else {
        return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).build();
    }
}
 
開發者ID:ustcwudi,項目名稱:springboot-seed,代碼行數:18,代碼來源:UserController.java

示例12: connectToProxiedTarget

import org.springframework.web.servlet.support.ServletUriComponentsBuilder; //導入依賴的package包/類
private void connectToProxiedTarget(WebSocketSession session) {
	URI sessionUri = session.getUri();
	ZuulWebSocketProperties.WsBrokerage wsBrokerage = getWebSocketBrokarage(
			sessionUri);

	Assert.notNull(wsBrokerage, "wsBrokerage");

	String path = getWebSocketServerPath(wsBrokerage, sessionUri);
	Assert.notNull(path, "Web socket uri path");

	String routeHost = zuulPropertiesResolver.getRouteHost(wsBrokerage);
	Assert.notNull(routeHost, "routeHost");

       String uri = ServletUriComponentsBuilder
               .fromHttpUrl(routeHost)
               .path(path)
               .replaceQuery(sessionUri.getQuery())
               .toUriString();

	ProxyWebSocketConnectionManager connectionManager = new ProxyWebSocketConnectionManager(
			messagingTemplate, stompClient, session, headersCallback, uri);
	connectionManager.errorHandler(this.errorHandler);
	managers.put(session, connectionManager);
	connectionManager.start();
}
 
開發者ID:mthizo247,項目名稱:spring-cloud-netflix-zuul-websocket,代碼行數:26,代碼來源:ProxyWebSocketHandler.java

示例13: postClass

import org.springframework.web.servlet.support.ServletUriComponentsBuilder; //導入依賴的package包/類
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<?> postClass(JwtAuthenticationToken token, @RequestBody Class klass) {
  UserContext userContext = (UserContext) token.getPrincipal();
  Class saved = classService.save(userContext.getTenantId(), userContext.getOrgId(), klass);
  HttpHeaders httpHeaders = new HttpHeaders();
  httpHeaders.setLocation(ServletUriComponentsBuilder
      .fromCurrentRequest().path("/{id}")
      .buildAndExpand(saved.getSourcedId()).toUri());
  return new ResponseEntity<>(saved, httpHeaders, HttpStatus.CREATED);
}
 
開發者ID:Apereo-Learning-Analytics-Initiative,項目名稱:OpenLRW,代碼行數:11,代碼來源:ClassController.java

示例14: createTag

import org.springframework.web.servlet.support.ServletUriComponentsBuilder; //導入依賴的package包/類
/**
 * Process POST /tags request
 * Create a tag
 *
 * @param tag tag to create
 * @return response entity
 */
@Override
public ResponseEntity<Object> createTag(@ApiParam(value = "Create a tag", required = true) @RequestBody Tag tag) {

    // Create tag in database
    TagEntity entity = toTagEntity(tag);
    tagRepository.save(entity);

    URI location = ServletUriComponentsBuilder.fromCurrentRequest()
            .path("/{id}")
            .buildAndExpand(entity.getId())
            .toUri();

    // Update tag's URL in database
    entity.setUrl(location.toString());
    tagRepository.save(entity);

    return ResponseEntity.created(location).build();
}
 
開發者ID:PestaKit,項目名稱:microservice-email,代碼行數:26,代碼來源:TagApiController.java

示例15: createTemplate

import org.springframework.web.servlet.support.ServletUriComponentsBuilder; //導入依賴的package包/類
/**
 * Process POST /templates request
 * Create a template
 *
 * @param template template to create
 * @return response entity
 */
@Override
public ResponseEntity<Object> createTemplate(@ApiParam(value = "Create a template", required = true) @RequestBody TemplateBody template) {

    // Create template in database
    TemplateEntity entity = toTemplateEntity(template);

    templateRepository.save(entity);

    URI location = ServletUriComponentsBuilder.fromCurrentRequest()
            .path("/{id}")
            .buildAndExpand(entity.getId())
            .toUri();

    // Update template's URL in database
    entity.setUrl(location.toString());
    templateRepository.save(entity);

    return ResponseEntity.created(location).build();
}
 
開發者ID:PestaKit,項目名稱:microservice-email,代碼行數:27,代碼來源:TemplateApiController.java


注:本文中的org.springframework.web.servlet.support.ServletUriComponentsBuilder類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。