下面列出了怎么用javax.servlet.ServletException的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
servletContext.addListener(new RequestContextListener());
// verifying configs for features activation
Set<String> profiles = new HashSet<String>();
if (isEmailFeaturesEnabled()) {
profiles.add("email");
}
if (isCdnFeaturesEnabled()) {
profiles.add("cdn");
}
if (isSslFeaturesEnabled()) {
profiles.add("ssl");
}
servletContext.setInitParameter("spring.profiles.active", StringUtils.arrayToCommaDelimitedString(profiles.toArray()));
}
@Override
protected void doDelete(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
CodeTimer timer = new CodeTimer("RestServlet.doDelete()", true);
Map<String,String> metaInfo = buildMetaInfo(request);
try {
String responseString = handleRequest(request, response, metaInfo);
response.getOutputStream().print(responseString);
}
catch (ServiceException ex) {
logger.error(ex.getMessage(), ex);
response.setStatus(ex.getCode());
response.getWriter().println(createErrorResponseMessage(request, metaInfo, ex));
}
finally {
timer.stopAndLogTiming("");
}
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if (req.isAsyncStarted()) {
req.getAsyncContext().complete();
} else if (req.isAsyncSupported()) {
AsyncContext actx = req.startAsync();
actx.addListener(this);
resp.setContentType("text/plain");
clients.add(actx);
if (clientcount.incrementAndGet()==1) {
ticker.addTickListener(this);
}
} else {
new Exception("Async Not Supported").printStackTrace();
resp.sendError(400,"Async is not supported.");
}
}
public String doSomething(HttpServletRequest request, String param) throws ServletException, IOException {
// Chain a bunch of propagators in sequence
String a34194 = param; //assign
StringBuilder b34194 = new StringBuilder(a34194); // stick in stringbuilder
b34194.append(" SafeStuff"); // append some safe content
b34194.replace(b34194.length()-"Chars".length(),b34194.length(),"Chars"); //replace some of the end content
java.util.HashMap<String,Object> map34194 = new java.util.HashMap<String,Object>();
map34194.put("key34194", b34194.toString()); // put in a collection
String c34194 = (String)map34194.get("key34194"); // get it back out
String d34194 = c34194.substring(0,c34194.length()-1); // extract most of it
String e34194 = new String( org.apache.commons.codec.binary.Base64.decodeBase64(
org.apache.commons.codec.binary.Base64.encodeBase64( d34194.getBytes() ) )); // B64 encode and decode it
String f34194 = e34194.split(" ")[0]; // split it on a space
org.owasp.benchmark.helpers.ThingInterface thing = org.owasp.benchmark.helpers.ThingFactory.createThing();
String bar = thing.doSomething(f34194); // reflection
return bar;
}
/**
* Tests if a non-simple request is given to simple request handler.
*
* @throws IOException
* @throws ServletException
*/
@Test(expected = IllegalArgumentException.class)
public void testNotSimple() throws IOException, ServletException {
TesterHttpServletRequest request = new TesterHttpServletRequest();
request.setHeader(CorsFilter.REQUEST_HEADER_ORIGIN,
TesterFilterConfigs.HTTPS_WWW_APACHE_ORG);
request.setHeader(
CorsFilter.REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD, "PUT");
request.setHeader(
CorsFilter.REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS,
"Content-Type");
request.setMethod("OPTIONS");
TesterHttpServletResponse response = new TesterHttpServletResponse();
CorsFilter corsFilter = new CorsFilter();
corsFilter.init(TesterFilterConfigs
.getDefaultFilterConfig());
corsFilter.handleSimpleCORS(request, response, filterChain);
}
@Test
@PrepareForTest( { Encode.class } )
public void testStartJobServletEscapesHtmlWhenTransNotFound() 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( StartJobServlet.CONTEXT_PATH );
when( mockHttpServletRequest.getParameter( anyString() ) ).thenReturn( ServletTestUtils.BAD_STRING_TO_TEST );
when( mockHttpServletResponse.getWriter() ).thenReturn( printWriter );
startJobServlet.doGet( mockHttpServletRequest, mockHttpServletResponse );
assertFalse( ServletTestUtils.hasBadText( ServletTestUtils.getInsideOfTag( "H1", out.toString() ) ) );
PowerMockito.verifyStatic( atLeastOnce() );
Encode.forHtml( anyString() );
}
@Override
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
ITestCaseService testService = appContext.getBean(ITestCaseService.class);
PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
String test = policy.sanitize(httpServletRequest.getParameter("test"));
JSONArray array = new JSONArray();
JSONObject jsonObject = new JSONObject();
for (TestCase testcase : testService.findTestCaseByTest(test)) {
array.put(testcase.getTestCase());
}
try {
jsonObject.put("testcasesList", array);
httpServletResponse.setContentType("application/json");
httpServletResponse.getWriter().print(jsonObject.toString());
} catch (JSONException exception) {
LOG.warn(exception.toString());
}
}
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try {
PrintWriter out = response.getWriter();
/* TODO output your page here. You may use following sample code. */
HttpSession session=request.getSession();
session.invalidate();
response.sendRedirect("index.jsp");
}
catch(Exception e)
{
}
}
/**
* Removes lineitem. Throws exception if lineitem is not found.
*
* @param _content_id
* @param _course_id
* @throws PersistenceException
* @throws ServletException
*/
public static void removeLineitem(String _content_id, String _course_id)
throws PersistenceException, ServletException {
BbPersistenceManager bbPm = PersistenceServiceFactory.getInstance().getDbPersistenceManager();
Container bbContainer = bbPm.getContainer();
ContentDbLoader courseDocumentLoader = ContentDbLoader.Default.getInstance();
LineitemDbPersister linePersister = LineitemDbPersister.Default.getInstance();
Id contentId = new PkId(bbContainer, CourseDocument.DATA_TYPE, _content_id);
Content bbContent = courseDocumentLoader.loadById(contentId);
//check isGradecenter option is ON and thus there should exist associated lineitem object
if (!bbContent.getIsDescribed()) {
return;
}
Id lineitemId = getLineitem(_content_id, _course_id, true);
linePersister.deleteById(lineitemId);
//Remove bbContentId -> lineitemid pair from the storage
PortalExtraInfo pei = PortalUtil.loadPortalExtraInfo(null, null, LAMS_LINEITEM_STORAGE);
ExtraInfo ei = pei.getExtraInfo();
ei.clearEntry(_content_id);
PortalUtil.savePortalExtraInfo(pei);
}
protected void doInternalDispatch() throws ServletException, IOException {
if (log.isDebugEnabled()) {
logDebug("intDispatch");
}
try {
Runnable runnable = dispatch;
dispatch = null;
runnable.run();
if (!request.isAsync()) {
fireOnComplete();
}
} catch (RuntimeException x) {
// doInternalComplete(true);
if (x.getCause() instanceof ServletException) {
throw (ServletException)x.getCause();
}
if (x.getCause() instanceof IOException) {
throw (IOException)x.getCause();
}
throw new ServletException(x);
}
}
@Override protected void doSuccessResponse(final SipServletResponse response) throws ServletException, IOException {
final String method = response.getRequest().getMethod();
if("REGISTER".equalsIgnoreCase(method)) {
final int status = response.getStatus();
if(status == SipServletResponse.SC_OK) {
final SipApplicationSession application = response.getApplicationSession();
final Gateway gateway = (Gateway)application.getAttribute(Gateway.class.getName());
final Address contact = response.getAddressHeader("Contact");
long expires = contact.getExpires() * 1000;
clock.createTimer(application, expires, false, "REGISTER");
// Issue http://code.google.com/p/vnxivr/issues/detail?id=66
expires += TimeUtils.SECOND_IN_MILLIS * 30;
application.setExpires(TimeUtils.millisToMinutes(expires));
if(logger.isDebugEnabled()) {
final StringBuilder buffer = new StringBuilder();
buffer.append("Successfully registered\n");
buffer.append(gateway.toString()).append("\n");
buffer.append("for a duration of ").append(expires).append(" seconds.");
logger.debug(buffer.toString());
}
}
}
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.setServletContext(servletContext);
rootContext.register(ThymeleafConfig.class);
servletContext.addListener(new SakaiContextLoaderListener(rootContext));
servletContext.addFilter("sakai.request", RequestFilter.class)
.addMappingForUrlPatterns(
EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE),
true,
"/*");
Dynamic servlet = servletContext.addServlet("sakai.onedrive", new DispatcherServlet(rootContext));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
@Override
public void doFilter(final ServletRequest req,
final ServletResponse res,
final FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods",
"POST, GET, OPTIONS, DELETE,PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers",
"X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept");
chain.doFilter(req, res);
}
/**
* Render the internal resource given the specified model.
* This includes setting the model as request attributes.
* 在给定指定模型的情况下呈现内部资源。这包括将模型设置为请求属性
*/
@Override
protected void renderMergedOutputModel(
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
// Expose the model object as request attributes.
exposeModelAsRequestAttributes(model, request);
// Expose helpers as request attributes, if any.
exposeHelpers(request);
// Determine the path for the request dispatcher.
String dispatcherPath = prepareForRendering(request, response);
// Obtain a RequestDispatcher for the target resource (typically a JSP).
RequestDispatcher rd = getRequestDispatcher(request, dispatcherPath);
if (rd == null) {
throw new ServletException("Could not get RequestDispatcher for [" + getUrl() +
"]: Check that the corresponding file exists within your web application archive!");
}
// If already included or response already committed, perform include, else forward.
if (useInclude(request, response)) {
response.setContentType(getContentType());
if (logger.isDebugEnabled()) {
logger.debug("Including [" + getUrl() + "]");
}
rd.include(request, response);
}
else {
// Note: The forwarded resource is supposed to determine the content type itself.
if (logger.isDebugEnabled()) {
logger.debug("Forwarding to [" + getUrl() + "]");
}
rd.forward(request, response);
}
}
/**
* Always returns a 401 error code to the client.
*/
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException arg2) throws IOException,
ServletException {
log.debug("Pre-authenticated entry point called. Rejecting access");
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access Denied");
}
@Test
public void testExecuteJobServletTest()
throws ServletException, IOException, KettleException {
doReturn( ExecuteJobServlet.CONTEXT_PATH ).when( mockHttpServletRequest ).getContextPath();
doReturn( REPOSITORY_NAME ).when( mockHttpServletRequest ).getParameter( "rep" );
doReturn( AUTHORIZED_USER ).when( mockHttpServletRequest ).getParameter( "user" );
doReturn( PASSWORD ).when( mockHttpServletRequest ).getParameter( "pass" );
doReturn( JOB_NAME ).when( mockHttpServletRequest ).getParameter( "job" );
doReturn( LEVEL ).when( mockHttpServletRequest ).getParameter( "level" );
PowerMockito.mockStatic( Encr.class );
when( Encr.decryptPasswordOptionallyEncrypted( PASSWORD ) ).thenReturn( PASSWORD );
doReturn( repository ).when( spyExecuteJobServlet ).openRepository( REPOSITORY_NAME, AUTHORIZED_USER, PASSWORD );
JobMeta jobMeta = buildJobMeta();
RepositoryDirectoryInterface repositoryDirectoryInterface = mock( RepositoryDirectoryInterface.class );
doReturn( repositoryDirectoryInterface ).when( repository ).loadRepositoryDirectoryTree();
doReturn( mock( RepositoryDirectoryInterface.class ) ).when( repositoryDirectoryInterface )
.findDirectory( anyString() );
doReturn( mock( ObjectId.class ) ).when( repository )
.getJobId( anyString(), any( RepositoryDirectoryInterface.class ) );
doReturn( jobMeta ).when( repository ).loadJob( any( ObjectId.class ), anyString() );
doReturn( Collections.emptyEnumeration() ).when( mockHttpServletRequest ).getParameterNames();
StringWriter out = mockWriter();
spyExecuteJobServlet.doGet( mockHttpServletRequest, spyHttpServletResponse );
assertTrue( out.toString().contains( WebResult.STRING_OK ) );
assertTrue( out.toString().contains( "Job started" ) );
}
@POST
public Response processPost(){
StringBuilder builder = new StringBuilder();
try {
doPost();
builder.append("SUCCESS");
} catch (ServletException | IOException e) {
builder.append("FAILURE due to: "+e);
}
GenericEntity<String> entity = new GenericEntity<String>(
builder.toString()) {
};
return Response.ok(entity).build();
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// some code
response.setContentType("text/html;charset=UTF-8");
org.owasp.benchmark.helpers.SeparateClassRequest scr = new org.owasp.benchmark.helpers.SeparateClassRequest( request );
String param = scr.getTheValue("BenchmarkTest00051");
String a1 = "";
String a2 = "";
String osName = System.getProperty("os.name");
if (osName.indexOf("Windows") != -1) {
a1 = "cmd.exe";
a2 = "/c";
} else {
a1 = "sh";
a2 = "-c";
}
String[] args = {a1, a2, "echo " + param};
ProcessBuilder pb = new ProcessBuilder(args);
try {
Process p = pb.start();
org.owasp.benchmark.helpers.Utils.printOSCommandResults(p, response);
} catch (IOException e) {
System.out.println("Problem executing cmdi - java.lang.ProcessBuilder(java.lang.String[]) Test Case");
throw new ServletException(e);
}
}
/**
* Check access token cookie and refresh it, if it is either not present, expired or about to expire.
*/
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
try {
httpServletRequest = refreshTokensIfExpiring(httpServletRequest, httpServletResponse);
} catch (ClientAuthenticationException ex) {
log.warn("Security exception: could not refresh tokens", ex);
httpServletRequest = authenticationService.stripTokens(httpServletRequest);
}
filterChain.doFilter(httpServletRequest, servletResponse);
}
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
UserAccountDetails user = (UserAccountDetails) authentication.getPrincipal();
userAccountService.updateLatelyLoginTime(user.getUserAccountId());
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
PrintWriter out = response.getWriter();
out.println(JSONObject.toJSONString(Result.success().setMsg("登录成功")));
out.flush();
out.close();
}
private static String doSomething(HttpServletRequest request, String param) throws ServletException, IOException {
String bar = "safe!";
java.util.HashMap<String,Object> map43776 = new java.util.HashMap<String,Object>();
map43776.put("keyA-43776", "a-Value"); // put some stuff in the collection
map43776.put("keyB-43776", param); // put it in a collection
map43776.put("keyC", "another-Value"); // put some stuff in the collection
bar = (String)map43776.get("keyB-43776"); // get it back out
return bar;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
if (enabled) {
super.doFilter(request, response, filterChain);
return;
}
filterChain.doFilter(request, response);
}
@Override
public Authentication attemptAuthentication(
HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException, IOException, ServletException {
String jwt = request.getHeader("X-SMS-VERIFICATION-JWT");
SmsVerificationClaims claims = smsVerificationJwtVerifier.verify(jwt, "SMS_LOGIN");
String mobile = claims.getMobile();
return userRepository.mustFindByMobile(mobile);
}
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
if (!HttpServletRequest.class.isInstance(request)) {
chain.doFilter(request, response);
return;
}
final HttpServletRequest httpServletRequest = HttpServletRequest.class.cast(request);
final HttpServletResponse httpServletResponse = HttpServletResponse.class.cast(response);
if (!this.delegate.isCXFResource(httpServletRequest)) {
chain.doFilter(request, response);
return;
}
if (CxfRsHttpListener.TRY_STATIC_RESOURCES) { // else 100% JAXRS
if (servletMappingIsUnderRestPath(httpServletRequest)) {
chain.doFilter(request, response);
return;
}
final InputStream staticContent = delegate.findStaticContent(httpServletRequest, welcomeFiles);
if (staticContent != null) {
chain.doFilter(request, response);
return;
}
}
try {
delegate.doInvoke(
new ServletRequestAdapter(httpServletRequest, httpServletResponse, request.getServletContext()),
new ServletResponseAdapter(httpServletResponse));
} catch (final Exception e) {
throw new ServletException("Error processing webservice request", e);
}
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException, IOException, ServletException {
if (!HttpMethod.POST.name().equals(request.getMethod())) {
if(log.isDebugEnabled()) {
log.debug("Authentication method not supported. Request method: " + request.getMethod());
}
throw new AuthMethodNotSupportedException("Authentication method not supported");
}
PublicLoginRequest loginRequest;
try {
loginRequest = objectMapper.readValue(request.getReader(), PublicLoginRequest.class);
} catch (Exception e) {
throw new AuthenticationServiceException("Invalid public login request payload");
}
if (StringUtils.isBlank(loginRequest.getPublicId())) {
throw new AuthenticationServiceException("Public Id is not provided");
}
UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.PUBLIC_ID, loginRequest.getPublicId());
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal, "");
return this.getAuthenticationManager().authenticate(token);
}
@Override
public final void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse,
final FilterChain filterChain) throws IOException, ServletException {
if (endpointSecurityService.isAllowed(servletRequest) && canCall(servletRequest)) {
filterChain.doFilter(servletRequest, servletResponse);
return;
}
final HttpServletResponse response = HttpServletResponse.class.cast(servletResponse);
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
@Override
public void init( FilterConfig config ) throws ServletException {
if (logger.isTraceEnabled()) {
logger.trace("init(FilterConfig paramFilterConfig)");
}
if ( sc == null ) {
sc = config.getServletContext();
}
properties = ( Properties ) getSpringBeanFromWeb( "properties" );
loadSwagger();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
Cookie[] requestCookies = request.getCookies();
out.write("<html><head></head><body>");
out.write("<h3>Hello Browser!!</h3>");
if(requestCookies != null){
out.write("<h3>Request Cookies:</h3>");
for(Cookie c : requestCookies){
out.write("Name="+c.getName()+", Value="+c.getValue()+", Comment="+c.getComment()
+", Domain="+c.getDomain()+", MaxAge="+c.getMaxAge()+", Path="+c.getPath()
+", Version="+c.getVersion());
out.write("<br>");
}
}
//Set cookies for counter, accessible to only this servlet
count++;
Cookie counterCookie = new Cookie("Counter", String.valueOf(count));
//add some description to be viewed in browser cookie viewer
counterCookie.setComment("SetCookie Counter");
//setting max age to be 1 day
counterCookie.setMaxAge(24*60*60);
//set path to make it accessible to only this servlet
counterCookie.setPath("/ServletCookie/cookie/SetCookie");
//adding cookie to the response
response.addCookie(counterCookie);
//set a domain specific cookie
Cookie domainCookie = new Cookie("Test", "Test Cookie"+String.valueOf(count));
domainCookie.setComment("Test Cookie");
response.addCookie(domainCookie);
out.write("</body></html>");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
switch (req.getParameter("action")) {
case "create":
req.getSession(true);
resp.getWriter().write(req.getRequestedSessionId());
break;
case "destroy":
req.getSession().invalidate();
resp.getWriter().write(req.getRequestedSessionId());
break;
case "destroycreate":
req.getSession().invalidate();
req.getSession(true);
resp.getWriter().write(req.getRequestedSessionId());
break;
case "change":
req.changeSessionId();
resp.getWriter().write(req.getRequestedSessionId());
break;
case "timeout":
req.getSession(true).setMaxInactiveInterval(1);
resp.getWriter().write(req.getRequestedSessionId());
break;
case "isvalid":
resp.getWriter().write(req.isRequestedSessionIdValid() + "");
break;
case "default":
resp.getWriter().write(req.getRequestedSessionId());
break;
}
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (filterConfig == null)
return;
uri = ((HttpServletRequest)request).getRequestURI();
LOG.info("filtering " + uri);
chain.doFilter(request, response);
}