下面列出了javax.servlet.http.HttpServletRequest#removeAttribute() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Expose the model objects in the given map as request attributes.
* Names will be taken from the model Map.
* This method is suitable for all resources reachable by {@link javax.servlet.RequestDispatcher}.
* @param model Map of model objects to expose
* @param request current HTTP request
*/
protected void exposeModelAsRequestAttributes(Map<String, Object> model, HttpServletRequest request) throws Exception {
for (Map.Entry<String, Object> entry : model.entrySet()) {
String modelName = entry.getKey();
Object modelValue = entry.getValue();
if (modelValue != null) {
request.setAttribute(modelName, modelValue);
if (logger.isDebugEnabled()) {
logger.debug("Added model object '" + modelName + "' of type [" + modelValue.getClass().getName() +
"] to request in view with name '" + getBeanName() + "'");
}
}
else {
request.removeAttribute(modelName);
if (logger.isDebugEnabled()) {
logger.debug("Removed model object '" + modelName +
"' from request in view with name '" + getBeanName() + "'");
}
}
}
}
@Override
public void postHandle(
HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView)
throws ServletException {
if (request.getParameter("noView") != null) {
modelAndView.clear();
}
if (request.getAttribute("test1x") == null) {
throw new ServletException("Wrong interceptor order");
}
if (!"test2x".equals(request.getAttribute("test2x"))) {
throw new ServletException("Incorrect request attribute");
}
request.removeAttribute("test2x");
}
/**
*
* 更改登录密码
*
* @param request
* @param oldPassword
* @param newPassword
* @param code
* @param user
* @return
* @throws Exception
*/
@RequestMapping("/update/password")
@Transactional(rollbackFor = Exception.class)
public MessageResult updateLoginPassword(HttpServletRequest request, String oldPassword, String newPassword, String code, @SessionAttribute(SESSION_MEMBER) AuthMember user) throws Exception {
hasText(oldPassword, msService.getMessage("MISSING_OLD_PASSWORD"));
hasText(newPassword, msService.getMessage("MISSING_NEW_PASSWORD"));
isTrue(newPassword.length() >= 6 && newPassword.length() <= 20, msService.getMessage("PASSWORD_LENGTH_ILLEGAL"));
ValueOperations valueOperations = redisTemplate.opsForValue();
Object cache = valueOperations.get(SysConstant.PHONE_UPDATE_PASSWORD_PREFIX + user.getMobilePhone());
notNull(cache, msService.getMessage("NO_GET_VERIFICATION_CODE"));
hasText(code, msService.getMessage("MISSING_VERIFICATION_CODE"));
if (!code.equals(cache.toString())) {
return MessageResult.error(msService.getMessage("VERIFICATION_CODE_INCORRECT"));
} else {
valueOperations.getOperations().delete(SysConstant.PHONE_UPDATE_PASSWORD_PREFIX + user.getMobilePhone());
}
Member member = memberService.findOne(user.getId());
request.removeAttribute(SysConstant.SESSION_MEMBER);
isTrue(Md5.md5Digest(oldPassword + member.getSalt()).toLowerCase().equals(member.getPassword()), msService.getMessage("PASSWORD_ERROR"));
member.setPassword(Md5.md5Digest(newPassword + member.getSalt()).toLowerCase());
return MessageResult.success(msService.getMessage("SETTING_SUCCESS"));
}
@Override
public boolean doAuthenticate(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
String user = null;
if (predicate != null) {
if (predicate.test(request)) {
user = (String) request.getAttribute(Principal.class.getName());
request.removeAttribute(Principal.class.getName());
}
}
final AtomicBoolean requestContinues = new AtomicBoolean(false);
forward(user, request, response, (req, res) -> {
filterChain.doFilter(req, res);
requestContinues.set(true);
});
return requestContinues.get();
}
public String getActionURL(FacesContext context, String viewId)
{
HttpServletRequest req = (HttpServletRequest) context.getExternalContext().getRequest();
if (req.getAttribute(URL_EXT) == null)
{
// If the request didn't go through JsfTool (the JSF is accessed directly from its webapp,
// not as a Sakai tool), then don't do Sakai's special action URL handling.
return getWrapped().getActionURL(context, viewId);
}
// get the path that got us here (from the tool's point of view)
String path = viewId;
// modify the path to remove things that were added by Sakai navigation to get here (prefix path, suffix extension)
String prefix = (String) req.getAttribute(URL_PATH);
if ((prefix != null) && path.startsWith(prefix)) path = path.substring(prefix.length());
Object extensions = req.getAttribute(URL_EXT);
String [] exts = extensions instanceof String?new String[]{(String)extensions}:(String[])extensions;
for (String ext:exts) {
if ((ext != null) && path.endsWith(ext)) path = path.substring(0, path.length() - ext.length());
}
// make sure the URL processing uses the Sakai, not Native the request object so we can get at the URL information setup by the invoker
req.removeAttribute(Tool.NATIVE_URL);
// form our return URL
String rv = Web.returnUrl(req, path);
// restore (if needed)
req.setAttribute(Tool.NATIVE_URL, Tool.NATIVE_URL);
log.debug("action url for view: " + viewId + " = " + rv);
return rv;
}
/**
* Removes the whole request vars map.
*/
public static void removeRequestVars(HttpServletRequest request,
Map<String, Object> context, Environment env) throws TemplateModelException {
if (request != null) {
request.removeAttribute(ContextFtlUtil.REQUEST_VAR_MAP_NAME_REQATTRIBS);
}
Map<String, Object> globalContext = getGlobalContext(context, env);
if (globalContext != null) {
globalContext.remove(ContextFtlUtil.REQUEST_VAR_MAP_NAME_GLOBALCONTEXT);
}
if (env != null) {
env.setGlobalVariable(ContextFtlUtil.REQUEST_VAR_MAP_NAME_FTLGLOBALS, null);
}
}
@Override
public void afterCompletion(
HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
if (request.getAttribute("test1y") == null) {
throw new ServletException("Wrong interceptor order");
}
if (request.getAttribute("test2y") == null) {
throw new ServletException("afterCompletion invoked twice");
}
request.removeAttribute("test2y");
}
public String getActionURL(FacesContext context, String viewId)
{
HttpServletRequest req = (HttpServletRequest) context.getExternalContext().getRequest();
if (req.getAttribute(URL_EXT) == null)
{
// If the request didn't go through JsfTool (the JSF is accessed directly from its webapp,
// not as a Sakai tool), then don't do Sakai's special action URL handling.
return getWrapped().getActionURL(context, viewId);
}
// get the path that got us here (from the tool's point of view)
String path = viewId;
// modify the path to remove things that were added by Sakai navigation to get here (prefix path, suffix extension)
String prefix = (String) req.getAttribute(URL_PATH);
if ((prefix != null) && path.startsWith(prefix)) path = path.substring(prefix.length());
Object extensions = req.getAttribute(URL_EXT);
String [] exts = extensions instanceof String?new String[]{(String)extensions}:(String[])extensions;
for (String ext:exts) {
if ((ext != null) && path.endsWith(ext)) path = path.substring(0, path.length() - ext.length());
}
// make sure the URL processing uses the Sakai, not Native the request object so we can get at the URL information setup by the invoker
req.removeAttribute(Tool.NATIVE_URL);
// form our return URL
String rv = Web.returnUrl(req, path);
// restore (if needed)
req.setAttribute(Tool.NATIVE_URL, Tool.NATIVE_URL);
log.debug("action url for view: " + viewId + " = " + rv);
return rv;
}
@Override
public void postHandle(
HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
throws ServletException {
if (request.getAttribute("test2x") != null) {
throw new ServletException("Wrong interceptor order");
}
if (!"test1x".equals(request.getAttribute("test1x"))) {
throw new ServletException("Incorrect request attribute");
}
request.removeAttribute("test1x");
}
@Override
public void afterCompletion(
HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
if (request.getAttribute("test1y") == null) {
throw new ServletException("Wrong interceptor order");
}
request.removeAttribute("test2y");
}
/**
* 绑定手机号
*
* @param password
* @param phone
* @param code
* @param user
* @return
*/
@RequestMapping("/bind/phone")
@Transactional(rollbackFor = Exception.class)
public MessageResult bindPhone(HttpServletRequest request, String password, String phone, String code, @SessionAttribute(SESSION_MEMBER) AuthMember user) throws Exception {
hasText(password, msService.getMessage("MISSING_LOGIN_PASSWORD"));
hasText(phone, msService.getMessage("MISSING_PHONE"));
hasText(code, msService.getMessage("MISSING_VERIFICATION_CODE"));
if ("中国".equals(user.getLocation().getCountry())) {
if (!ValidateUtil.isMobilePhone(phone.trim())) {
return MessageResult.error(msService.getMessage("PHONE_FORMAT_ERROR"));
}
}
ValueOperations valueOperations = redisTemplate.opsForValue();
Object cache = valueOperations.get(SysConstant.PHONE_BIND_CODE_PREFIX + phone);
notNull(cache, msService.getMessage("NO_GET_VERIFICATION_CODE"));
Member member1 = memberService.findByPhone(phone);
isTrue(member1 == null, msService.getMessage("PHONE_ALREADY_BOUND"));
if (!code.equals(cache.toString())) {
return MessageResult.error(msService.getMessage("VERIFICATION_CODE_INCORRECT"));
} else {
valueOperations.getOperations().delete(SysConstant.PHONE_BIND_CODE_PREFIX + phone);
}
Member member = memberService.findOne(user.getId());
isTrue(member.getMobilePhone() == null, msService.getMessage("REPEAT_PHONE_REQUEST"));
if (member.getPassword().equals(Md5.md5Digest(password + member.getSalt()).toLowerCase())) {
member.setMobilePhone(phone);
return MessageResult.success(msService.getMessage("SETTING_SUCCESS"));
} else {
request.removeAttribute(SysConstant.SESSION_MEMBER);
return MessageResult.error(msService.getMessage("PASSWORD_ERROR"));
}
}
private static void reset(HttpServletRequest req, String... mts) {
/**
* RestAction 中 ServletPath 为 /api/, PathInfo 为 /abc/def
* ApisAction 中 ServletPath 为 /abc/def.api, 并无 PathInfo
* 故需将前者转换为后者的形式, 然后交由 ApisAction 继续处理
*/
String uri = parse (req, mts);
req.setAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH , uri);
req.removeAttribute(RequestDispatcher.INCLUDE_PATH_INFO);
req.setAttribute(RequestDispatcher.FORWARD_SERVLET_PATH , uri);
req.removeAttribute(RequestDispatcher.FORWARD_PATH_INFO);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
request.removeAttribute("startTime");
System.out.println(">>>>> MyInterceptor2 afterCompletion >>>>>>>>>>>>>>>>>>>>>>");
}
/**
* Remove authentication result from request and cache
* @param req
*/
private void removeAuthenticationResultFromRequest(HttpServletRequest req) {
req.removeAttribute(FrameworkConstants.RequestAttribute.AUTH_RESULT);
}
/** {@inheritDoc} */
public ActionForward execute(ActionMapping mapping,
ActionForm formIn,
HttpServletRequest request,
HttpServletResponse response) {
DynaActionForm form = (DynaActionForm) formIn;
RequestContext ctx = new RequestContext(request);
request.setAttribute(mapping.getParameter(), Boolean.TRUE);
if (ctx.isSubmitted()) {
ValidatorResult result = RhnValidationHelper.validate(this.getClass(),
makeValidationMap(form), null,
VALIDATION_XSD);
if (!result.isEmpty()) {
getStrutsDelegate().saveMessages(request, result);
RhnValidationHelper.setFailedValidation(request);
}
else {
try {
CobblerSnippet snip = submit(request, form);
if (isCreateMode(request)) {
createSuccessMessage(request,
"cobblersnippet.create.success", snip.getName());
}
else {
createSuccessMessage(request,
"cobblersnippet.update.success", snip.getName());
}
request.removeAttribute(CREATE_MODE);
setupSnippet(request, form, snip);
return getStrutsDelegate().forwardParam(mapping.findForward("success"),
NAME, snip.getName());
}
catch (ValidatorException ve) {
getStrutsDelegate().saveMessages(request, ve.getResult());
RhnValidationHelper.setFailedValidation(request);
}
}
}
setup(request, form);
return mapping.findForward(RhnHelper.DEFAULT_FORWARD);
}
@Override
public void removeValue(HttpServletRequest request, String name) {
request.removeAttribute(name);
}
@Test
public final void testDispatchRequestToManagedPipeline() throws ServletException, IOException {
DaggerServletContextListener contextListener = new DaggerServletContextListener() {
@Override
protected Class<?>[] getBaseModules() {
return new Class<?>[]{TestModule.class};
}
@Override
protected Class<?>[] getRequestScopedModules() {
return new Class<?>[]{ServletRequestModule.class};
}
@Override
protected void configureServlets() {
filter("/*").through(TestFilter.class);
filter("*.html").through(TestFilter.class);
filter("/*").through(TestFilter.class);
// These filters should never fire
filter("/index/*").through(TestFilter.class);
filter("*.jsp").through(TestFilter.class);
// Bind a servlet
serve("*.html").with(TestServlet.class);
}
};
ServletContext servletContext = createMock("blah", ServletContext.class);
contextListener.contextInitialized(new ServletContextEvent(servletContext));
final ObjectGraph objectGraph = contextListener.getObjectGraph();
final FilterPipeline pipeline = objectGraph.get(FilterPipeline.class);
pipeline.initPipeline(null);
// create ourselves a mock request with test URI
HttpServletRequest requestMock = control.createMock(HttpServletRequest.class);
expect(requestMock.getRequestURI())
.andReturn("/index.html")
.anyTimes();
expect(requestMock.getContextPath())
.andReturn("")
.anyTimes();
requestMock.setAttribute(REQUEST_DISPATCHER_REQUEST, true);
requestMock.removeAttribute(REQUEST_DISPATCHER_REQUEST);
HttpServletResponse responseMock = control.createMock(HttpServletResponse.class);
expect(responseMock.isCommitted())
.andReturn(false)
.anyTimes();
responseMock.resetBuffer();
expectLastCall().anyTimes();
FilterChain filterChain = control.createMock(FilterChain.class);
//dispatch request
control.replay();
pipeline.dispatch(requestMock, responseMock, filterChain);
pipeline.destroyPipeline();
control.verify();
TestServlet servlet = objectGraph.get(TestServlet.class);
assertEquals(2, servlet.processedUris.size());
assertTrue(servlet.processedUris.contains("/index.html"));
assertTrue(servlet.processedUris.contains(TestServlet.FORWARD_TO));
assertTrue(inits == 1 && doFilters == 3 && destroys == 1, "lifecycle states did not"
+ " fire correct number of times-- inits: " + inits + "; dos: " + doFilters
+ "; destroys: " + destroys);
}
@SuppressWarnings("unchecked")
@Override
public void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Object obj = request.getAttribute(ServletController.AUTH_SERVICE_LIST);
boolean isAuthServiceList = false;
if (obj != null) {
isAuthServiceList = Boolean.valueOf(obj.toString());
}
if (isAuthServiceList) {
String authServiceListRealm = (String)request.getAttribute(ServletController.AUTH_SERVICE_LIST_REALM);
ServiceListJAASAuthenticator authenticator = new ServiceListJAASAuthenticator();
authenticator.setRealm(authServiceListRealm);
if (!authenticator.authenticate(request, response)) {
return;
}
request.removeAttribute(ServletController.AUTH_SERVICE_LIST);
request.removeAttribute(ServletController.AUTH_SERVICE_LIST_REALM);
}
AbstractDestination[] destinations = destinationRegistry.getSortedDestinations();
if (request.getParameter("stylesheet") != null) {
renderStyleSheet(request, response);
return;
}
List<String> privateEndpoints;
if (bus == null) {
bus = BusFactory.getDefaultBus(false);
}
if (bus != null) {
privateEndpoints = (List<String>)bus.getProperty("org.apache.cxf.private.endpoints");
} else {
privateEndpoints = new ArrayList<>();
}
AbstractDestination[] soapEndpoints = getSOAPEndpoints(destinations, privateEndpoints);
AbstractDestination[] restEndpoints = getRestEndpoints(destinations, privateEndpoints);
ServiceListWriter serviceListWriter;
if ("false".equals(request.getParameter("formatted"))) {
boolean renderWsdlList = "true".equals(request.getParameter("wsdlList"));
serviceListWriter = new UnformattedServiceListWriter(renderWsdlList, bus);
} else {
String styleSheetPath;
if (serviceListStyleSheet != null) {
styleSheetPath = request.getContextPath() + "/" + serviceListStyleSheet;
} else {
styleSheetPath = "";
String contextPath = request.getContextPath();
if (contextPath != null) {
styleSheetPath += contextPath;
}
String servletPath = request.getServletPath();
if (servletPath != null) {
styleSheetPath += servletPath;
}
String pathInfo = request.getPathInfo();
if (pathInfo != null) {
styleSheetPath += pathInfo;
}
if (!styleSheetPath.endsWith("/")) {
styleSheetPath += "/";
}
styleSheetPath += "?stylesheet=1";
}
serviceListWriter =
new FormattedServiceListWriter(styleSheetPath, title, showForeignContexts, bus);
}
response.setContentType(serviceListWriter.getContentType());
Object basePath = request.getAttribute(Message.BASE_PATH);
serviceListWriter.writeServiceList(response.getWriter(),
basePath == null ? null : basePath.toString(),
soapEndpoints, restEndpoints);
}
@Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse rep, Object handler) {
// 在跳转到该方法先清除request中的国际化信息
req.removeAttribute(MessageResourceExtension.I18N_ATTRIBUTE);
return true;
}
public ActionForward removeClass(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
ContextUtils.setClassContext(request);
InfoClass infoClass = (InfoClass) request.getAttribute(PresentationConstants.CLASS_VIEW);
InfoShift infoShift = (InfoShift) request.getAttribute(PresentationConstants.SHIFT);
RemoverTurno.run(infoShift, infoClass);
ContextUtils.setShiftContext(request);
request.removeAttribute(PresentationConstants.CLASS_VIEW);
return prepareEditShift(mapping, form, request, response);
}