<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.idvsbruck</groupId> <artifactId>jetty-spring-test</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>test</name> <description>Embedded Jetty, Spring Java-based configuration</description> <developers> <developer> <id>IDVsbruck</id> </developer> </developers> <properties> <out.name>${project.artifactId}</out.name> <out.folder>out</out.folder> <source.folder>source</source.folder> <resource.folder>resource</resource.folder> <spring.version>4.1.6.RELEASE</spring.version> <spring.security.version>4.0.0.RELEASE</spring.security.version> <jetty.version>9.3.0.M1</jetty.version> </properties> <build> <finalName>${out.name}</finalName> <directory>${out.folder}</directory> <testOutputDirectory>${out.folder}</testOutputDirectory> <outputDirectory>${out.folder}</outputDirectory> <testSourceDirectory>${source.folder}</testSourceDirectory> <sourceDirectory>${source.folder}</sourceDirectory> <resources> <resource> <directory>${resource.folder}</directory> <filtering>true</filtering> </resource> </resources> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> </plugins> </build> <dependencies> <!-- Embedded Jetty server --> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-server</artifactId> <version>${jetty.version}</version> </dependency> <!-- Web Application Context Handler --> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-webapp</artifactId> <version>${jetty.version}</version> </dependency> <!-- , Jetty- --> <!-- () Jetty --> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-annotations</artifactId> <version>${jetty.version}</version> </dependency> <!-- Runtime JSP, Jetty JSP --> <!-- jsp- --> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-jsp</artifactId> <version>${jetty.version}</version> </dependency> <!-- Spring MVC --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- Spring ORM --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <!-- Spring Security --> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>${spring.security.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>${spring.security.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>${spring.security.version}</version> </dependency> <!-- --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.5</version> </dependency> <!-- Hibernate ORM --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.3.8.Final</version> </dependency> <!-- org.hibernate.validator.constraints javax.validation.constraints --> <!-- - --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.1.3.Final</version> </dependency> <!-- DBCP Apache --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>2.0.1</version> </dependency> <!-- MySQL ( ) --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.31</version> </dependency> <!-- Spring Security jsr250 --> <dependency> <groupId>javax.annotation</groupId> <artifactId>jsr250-api</artifactId> <version>1.0</version> </dependency> </dependencies> </project>
base.url=/test base.port=8080 database.url=jdbc:mysql://localhost:3306/test database.user=root database.password=root log4j.rootLogger=INFO, CONSOLE log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n log4j.logger.org.hibernate=WARN log4j.logger.org.springframework=WARN log4j.logger.org.springframework.web=WARN log4j.logger.org.springframework.security=WARN log4j.logger.org.eclipse.jetty=WARN log4j.logger.com.idvsbruck.test=DEBUG
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE html> <html> <head> <title>Jetty-Spring :: Test</title> </head> <body> <div>Welcome!<br/>Project context path: ${path}</div> </body> </html>
@Controller public class BaseController { @RequestMapping(value = "/**", method = RequestMethod.GET) public ModelAndView index(HttpSession session, HttpServletRequest request) { ModelAndView result = new ModelAndView("index"); result.addObject("path", request.getContextPath()); return result; } }
log4j: WARN No appenders could be found for logger (org.eclipse.jetty.util.log) .log4j: WARN Please initialize the log4j system properly.log4j: WARN See http://logging.apache.org/log4j/1.2/ faq.html # noconfig for more info.The very question of a damn is not worth it, but newcomers stumble on it constantly. I did it my own way: all properties are stored in one file, the placement of which does not require indication in the classpath , and is loaded once at project start. Necessity and meaning are very controversial, but rather it’s just a solution to an interesting puzzle.
@Configuration @ComponentScan(basePackages = "com.idvsbruck.test") @PropertySource({"WEB-INF/application.properties"}) public class ApplicationContext { // ConfigurableEnvironment // embedded Jetty @PropertySource @Bean public static PropertySourcesPlaceholderConfigurer appProperty() { return new PropertySourcesPlaceholderConfigurer(); } // , // @Bean(name = "messageSource") public MessageSource messageSource() { ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource.setBasenames("WEB-INF/i18n/messages", "WEB-INF/i18n/errors"); messageSource.setDefaultEncoding("UTF-8"); return messageSource; } }
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:property-placeholder location="/WEB-INF/application.properties"/> <context:annotation-config/> <context:component-scan base-package="com.idvsbruck.test"/> <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basenames" value="/WEB-INF/i18n/messages, /WEB-INF/i18n/errors"/> <property name="defaultEncoding" value="UTF-8"/> </bean> </beans>
@Configuration @EnableTransactionManagement public class PersistenceContext { @Autowired private Environment environment; @Bean(name = "sessionFactory") public SessionFactory sessionFactory() throws IOException { final LocalSessionFactoryBean factory = new LocalSessionFactoryBean(); factory.setDataSource(dataSource()); factory.setHibernateProperties(hibernateProperties()); factory.setPackagesToScan("com.idvsbruck.test.entity"); factory.afterPropertiesSet(); return factory.getObject(); } @Bean(name = "dataSource") public DataSource dataSource() { final BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl(environment.getProperty("database.url")); dataSource.setUsername(environment.getProperty("database.user")); dataSource.setPassword(environment.getProperty("database.password")); return dataSource; } @Bean(name = "transactionManager") public HibernateTransactionManager transactionManager() throws IOException { return new HibernateTransactionManager(sessionFactory()); } private static Properties hibernateProperties() { Properties hibernateProperties = new Properties(); hibernateProperties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); hibernateProperties.put("hibernate.connection.autocommit", true); hibernateProperties.put("hibernate.show_sql", false); hibernateProperties.put("hibernate.format_sql", false); hibernateProperties.put("hibernate.generate_statistics", false); hibernateProperties.put("hibernate.hbm2ddl.auto", "update"); hibernateProperties.put("hibernate.use_sql_comments", false); hibernateProperties.put("hibernate.cache.use_query_cache", false); hibernateProperties.put("hibernate.cache.use_second_level_cache", true); return hibernateProperties; } }
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="${database.url}"/> <property name="username" value="${database.user}"/> <property name="password" value="${database.password}"/> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.connection.autocommit">true</prop> <prop key="hibernate.show_sql">false</prop> <prop key="hibernate.format_sql">false</prop> <prop key="hibernate.generate_statistics">false</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.use_sql_comments">false</prop> <prop key="hibernate.cache.use_query_cache">false</prop> <prop key="hibernate.cache.use_second_level_cache">true</prop> </props> </property> <property name="packagesToScan" value="com.idvsbruck.test.entity"/> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
@EnableWebMvc @Configuration public class WebContext extends WebMvcConfigurerAdapter { @Autowired private MessageSource messageSource; @Autowired private SessionFactory sessionFactory; // , order -1 , // "/**" @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/javascript/share/**").addResourceLocations("/javascript/share/"); registry.setOrder(-1); } // resolver , , // InternalResourceViewResolver, UrlBasedViewResolver // JstlView JSTL- @Bean public ViewResolver viewResolver(){ InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix("/WEB-INF/views/"); resolver.setSuffix(".jsp"); resolver.setViewClass(JstlView.class); return resolver; } // , -, // @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } // , @Bean(name = "validator") public LocalValidatorFactoryBean validator() { LocalValidatorFactoryBean validatorFactoryBean = new LocalValidatorFactoryBean(); validatorFactoryBean.setValidationMessageSource(messageSource); return validatorFactoryBean; } // Spring MVC @Override public Validator getValidator() { return validator(); } // , ( // ) @Bean public CookieLocaleResolver localeResolver() { CookieLocaleResolver localeResolver = new CookieLocaleResolver(); localeResolver.setDefaultLocale(Locale.forLanguageTag("en")); return localeResolver; } // , - @Override public void addInterceptors(InterceptorRegistry registry) { // LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); localeChangeInterceptor.setParamName("language"); registry.addInterceptor(localeChangeInterceptor); // OSIV OpenSessionInViewInterceptor openSessionInViewInterceptor = new OpenSessionInViewInterceptor(); openSessionInViewInterceptor.setSessionFactory(sessionFactory); registry.addWebRequestInterceptor(openSessionInViewInterceptor); // ApiInterceptor apiInterceptor = new ApiInterceptor(); registry.addInterceptor(apiInterceptor).addPathPatterns("/api/**"); } }
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <mvc:resources mapping="/javascript/share/**" location="/javascript/share/" order="-1"/> <mvc:default-servlet-handler/> <mvc:annotation-driven validator="validator"/> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> <mvc:interceptors> <bean class="org.springframework.orm.hibernate4.support.OpenSessionInViewInterceptor"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"> <property name="paramName" value="language"/> </bean> <mvc:interceptor> <mvc:mapping path="/api/**"/> <bean class="com.idvsbruck.test.common.ApiInterceptor"/> </mvc:interceptor> </mvc:interceptors> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver"> <property name="defaultLocale" value="en"/> </bean> </beans>
@Configuration // debug=true, - @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true) public class SecurityContext extends WebSecurityConfigurerAdapter { // web based security http- @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/**").permitAll(); http.formLogin().loginPage("/signin"); http.logout().invalidateHttpSession(true).logoutSuccessUrl("/").logoutUrl("/signout"); http.anonymous().authorities("USER_ANONYMOUS").principal("guest").key("foobar"); } // @Override public void configure(WebSecurity web) { web.ignoring().antMatchers("/javascript/share/**"); } // ( - InMemory, , .. // @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(authenticationProvider()); } // , ; @Bean @Override public AuthenticationManager authenticationManager() throws Exception { return super.authenticationManager(); } // @Bean(name = "authenticationProvider") public AuthenticationProvider authenticationProvider() { return new CustomAuthenticationProvider(); } // UserDetailsService @Bean(name = "userDetailsService") public UserDetailsService userDetailsService() { return new CustomUserDetailsManager(); } // ; deprecated org.springframework.security.authentication.encoding.PasswordEncoder // org.springframework.security.crypto.password.PasswordEncoder // BCryptPasswordEncoder - BCrypt, StandartPasswordEncoder, // SHA-256 NoOpPasswordEncoder ( ) @Bean(name = "passwordEncoder") public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:security="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd"> <security:http pattern="/javascript/share/**" security="none"/> <security:global-method-security secured-annotations="enabled" jsr250-annotations="enabled" pre-post-annotations="enabled"/> <security:http auto-config="false" use-expressions="true" disable-url-rewriting="true" entry-point-ref="authEntryPoint"> <security:intercept-url pattern="/**" access="permitAll"/> <security:form-login login-page="/signin"/> <security:logout invalidate-session="true" logout-success-url="/" logout-url="/signout"/> <security:anonymous enabled="true" username="guest" granted-authority="USER_ANONYMOUS" key="foobar"/> </security:http> <security:authentication-manager alias="authenticationManager"> <security:authentication-provider ref="customAuthenticationProvider"/> </security:authentication-manager> <bean id="customAuthenticationProvider" class="com.idvsbruck.test.security.CustomAuthenticationProvider"> <property name="userDetailsService" ref="userDetailsService"/> </bean> <bean id="userDetailsService" class="com.idvsbruck.test.security.CustomUserDetailsManager"/> <bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/> </beans>
public class Main { public static void main(String... args) throws Exception { Properties properties = new Properties(); // Properties InputStream stream = Main.class.getResourceAsStream("/WEB-INF/application.properties"); properties.load(stream); stream.close(); // log4j PropertyConfigurator.configure(properties); // - Java-based WebContext AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext(); webContext.register(WebContext.class); // webContext.getEnvironment().getPropertySources().addLast(new PropertiesPropertySource("applicationEnvironment", properties)); // Spring MVC ServletHolder servletHolder = new ServletHolder("test-dispatcher", new DispatcherServlet(webContext)); servletHolder.setAsyncSupported(true); servletHolder.setInitOrder(1); // Spring Security FilterHolder filterHolder = new FilterHolder(new DelegatingFilterProxy("springSecurityFilterChain")); filterHolder.setAsyncSupported(true); // - Jetty WebAppContext webAppContext = new WebAppContext(); // webAppContext.setInitParameter("contextConfigLocation", ApplicationContext.class.getName()); // , WEB-INF webAppContext.setResourceBase("resource"); // , Context Path, webAppContext.addEventListener(new ContextLoaderListener(webContext)); webAppContext.setContextPath(properties.getProperty("base.url")); webAppContext.addServlet(servletHolder, "/"); webAppContext.addFilter(filterHolder, "/*", EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR)); // Server server = new Server(Integer.parseInt(properties.getProperty("base.port"))); server.setHandler(webAppContext); server.start(); server.join(); } }
public class Main { public static void main(String... args) throws Exception { Properties properties = new Properties(); InputStream stream = Main.class.getResourceAsStream("/WEB-INF/application.properties"); properties.load(stream); stream.close(); PropertyConfigurator.configure(properties); WebAppContext webAppContext = new WebAppContext(); webAppContext.setResourceBase("resource"); webAppContext.setContextPath(properties.getProperty("base.url")); webAppContext.setConfigurations(new Configuration[] { new WebXmlConfiguration(), new AnnotationConfiguration() { @Override public void preConfigure(WebAppContext context) { ClassInheritanceMap map = new ClassInheritanceMap(); map.put(WebApplicationInitializer.class.getName(), new ConcurrentHashSet<String>() {{ add(WebInitializer.class.getName()); add(SecurityWebInitializer.class.getName()); }}); context.setAttribute(CLASS_INHERITANCE_MAP, map); _classInheritanceHandler = new ClassInheritanceHandler(map); } } }); Server server = new Server(Integer.parseInt(properties.getProperty("base.port"))); server.setHandler(webAppContext); server.start(); server.join(); } }
public class SecurityWebInitializer extends AbstractSecurityWebApplicationInitializer { }
... <filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <async-supported>true</async-supported> </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>ERROR</dispatcher> </filter-mapping> ...
public class WebInitializer extends AbstractSecurityWebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) { AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext(); applicationContext.register(ApplicationContext.class); servletContext.addListener(new ContextLoaderListener(applicationContext)); ServletRegistration.Dynamic dispatcher = servletContext.addServlet("test-dispatcher", new DispatcherServlet(applicationContext)); dispatcher.setLoadOnStartup(1); dispatcher.setAsyncSupported(true); dispatcher.addMapping("/"); } }
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class<?>[] {ApplicationContext.class}; } @Override protected Class<?>[] getServletConfigClasses() { return null; } @Override protected String[] getServletMappings() { return new String[] {"/"}; } @Override protected String getServletName() { return "test-dispatcher"; } }
Source: https://habr.com/ru/post/255773/
All Articles