下面列出了怎么用javax.servlet.http.HttpServletRequest的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testAddHttpRequestToContext() throws Exception {
HttpServletRequest request = getMock("/solr/select", null, -1);
when(request.getMethod()).thenReturn("GET");
when(request.getQueryString()).thenReturn("q=title:solr");
Map<String, String> headers = new HashMap<>();
headers.put("X-Forwarded-For", "10.0.0.1");
when(request.getHeaderNames()).thenReturn(new Vector<>(headers.keySet()).elements());
for(Map.Entry<String,String> entry:headers.entrySet()) {
Vector<String> v = new Vector<>();
v.add(entry.getValue());
when(request.getHeaders(entry.getKey())).thenReturn(v.elements());
}
SolrRequestParsers parsers = new SolrRequestParsers(h.getCore().getSolrConfig());
assertFalse(parsers.isAddRequestHeadersToContext());
SolrQueryRequest solrReq = parsers.parse(h.getCore(), "/select", request);
assertFalse(solrReq.getContext().containsKey("httpRequest"));
parsers.setAddRequestHeadersToContext(true);
solrReq = parsers.parse(h.getCore(), "/select", request);
assertEquals(request, solrReq.getContext().get("httpRequest"));
assertEquals("10.0.0.1", ((HttpServletRequest)solrReq.getContext().get("httpRequest")).getHeaders("X-Forwarded-For").nextElement());
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String reqUri = req.getRequestURI();
if (reqUri.endsWith("/login")) {
serviceAccountLogin(req);
} else if (reqUri.endsWith("/logout")){
logout(req);
}
// Don't load products if some error happened during login,refresh or logout
if (req.getAttribute(ERROR) == null) {
loadProducts(req);
}
req.getRequestDispatcher("/WEB-INF/page.jsp").forward(req, resp);
}
@Test
@PrepareForTest( { Encode.class } )
public void testStartExecutionTransServletEscapesHtmlWhenTransNotFound() throws ServletException, IOException {
HttpServletRequest mockHttpServletRequest = mock( HttpServletRequest.class );
HttpServletResponse mockHttpServletResponse = mock( HttpServletResponse.class );
StringWriter out = new StringWriter();
PrintWriter printWriter = new PrintWriter( out );
PowerMockito.spy( Encode.class );
when( mockHttpServletRequest.getContextPath() ).thenReturn( StartExecutionTransServlet.CONTEXT_PATH );
when( mockHttpServletRequest.getParameter( anyString() ) ).thenReturn( ServletTestUtils.BAD_STRING_TO_TEST );
when( mockHttpServletResponse.getWriter() ).thenReturn( printWriter );
startExecutionTransServlet.doGet( mockHttpServletRequest, mockHttpServletResponse );
assertFalse( ServletTestUtils.hasBadText( ServletTestUtils.getInsideOfTag( "H1", out.toString() ) ) );
PowerMockito.verifyStatic( atLeastOnce() );
Encode.forHtml( anyString() );
}
/**
* Validate that a parameter constraint it respected or violated. Return a message if violated.
* @param request HttpServlet request holding parameters to validate
* @param constraint Constraint to apply to one request parameter.
* @return A string representing constraint violation if any. null otherwise.
*/
public static String validateConstraint(HttpServletRequest request, ParameterConstraint constraint) {
String value = null;
if (ParameterLocation.header == constraint.getIn()) {
value = request.getHeader(constraint.getName());
} else if (ParameterLocation.query == constraint.getIn()) {
value = request.getParameter(constraint.getName());
}
if (value != null) {
if (constraint.getMustMatchRegexp() != null) {
if (!Pattern.matches(constraint.getMustMatchRegexp(), value)) {
return "Parameter " + constraint.getName() + " should match " + constraint.getMustMatchRegexp();
}
}
} else {
if (constraint.isRequired()) {
return "Parameter " + constraint.getName() + " is required";
}
}
return null;
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String webName = null;
if (request.getUserPrincipal() != null) {
webName = request.getUserPrincipal().getName();
}
response.getWriter().write(
"<html><body> This is a servlet <br><br>\n" +
"web username: " + webName + "<br><br>\n" +
"web user has role \"foo\": " + request.isUserInRole("foo") + "<br>\n" +
"web user has role \"bar\": " + request.isUserInRole("bar") + "<br>\n" +
"web user has role \"kaz\": " + request.isUserInRole("kaz") + "<br><br>\n" +
"<form method=\"POST\">" +
"<input type=\"hidden\" name=\"logout\" value=\"true\" >" +
"<input type=\"submit\" value=\"Logout\">" +
"</form>" +
"</body></html>");
}
/**
* 删除黑名单
*
* @return
*/
@RequestMapping(params = "doDel")
@ResponseBody
public AjaxJson doDel(TsBlackListEntity tsBlackList, HttpServletRequest request) {
String message = null;
AjaxJson j = new AjaxJson();
tsBlackList = systemService.getEntity(TsBlackListEntity.class, tsBlackList.getId());
message = "黑名单删除成功";
try{
tsBlackListService.delete(tsBlackList);
systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
}catch(Exception e){
e.printStackTrace();
message = "黑名单删除失败";
throw new BusinessException(e.getMessage());
}
j.setMsg(message);
return j;
}
private static String doSomething(HttpServletRequest request, String param) throws ServletException, IOException {
String bar;
String guess = "ABC";
char switchTarget = guess.charAt(1); // condition 'B', which is safe
// Simple case statement that assigns param to bar on conditions 'A', 'C', or 'D'
switch (switchTarget) {
case 'A':
bar = param;
break;
case 'B':
bar = "bob";
break;
case 'C':
case 'D':
bar = param;
break;
default:
bar = "bob's your uncle";
break;
}
return bar;
}
private String GenDependTree(HttpServletRequest Req)
{
StringBuilder DepTree=new StringBuilder(5000);
DepTree.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n").append("<tree id=\"0\">");
DriverGeneric PDSession=getSessOPD(Req);
String IdVersProdSec=Req.getParameter("IdVers");
try {
PDFolders F=new PDFolders(PDSession);
F.LoadFull(IdVersProdSec);
DepTree.append("<item id=\"").append(F.getPDId()).append("\" text=\"").append(F.getTitle()).append("\" open=\"1\">");
TreeSet<String> ListDep = F.getRecSum().getAttr(DEPENDENCIES).getValuesList();
for (Iterator<String> iterator = ListDep.iterator(); iterator.hasNext();)
{
String Rel = iterator.next();
DepTree.append(SubDependTree(PDSession, Rel));
}
DepTree.append("</item>");
} catch (Exception Ex)
{
Ex.printStackTrace();
}
DepTree.append("</tree>");
return(DepTree.toString());
}
private static String doSomething(HttpServletRequest request, String param) throws ServletException, IOException {
String bar = "alsosafe";
if (param != null) {
java.util.List<String> valuesList = new java.util.ArrayList<String>( );
valuesList.add("safe");
valuesList.add( param );
valuesList.add( "moresafe" );
valuesList.remove(0); // remove the 1st safe value
bar = valuesList.get(1); // get the last 'safe' value
}
return bar;
}
@GetMapping
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
int id = ServletRequestUtils.getRequiredIntParameter(request, "id");
MediaFile dir = mediaFileService.getMediaFile(id);
List<MediaFile> files = mediaFileService.getChildrenOf(dir, true, false, true, false);
Map<String, Object> map = new HashMap<String, Object>();
if (!files.isEmpty()) {
map.put("defaultArtist", files.get(0).getArtist());
map.put("defaultAlbum", files.get(0).getAlbumName());
map.put("defaultYear", files.get(0).getYear());
map.put("defaultGenre", files.get(0).getGenre());
}
map.put("allGenres", JaudiotaggerParser.getID3V1Genres());
List<Song> songs = new ArrayList<Song>();
for (int i = 0; i < files.size(); i++) {
songs.add(createSong(files.get(i), i));
}
map.put("id", id);
map.put("songs", songs);
return new ModelAndView("editTags","model",map);
}
@RequestMapping(method = RequestMethod.POST)
protected String onSubmit(final HttpServletRequest request,
final TrackCommand command,
final Map<String, Object> model,
final BindingResult bindingResult) {
new TrackCommandValidator().validate(command, bindingResult);
final TrackingId trackingId = new TrackingId(command.getTrackingId());
final Cargo cargo = cargoRepository.find(trackingId);
if (cargo != null) {
final Locale locale = RequestContextUtils.getLocale(request);
final List<HandlingEvent> handlingEvents = handlingEventRepository.lookupHandlingHistoryOfCargo(trackingId).distinctEventsByCompletionTime();
model.put("cargo", new CargoTrackingViewAdapter(cargo, messageSource, locale, handlingEvents));
} else {
bindingResult.rejectValue("trackingId", "cargo.unknown_id", new Object[]{command.getTrackingId()}, "Unknown tracking id");
}
return "track";
}
/**
* 检查CSRF Token
*
* @param req ServletRequest
*/
private boolean checkCsrfToken(ServletRequest req) {
AdamProperties adamProperties = CHERRY.SPRING_CONTEXT.getBean(AdamProperties.class);
boolean isValid = false;
String csrf = ((HttpServletRequest) req).getHeader(adamProperties.getCsrf().getHeaderName());
if (StringUtils.isBlank(csrf)) {
csrf = req.getParameter(adamProperties.getCsrf().getRequestName());
}
if (StringUtils.isNotBlank(csrf)) {
Boolean hasKey = CHERRY.SPRING_CONTEXT.getBean(StringRedisTemplate.class).hasKey(CHERRY.REDIS_KEY_CSRF + csrf);
isValid = hasKey == null ? false : hasKey;
}
return isValid;
}
/**
* Add request to the purgatory and return the {@link ReviewResult} for the request that has been added to
* the purgatory.
*
* @param request Http Servlet Request to add to the purgatory.
* @param parameters Request parameters.
* @param <P> Type corresponding to the request parameters.
* @return The result showing the {@link ReviewResult} for the request that has been added to the purgatory.
*/
private synchronized <P extends CruiseControlParameters> ReviewResult addRequest(HttpServletRequest request,
P parameters) {
if (!request.getMethod().equals(POST_METHOD)) {
throw new IllegalArgumentException(String.format("Purgatory can only contain POST request (Attempted to add: %s).",
httpServletRequestToString(request)));
}
RequestInfo requestInfo = new RequestInfo(request, parameters);
_requestInfoById.put(_requestId, requestInfo);
Map<Integer, RequestInfo> requestInfoById = new HashMap<>();
requestInfoById.put(_requestId, requestInfo);
Set<Integer> filteredRequestIds = new HashSet<>();
filteredRequestIds.add(_requestId);
ReviewResult result = new ReviewResult(requestInfoById, filteredRequestIds, _config);
_requestId++;
return result;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
AdminService adminService = (AdminService) factory.getBean("adminService");
System.out.println(request.getContextPath());
Subject currentUser = SecurityUtils.getSubject();
//判断用户是通过记住我功能自动登录,此时session失效
if(!currentUser.isAuthenticated() && currentUser.isRemembered()){
try {
Admin admin = adminService.findByUsername(currentUser.getPrincipals().toString());
//对密码进行加密后验证
UsernamePasswordToken token = new UsernamePasswordToken(admin.getUsername(), admin.getPassword(),currentUser.isRemembered());
//把当前用户放入session
currentUser.login(token);
Session session = currentUser.getSession();
session.setAttribute(SysConstant.SESSION_ADMIN,admin);
//设置会话的过期时间--ms,默认是30分钟,设置负数表示永不过期
session.setTimeout(30*60*1000L);
}catch (Exception e){
//自动登录失败,跳转到登录页面
//response.sendRedirect(request.getContextPath()+"/system/employee/sign/in");
ajaxReturn(response, 4000, "unauthorized");
return false;
}
if(!currentUser.isAuthenticated()){
//自动登录失败,跳转到登录页面
ajaxReturn(response, 4000, "unauthorized");
return false;
}
}
return true;
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (!initialized.get()) {
init(request.getServletContext());
initialized.set(true);
}
String result = validateFormService.validate(request);
CrosUtil.setCrosHeader(response);
response.setContentType("application/json;charset=utf-8");
response.setStatus(200);
response.getWriter().write(result);
response.getWriter().close();
return;
}
/**
* 跳转到添加页面
* @return
*/
@RequestMapping(value = "/toAdd",method ={RequestMethod.GET, RequestMethod.POST})
public void toAddDialog(HttpServletRequest request,HttpServletResponse response,ModelMap model)throws Exception{
VelocityContext velocityContext = new VelocityContext();
String viewName = "cms/back/cmsSite-add.vm";
//update-begin-author:taoYan date:20181018 for:cms默认appid设置---
String jwid = (String) request.getSession().getAttribute("jwid");
String defaultJwid = CmsProperties.defaultJwid;
if(defaultJwid.equals(jwid)){
velocityContext.put("isDefaultJwid",1);
}
//update-end-author:taoYan date:20181018 for:cms默认appid设置---
velocityContext.put("templateStyle", CmsSiteTemplateEnum.getAllEnumData());
ViewVelocity.view(request,response,viewName,velocityContext);
}
@SuppressWarnings("unchecked")
protected ActionResult<Wo> execute( HttpServletRequest request, EffectivePerson effectivePerson, String id ) throws Exception {
ActionResult<Wo> result = new ActionResult<>();
Boolean check = true;
if( check ){
if( id == null || id.isEmpty() ){
check = false;
Exception exception = new ExceptionForumInfoIdEmpty();
result.error( exception );
}
}
if( check ){
String cacheKey = "forum#" + id;
Element element = cache.get( cacheKey );
if ((null != element) && (null != element.getObjectValue())) {
ActionResult<Wo> result_cache = (ActionResult<Wo>) element.getObjectValue();
result.setData( result_cache.getData() );
result.setCount( 1L);
} else {
//继续进行数据查询
result = getForumQueryResult( id, request, effectivePerson );
cache.put(new Element(cacheKey, result ));
}
}
return result;
}
@Override
public Object run() {
final RequestContext ctx = RequestContext.getCurrentContext();
logger.info("in zuul filter " + ctx.getRequest().getRequestURI());
byte[] encoded;
try {
encoded = Base64.getEncoder().encode("fooClientIdPassword:secret".getBytes("UTF-8"));
ctx.addZuulRequestHeader("Authorization", "Basic " + new String(encoded));
logger.info("pre filter");
logger.info(ctx.getRequest().getHeader("Authorization"));
final HttpServletRequest req = ctx.getRequest();
final String refreshToken = extractRefreshToken(req);
if (refreshToken != null) {
final Map<String, String[]> param = new HashMap<String, String[]>();
param.put("refresh_token", new String[] { refreshToken });
param.put("grant_type", new String[] { "refresh_token" });
ctx.setRequest(new CustomHttpServletRequest(req, param));
}
} catch (final UnsupportedEncodingException e) {
logger.error("Error occured in pre filter", e);
}
//
return null;
}
public String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException
{
final String agent = request.getHeader("USER-AGENT");
String filename = fileName;
if (agent.contains("MSIE"))
{
// IE浏览器
filename = URLEncoder.encode(filename, "utf-8");
filename = filename.replace("+", " ");
}
else if (agent.contains("Firefox"))
{
// 火狐浏览器
filename = new String(fileName.getBytes(), "ISO8859-1");
}
else if (agent.contains("Chrome"))
{
// google浏览器
filename = URLEncoder.encode(filename, "utf-8");
}
else
{
// 其它浏览器
filename = URLEncoder.encode(filename, "utf-8");
}
return filename;
}
@Override
public ActionForward execute(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
HttpServletResponse response) throws Exception {
request.setAttribute("application.name", getStringFromDefaultBundle(getCandidacyNameKey()));
request.setAttribute("mappingPath", mapping.getPath());
request.setAttribute("isApplicationSubmissionPeriodValid", isApplicationSubmissionPeriodValid());
request.setAttribute("application.information.link.default", getCandidacyInformationLinkDefaultLanguage());
request.setAttribute("application.information.link.english", getCandidacyInformationLinkEnglish());
setProcess(request);
return super.execute(mapping, actionForm, request, response);
}
private String getURLBase(HttpServletRequest request) {
String scheme = request.getScheme();
String serverName = request.getServerName();
int serverPort = request.getServerPort();
StringBuffer url = new StringBuffer();
url.append(scheme).append("://").append(serverName);
if ((serverPort != 80) && (serverPort != 443)) {
url.append(":").append(serverPort);
}
url.append("/gerbil/");
return url.toString();
}
private static String doSomething(HttpServletRequest request, String param) throws ServletException, IOException {
String bar;
// Simple if statement that assigns param to bar on true condition
int num = 196;
if ( (500/42) + num > 200 )
bar = param;
else bar = "This should never happen";
return bar;
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String servletPath = request.getServletPath();
String view = processRequest(servletPath, request);
RequestDispatcher dispatcher = request.getRequestDispatcher(view);
dispatcher.forward(request, response);
}
/**
* @param cookieAuthValue クッキー内の dc_cookieキーに指定された値
* @param cookiePeer dc_cookie_peerクエリに指定された値
* @param authzHeaderValue Authorization ヘッダ
* @param host Host ヘッダ
* @param uriInfo UriInfo
* @param xDcUnitUser X-Dc-UnitUserヘッダ
* @param httpServletRequest HttpServletRequest
* @return CellResourceオブジェクトまたはResponseオブジェクト
*/
@Path("{path1}")
public final Object facade(
@CookieParam(DC_COOKIE_KEY) final String cookieAuthValue,
@QueryParam(COOKIE_PEER_QUERY_KEY) final String cookiePeer,
@HeaderParam(HttpHeaders.AUTHORIZATION) final String authzHeaderValue,
@HeaderParam(HttpHeaders.HOST) final String host,
@HeaderParam(DcCoreUtils.HttpHeaders.X_DC_UNIT_USER) final String xDcUnitUser,
@Context final UriInfo uriInfo,
@Context HttpServletRequest httpServletRequest) {
Cell cell = ModelFactory.cell(uriInfo);
AccessContext ac = AccessContext.create(authzHeaderValue,
uriInfo, cookiePeer, cookieAuthValue, cell, uriInfo.getBaseUri().toString(),
host, xDcUnitUser);
if (cell == null) {
throw DcCoreException.Dav.CELL_NOT_FOUND;
}
long cellStatus = CellLockManager.getCellStatus(cell.getId());
if (cellStatus == CellLockManager.CELL_STATUS_BULK_DELETION) {
throw DcCoreException.Dav.CELL_NOT_FOUND;
}
CellLockManager.incrementReferenceCount(cell.getId());
httpServletRequest.setAttribute("cellId", cell.getId());
return new CellResource(ac);
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, javax.servlet.FilterChain chain)
throws IOException, ServletException {
Authentication authentication = TokenAuthentication
.getAuthentication((HttpServletRequest)request);
SecurityContextHolder.getContext()
.setAuthentication(authentication);
chain.doFilter(request,response);
}
/**
* GET /authenticate : check if the user is authenticated, and return its login.
*
* @param request the HTTP request
* @return the login if the user is authenticated
*/
@RequestMapping(value = "/authenticate",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public String isAuthenticated(HttpServletRequest request) {
log.debug("REST request to check if the current user is authenticated");
return request.getRemoteUser();
}
@Override
public boolean canHandle(HttpServletRequest request) {
String userName = request.getParameter(BasicAuthenticatorConstants.USER_NAME);
String password = request.getParameter(BasicAuthenticatorConstants.PASSWORD);
if (userName != null && password != null) {
return true;
}
return false;
}
/**
* @see org.apache.struts.action.ActionForm#reset(org.apache.struts.action.ActionMapping, javax.servlet.http.HttpServletRequest)
*/
@Override
public void reset(ActionMapping mapping, HttpServletRequest request) {
super.reset(mapping, request);
if (extraButtons != null) {
extraButtons.clear();
}
//fieldNameToFocusOnAfterSubmit = "";
clearDisplayedMessages();
}
/**
* Creates and persists an authentication
*
* @response.representation.qname {http://www.example.com}authenticationVO
* @response.representation.mediaType application/xml, application/json
* @response.representation.doc An authentication to save
* @response.representation.example {@link org.olat.connectors.rest.support.vo.Examples#SAMPLE_AUTHVO}
* @response.representation.200.qname {http://www.example.com}authenticationVO
* @response.representation.200.mediaType application/xml, application/json
* @response.representation.200.doc The saved authentication
* @response.representation.200.example {@link org.olat.connectors.rest.support.vo.Examples#SAMPLE_AUTHVO}
* @response.representation.401.doc The roles of the authenticated user are not sufficient
* @response.representation.404.doc The identity not found
* @param username
* The username of the user
* @param authenticationVO
* The authentication object to persist
* @param request
* The HTTP request
* @return the saved authentication
*/
@PUT
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response create(@PathParam("username") final String username, final AuthenticationVO authenticationVO, @Context final HttpServletRequest request) {
if (!RestSecurityHelper.isUserManager(request)) {
return Response.serverError().status(Status.UNAUTHORIZED).build();
}
final BaseSecurity baseSecurity = getBaseSecurity();
final Identity identity = baseSecurity.loadIdentityByKey(authenticationVO.getIdentityKey(), false);
if (identity == null) {
return Response.serverError().status(Status.NOT_FOUND).build();
}
if (!identity.getName().equals(username)) {
return Response.serverError().status(Status.NOT_FOUND).build();
}
final String provider = authenticationVO.getProvider();
final String authUsername = authenticationVO.getAuthUsername();
final String credentials = authenticationVO.getCredential();
final Authentication authentication = baseSecurity.createAndPersistAuthentication(identity, provider, authUsername, credentials);
if (authentication == null) {
return Response.serverError().status(Status.NOT_ACCEPTABLE).build();
}
log.info("Audit:New authentication created for " + authUsername + " with provider " + provider);
final AuthenticationVO savedAuth = ObjectFactory.get(authentication, true);
return Response.ok(savedAuth).build();
}
public void doGet(
HttpServletRequest request, HttpServletResponse response
) throws ServletException, IOException {
logger.info("Blocking forward endpoint hit");
sleepThread(SLEEP_TIME_MILLIS);
request.getServletContext().getRequestDispatcher(BLOCKING_PATH).forward(request, response);
}