Ссылка: https://wenku.baidu.com/view/493cf9eba300a6c30d229f49.html
Root WebApplicationContext
и Servlet WebApplicationContext
использует Environment и инициализирует PropertySources на основе профиля пружины , Для приложений, не поддерживающих Spring, нам нужно настроить их, чтобы получить свойства от сервера конфигурации и обновлять компоненты при каждом изменении свойства. Ниже приведены изменения, которые должны произойти, чтобы заставить конфигурацию работать в SpringMVC. Вам также понадобится системное свойство для spring.profile.active
Создайте CustomBeanFactoryPostProcessor
и установите lazyInit
для всех определений бинов в значение true, чтобы инициализировать все бин лениво, т. Е. Бины инициализируются только при запрос.
@Component
public class AddRefreshScopeProcessor implements BeanFactoryPostProcessor, ApplicationContextAware {
private static ApplicationContext applicationContext;
@SuppressWarnings("unchecked")
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
String[] beanNames = applicationContext.getBeanDefinitionNames();
for(int i=0; i T getBean(Class beanClass) {
return applicationContext.getBean(beanClass);
}
/**
* Get a Spring bean by name.
*
* @param beanName
* @return
*/
public static Object getBean(String beanName) {
return applicationContext.getBean(beanName);
}
}
Создайте собственный класс, расширяющий StandardServletEnvironment
и переопределяющий метод initPropertySources
для загрузки дополнительных PropertySources (с сервера конфигурации).
public class CloudEnvironment extends StandardServletEnvironment {
@Override
public void initPropertySources(ServletContext servletContext, ServletConfig servletConfig) {
super.initPropertySources(servletContext,servletConfig);
customizePropertySources(this.getPropertySources());
}
@Override
protected void customizePropertySources(MutablePropertySources propertySources) {
super.customizePropertySources(propertySources);
try {
PropertySource> source = initConfigServicePropertySourceLocator(this);
propertySources.addLast(source);
} catch (
Exception ex) {
ex.printStackTrace();
}
}
private PropertySource> initConfigServicePropertySourceLocator(Environment environment) {
ConfigClientProperties configClientProperties = new ConfigClientProperties(environment);
configClientProperties.setUri("http://localhost:8888");
configClientProperties.setProfile("dev");
configClientProperties.setLabel("master");
configClientProperties.setName("YourApplicationName");
System.out.println("##################### will load the client configuration");
System.out.println(configClientProperties);
ConfigServicePropertySourceLocator configServicePropertySourceLocator =
new ConfigServicePropertySourceLocator(configClientProperties);
return configServicePropertySourceLocator.locate(environment);
}
}
Создайте пользовательский ApplicatonContextInitializer
и переопределите метод initialize
, чтобы установить custom Enviroment
вместо StandardServletEnvironment
.
public class ConfigAppContextInitializer implements ApplicationContextInitializer {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
applicationContext.setEnvironment(new CloudEnvironment());
}
}
Измените web.xml
, чтобы использовать этот инициализатор пользовательского контекста для application context
и servlet context
.
dispatcher
org.springframework.web.servlet.DispatcherServlet
contextInitializerClasses
com.my.context.ConfigAppContextInitializer
1
dispatcher
/
org.springframework.web.context.ContextLoaderListener
contextInitializerClasses
com.my.context.ConfigAppContextInitializer
contextConfigLocation
/WEB-INF/dispatcher-servlet.xml
Чтобы обновить бины, создавшие конечную точку обновления, вам также необходимо обновить application Context
.
@Controller
public class RefreshController {
@Autowired
private RefreshAppplicationContext refreshAppplicationContext;
@Autowired
private RefreshScope refreshScope;
@RequestMapping(path = "/refreshall", method = RequestMethod.GET)
public String refresh() {
refreshScope.refreshAll();
refreshAppplicationContext.refreshctx();
return "Refreshed";
}
}
RefreshAppplicationContext.java
@Component
public class RefreshAppplicationContext implements ApplicationContextAware {
private ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
public void refreshctx(){
((XmlWebApplicationContext)(applicationContext)).refresh();
}
}
Вы можете легко запрограммировать XSS-защиту на Python, см., Например, http://code.activestate.com/recipes/496942/ для получения поучительного и полезного фрагмента код.
The Strip-o-Gram library looks quite nice. I haven't checked it out properly, but it looks like it does things well (i.e. can whitelist HTML tags you specify, as well as HTML-escaping anything nasty).
Here's the example usage snippet, quoted from that page:
from stripogram import html2text, html2safehtml
mylumpofdodgyhtml # a lump of dodgy html ;-)
# Only allow <b>, <a>, <i>, <br>, and <p> tags
mylumpofcoolcleancollectedhtml = html2safehtml(mylumpofdodgyhtml,valid_tags=("b", "a", "i", "br", "p"))
# Don't process <img> tags, just strip them out. Use an indent of 4 spaces
# and a page that's 80 characters wide.
mylumpoftext = html2text(mylumpofcoolcleancollectedhtml,ignore_tags=("img",),indent_width=4,page_width=80)
Hope that helps.