下面列出了org.springframework.http.MediaType#TEXT_HTML 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private MediaType getContentType(String contentType) {
if (contentType.equalsIgnoreCase(MediaType.IMAGE_GIF_VALUE)) {
return MediaType.IMAGE_GIF;
} else if (contentType.equalsIgnoreCase(MediaType.IMAGE_PNG_VALUE)) {
return MediaType.IMAGE_PNG;
} else if (contentType.equalsIgnoreCase(MediaType.IMAGE_JPEG_VALUE)) {
return MediaType.IMAGE_JPEG;
} else if (contentType.equalsIgnoreCase(MediaType.TEXT_PLAIN_VALUE)) {
return MediaType.TEXT_PLAIN;
} else if (contentType.equalsIgnoreCase(MediaType.TEXT_XML_VALUE)) {
return MediaType.TEXT_XML;
} else if (contentType.equalsIgnoreCase(MediaType.TEXT_HTML_VALUE)) {
return MediaType.TEXT_HTML;
}
return MediaType.APPLICATION_OCTET_STREAM;
}
@Test
public void nestedViewResolverIsNotSpringBean() throws Exception {
StaticWebApplicationContext webAppContext = new StaticWebApplicationContext();
webAppContext.setServletContext(new MockServletContext());
webAppContext.refresh();
InternalResourceViewResolver nestedResolver = new InternalResourceViewResolver();
nestedResolver.setApplicationContext(webAppContext);
nestedResolver.setViewClass(InternalResourceView.class);
viewResolver.setViewResolvers(new ArrayList<>(Arrays.asList(nestedResolver)));
FixedContentNegotiationStrategy fixedStrategy = new FixedContentNegotiationStrategy(MediaType.TEXT_HTML);
viewResolver.setContentNegotiationManager(new ContentNegotiationManager(fixedStrategy));
viewResolver.afterPropertiesSet();
String viewName = "view";
Locale locale = Locale.ENGLISH;
View result = viewResolver.resolveViewName(viewName, locale);
assertNotNull("Invalid view", result);
}
@Test // gh-22853
public void matchAndCompare() {
ContentNegotiationManager manager = new ContentNegotiationManager(
new HeaderContentNegotiationStrategy(),
new FixedContentNegotiationStrategy(MediaType.TEXT_HTML));
ProducesRequestCondition none = new ProducesRequestCondition(new String[0], null, manager);
ProducesRequestCondition html = new ProducesRequestCondition(new String[] {"text/html"}, null, manager);
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Accept", "*/*");
ProducesRequestCondition noneMatch = none.getMatchingCondition(request);
ProducesRequestCondition htmlMatch = html.getMatchingCondition(request);
assertEquals(1, noneMatch.compareTo(htmlMatch, request));
}
@GetMapping("/{reportId:\\d+}/view.action")
public String view(ComAdmin admin, @PathVariable int reportId, Model model) {
String reportContent = recipientsReportService.getImportReportContent(admin.getCompanyID(), reportId);
if (StringUtils.isBlank(reportContent)) {
reportContent = I18nString.getLocaleString("recipient.reports.notAvailable", admin.getLocale());
}
if (RecipientReportUtils.resolveMediaType(reportContent) != MediaType.TEXT_HTML) {
reportContent = reportContent.replace("\r\n", "\n").replace("\n", "<br />\n");
}
model.addAttribute("reportId", reportId);
// Escape all text, even html, so it can be viewed in an iframe as docsource
model.addAttribute("reportContentEscaped", StringEscapeUtils.escapeHtml4(reportContent));
writeUserActivityLog(admin, "Import/Export logs view", "Report ID: " + reportId);
return "recipient_report_view";
}
private DownloadRecipientReport getDownloadReportData(ComAdmin admin, String filename, String reportContent) throws UnsupportedEncodingException {
DownloadRecipientReport recipientReport = new DownloadRecipientReport();
if (StringUtils.isBlank(reportContent)) {
reportContent = I18nString.getLocaleString("recipient.reports.notAvailable", admin.getLocale());
recipientReport.setMediaType(MediaType.TEXT_PLAIN);
recipientReport.setFilename(FilenameUtils.removeExtension(filename) + RecipientReportUtils.TXT_EXTENSION);
} else {
recipientReport.setFilename(RecipientReportUtils.resolveFileName(filename, reportContent));
MediaType mediaType = MediaType.parseMediaType(mimeTypeService.getMimetypeForFile(filename.toLowerCase()));
recipientReport.setMediaType(mediaType);
if (MediaType.TEXT_HTML == mediaType) {
reportContent = reportContent.replace("\r\n", "\n").replace("\n", "<br />\n");
}
}
recipientReport.setContent(reportContent.getBytes("UTF-8"));
return recipientReport;
}
@Test
public void nestedViewResolverIsNotSpringBean() throws Exception {
StaticWebApplicationContext webAppContext = new StaticWebApplicationContext();
webAppContext.setServletContext(new MockServletContext());
webAppContext.refresh();
InternalResourceViewResolver nestedResolver = new InternalResourceViewResolver();
nestedResolver.setApplicationContext(webAppContext);
nestedResolver.setViewClass(InternalResourceView.class);
viewResolver.setViewResolvers(new ArrayList<>(Arrays.asList(nestedResolver)));
FixedContentNegotiationStrategy fixedStrategy = new FixedContentNegotiationStrategy(MediaType.TEXT_HTML);
viewResolver.setContentNegotiationManager(new ContentNegotiationManager(fixedStrategy));
viewResolver.afterPropertiesSet();
String viewName = "view";
Locale locale = Locale.ENGLISH;
View result = viewResolver.resolveViewName(viewName, locale);
assertNotNull("Invalid view", result);
}
@Test
public void nestedViewResolverIsNotSpringBean() throws Exception {
StaticWebApplicationContext webAppContext = new StaticWebApplicationContext();
webAppContext.setServletContext(new MockServletContext());
webAppContext.refresh();
InternalResourceViewResolver nestedResolver = new InternalResourceViewResolver();
nestedResolver.setApplicationContext(webAppContext);
nestedResolver.setViewClass(InternalResourceView.class);
viewResolver.setViewResolvers(new ArrayList<ViewResolver>(Arrays.asList(nestedResolver)));
FixedContentNegotiationStrategy fixedStrategy = new FixedContentNegotiationStrategy(MediaType.TEXT_HTML);
viewResolver.setContentNegotiationManager(new ContentNegotiationManager(fixedStrategy));
viewResolver.afterPropertiesSet();
String viewName = "view";
Locale locale = Locale.ENGLISH;
View result = viewResolver.resolveViewName(viewName, locale);
assertNotNull("Invalid view", result);
}
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
ContentNegotiationStrategy negotiationStrategy = new HeaderContentNegotiationStrategy();
MediaTypeRequestMatcher matcher =
new MediaTypeRequestMatcher(negotiationStrategy, MediaType.TEXT_HTML);
matcher.setUseEquals(false);
if (matcher.matches(request)) {
DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
redirectStrategy.setContextRelative(false);
redirectStrategy.sendRedirect(request, response, LOGIN_FORM_URL);
} else {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
}
}
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException, ServletException {
ContentNegotiationStrategy negotiationStrategy = new HeaderContentNegotiationStrategy();
MediaTypeRequestMatcher matcher =
new MediaTypeRequestMatcher(negotiationStrategy, MediaType.TEXT_HTML);
matcher.setUseEquals(false);
if (matcher.matches(request)) {
DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
redirectStrategy.setContextRelative(false);
redirectStrategy.sendRedirect(request, response, "/errores/403");
} else {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
}
}
private MediaType getContentType(String contentType) {
if (contentType.equalsIgnoreCase(MediaType.IMAGE_GIF_VALUE)) {
return MediaType.IMAGE_GIF;
} else if (contentType.equalsIgnoreCase(MediaType.IMAGE_PNG_VALUE)) {
return MediaType.IMAGE_PNG;
} else if (contentType.equalsIgnoreCase(MediaType.IMAGE_JPEG_VALUE)) {
return MediaType.IMAGE_JPEG;
} else if (contentType.equalsIgnoreCase(MediaType.TEXT_PLAIN_VALUE)) {
return MediaType.TEXT_PLAIN;
} else if (contentType.equalsIgnoreCase(MediaType.TEXT_XML_VALUE)) {
return MediaType.TEXT_XML;
} else if (contentType.equalsIgnoreCase(MediaType.TEXT_HTML_VALUE)) {
return MediaType.TEXT_HTML;
}
return MediaType.APPLICATION_OCTET_STREAM;
}
public static String resolveFileName(String filename, String reportContent) {
String fileNameWithoutExtension = FilenameUtils.removeExtension(filename);
if (StringUtils.isNotEmpty(fileNameWithoutExtension)) {
//resolve content type and create proper file name if file name doesn't have extension
MediaType contentType = resolveMediaType(reportContent);
return fileNameWithoutExtension + (MediaType.TEXT_HTML == contentType ? HTML_EXTENSION : TXT_EXTENSION);
}
return filename;
}
public static MediaType resolveMediaType(String reportContent) {
if (StringUtils.startsWith(reportContent, HTML_TAG) || StringUtils.startsWith(reportContent, DOCTYPE_HTML_TAG)) {
return MediaType.TEXT_HTML;
} else {
return MediaType.TEXT_PLAIN;
}
}
@Test
public void useHttpOutputMessageMediaType() {
MediaType outputMessageMediaType = MediaType.TEXT_HTML;
this.response.getHeaders().setContentType(outputMessageMediaType);
HttpMessageWriter<String> writer = getWriter(TEXT_PLAIN_UTF_8, TEXT_HTML);
writer.write(Mono.just("body"), forClass(String.class), TEXT_PLAIN, this.response, NO_HINTS);
assertEquals(outputMessageMediaType, this.response.getHeaders().getContentType());
assertEquals(outputMessageMediaType, this.mediaTypeCaptor.getValue());
}
public static void forLogin(
final ServerHttpSecurity http,
final AMType amType,
final ApplicationContext ctx) {
ReactiveClientRegistrationRepository clientRegistrationRepository =
ctx.getBean(ReactiveClientRegistrationRepository.class);
ReactiveOAuth2AuthorizedClientService authorizedClientService =
new InMemoryReactiveOAuth2AuthorizedClientService(clientRegistrationRepository);
ServerOAuth2AuthorizedClientRepository authorizedClientRepository =
new AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository(authorizedClientService);
OAuth2AuthorizationRequestRedirectWebFilter authRequestRedirectFilter =
new OAuth2AuthorizationRequestRedirectWebFilter(clientRegistrationRepository);
AuthenticationWebFilter authenticationFilter =
new OAuth2LoginAuthenticationWebFilter(authenticationManager(amType), authorizedClientRepository);
authenticationFilter.setRequiresAuthenticationMatcher(
new PathPatternParserServerWebExchangeMatcher("/login/oauth2/code/{registrationId}"));
authenticationFilter.setServerAuthenticationConverter(
new ServerOAuth2AuthorizationCodeAuthenticationTokenConverter(clientRegistrationRepository));
authenticationFilter.setAuthenticationSuccessHandler(new RedirectServerAuthenticationSuccessHandler());
authenticationFilter.setAuthenticationFailureHandler((exchange, ex) -> Mono.error(ex));
authenticationFilter.setSecurityContextRepository(new WebSessionServerSecurityContextRepository());
MediaTypeServerWebExchangeMatcher htmlMatcher = new MediaTypeServerWebExchangeMatcher(MediaType.TEXT_HTML);
htmlMatcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL));
ServerAuthenticationEntryPoint entrypoint =
new RedirectServerAuthenticationEntryPoint("/oauth2/authorization/" + amType.name());
http.exceptionHandling().authenticationEntryPoint(new DelegateEntry(htmlMatcher, entrypoint).getEntryPoint());
http.addFilterAt(authRequestRedirectFilter, SecurityWebFiltersOrder.HTTP_BASIC);
http.addFilterAt(authenticationFilter, SecurityWebFiltersOrder.AUTHENTICATION);
}
@Test
public void testContentNegotiation() throws Exception {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(Person.class);
List<View> viewList = new ArrayList<View>();
viewList.add(new MappingJackson2JsonView());
viewList.add(new MarshallingView(marshaller));
ContentNegotiationManager manager = new ContentNegotiationManager(
new HeaderContentNegotiationStrategy(), new FixedContentNegotiationStrategy(MediaType.TEXT_HTML));
ContentNegotiatingViewResolver cnViewResolver = new ContentNegotiatingViewResolver();
cnViewResolver.setDefaultViews(viewList);
cnViewResolver.setContentNegotiationManager(manager);
cnViewResolver.afterPropertiesSet();
MockMvc mockMvc =
standaloneSetup(new PersonController())
.setViewResolvers(cnViewResolver, new InternalResourceViewResolver())
.build();
mockMvc.perform(get("/person/Corea"))
.andExpect(status().isOk())
.andExpect(model().size(1))
.andExpect(model().attributeExists("person"))
.andExpect(forwardedUrl("person/show"));
mockMvc.perform(get("/person/Corea").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.person.name").value("Corea"));
mockMvc.perform(get("/person/Corea").accept(MediaType.APPLICATION_XML))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_XML))
.andExpect(xpath("/person/name/text()").string(equalTo("Corea")));
}
public TextWebSocketFrame toWebSocketResponse(String acceptHeader) throws Exception {
MediaType negotiatedType = MediaType.TEXT_HTML;
if (null != acceptHeader) {
List<MediaType> requestedTypes = MediaType.parseMediaTypes(acceptHeader);
MediaType.sortBySpecificityAndQuality(requestedTypes);
LOG.trace("Acceptable response types: {}", MediaType.toString(requestedTypes));
for (MediaType t : requestedTypes) {
if (t.includes(MediaType.TEXT_HTML)) {
negotiatedType = MediaType.TEXT_HTML;
LOG.trace("{} allows HTML", t.toString());
break;
}
if (t.includes(MediaType.APPLICATION_JSON)) {
negotiatedType = MediaType.APPLICATION_JSON;
LOG.trace("{} allows JSON", t.toString());
break;
}
}
}
String result = null;
if (negotiatedType.equals(MediaType.APPLICATION_JSON)) {
result = this.generateJson(JsonUtil.getObjectMapper());
} else {
result = this.generateHtml().toString();
}
return new TextWebSocketFrame(result);
}
public FullHttpResponse toHttpResponse(String acceptHeader) throws Exception {
MediaType negotiatedType = MediaType.TEXT_HTML;
if (null != acceptHeader) {
List<MediaType> requestedTypes = MediaType.parseMediaTypes(acceptHeader);
MediaType.sortBySpecificityAndQuality(requestedTypes);
LOG.trace("Acceptable response types: {}", MediaType.toString(requestedTypes));
for (MediaType t : requestedTypes) {
if (t.includes(MediaType.TEXT_HTML)) {
negotiatedType = MediaType.TEXT_HTML;
LOG.trace("{} allows HTML", t.toString());
break;
}
if (t.includes(MediaType.APPLICATION_JSON)) {
negotiatedType = MediaType.APPLICATION_JSON;
LOG.trace("{} allows JSON", t.toString());
break;
}
}
}
byte[] buf = null;
Object responseType = Constants.HTML_TYPE;
if (negotiatedType.equals(MediaType.APPLICATION_JSON)) {
buf = this.generateJson(JsonUtil.getObjectMapper()).getBytes(StandardCharsets.UTF_8);
responseType = Constants.JSON_TYPE;
} else {
buf = this.generateHtml().toString().getBytes(StandardCharsets.UTF_8);
}
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
Unpooled.copiedBuffer(buf));
response.headers().set(HttpHeaderNames.CONTENT_TYPE, responseType);
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
return response;
}
@Test
public void testContentNegotiation() throws Exception {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(Person.class);
List<View> viewList = new ArrayList<>();
viewList.add(new MappingJackson2JsonView());
viewList.add(new MarshallingView(marshaller));
ContentNegotiationManager manager = new ContentNegotiationManager(
new HeaderContentNegotiationStrategy(), new FixedContentNegotiationStrategy(MediaType.TEXT_HTML));
ContentNegotiatingViewResolver cnViewResolver = new ContentNegotiatingViewResolver();
cnViewResolver.setDefaultViews(viewList);
cnViewResolver.setContentNegotiationManager(manager);
cnViewResolver.afterPropertiesSet();
MockMvc mockMvc =
standaloneSetup(new PersonController())
.setViewResolvers(cnViewResolver, new InternalResourceViewResolver())
.build();
mockMvc.perform(get("/person/Corea"))
.andExpect(status().isOk())
.andExpect(model().size(1))
.andExpect(model().attributeExists("person"))
.andExpect(forwardedUrl("person/show"));
mockMvc.perform(get("/person/Corea").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.person.name").value("Corea"));
mockMvc.perform(get("/person/Corea").accept(MediaType.APPLICATION_XML))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_XML))
.andExpect(xpath("/person/name/text()").string(equalTo("Corea")));
}
@Override
protected void configure(HttpSecurity http) throws Exception {
final RequestMatcher textHtmlMatcher = new MediaTypeRequestMatcher(
contentNegotiationStrategy,
MediaType.TEXT_HTML);
final String loginPage = dashboard("/#/login");
final BasicAuthenticationEntryPoint basicAuthenticationEntryPoint = new BasicAuthenticationEntryPoint();
basicAuthenticationEntryPoint.setRealmName(securityProperties.getBasic().getRealm());
basicAuthenticationEntryPoint.afterPropertiesSet();
http
.csrf()
.disable()
.authorizeRequests()
.antMatchers("/")
.authenticated()
.antMatchers(
dashboard("/**"),
"/authenticate",
"/security/info",
"/features",
"/assets/**").permitAll()
.and()
.formLogin().loginPage(loginPage)
.loginProcessingUrl(dashboard("/login"))
.defaultSuccessUrl(dashboard("/")).permitAll()
.and()
.logout().logoutUrl(dashboard("/logout"))
.logoutSuccessUrl(dashboard("/logout-success.html"))
.logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler()).permitAll()
.and().httpBasic()
.and().exceptionHandling()
.defaultAuthenticationEntryPointFor(
new LoginUrlAuthenticationEntryPoint(loginPage),
textHtmlMatcher)
.defaultAuthenticationEntryPointFor(basicAuthenticationEntryPoint,
AnyRequestMatcher.INSTANCE)
.and()
.authorizeRequests()
.anyRequest().authenticated();
final SessionRepositoryFilter<ExpiringSession> sessionRepositoryFilter = new SessionRepositoryFilter<ExpiringSession>(
sessionRepository());
sessionRepositoryFilter
.setHttpSessionStrategy(new HeaderHttpSessionStrategy());
http.addFilterBefore(sessionRepositoryFilter,
ChannelProcessingFilter.class).csrf().disable();
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);
}
/**
* ContentTypeがtext/htmlのヘッダとリクエストデータを設定します。
* @param entity リクエストデータ
* @param <T> リクエストデータの型
* @return このユーティリティを返します。
*/
public static <T> Entity<T> html(final T entity) {
return new Entity<T>(entity, MediaType.TEXT_HTML);
}