用代碼配置Spring Web MVC
初始化配置
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
// 返回配置IoC容器的類的類對(duì)象
return new Class<?>[] { AppConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
// 返回配置Spring MVC(視圖解析器沉颂、控制器等)的類的類對(duì)象
return new Class<?>[] { WebConfig.class };
}
@Override
protected String[] getServletMappings() {
// 前端控制器映射
return new String[] { "/" };
}
}
配置IoC容器的類
@Configuration
@EnableAspectJAutoProxy
@EnableTransactionManagement
@ComponentScan(basePackages = "com.kygo.springmvc")
public class AppConfig {
@Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/dang?useUnicode=true&characterEncoding=utf8");
dataSource.setUsername("root");
dataSource.setPassword("123456");
dataSource.setInitialSize(10);
dataSource.setMaxIdle(50);
return dataSource;
}
@Bean
public LocalSessionFactoryBean sessionFactory(DataSource dataSource) {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
sessionFactory.setPackagesToScan(new String[] { "com.kygo.springmvc.entity" });
Properties props = new Properties();
props.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
props.setProperty("hibernate.show_sql", "true");
props.setProperty("hibernate.format_sql", "true");
sessionFactory.setHibernateProperties(props);
return sessionFactory;
}
@Bean
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
return new HibernateTransactionManager(sessionFactory);
}
}
配置Spring MVC(視圖解析器浩峡、控制器等)的類
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.kygo.springmvc.controller")
public class WebConfig extends WebMvcConfigurerAdapter {
// 視圖解析器
@Bean
public ViewResolver internalResourceViewResolver() {
InternalResourceViewResolver resolver =
new InternalResourceViewResolver();
resolver.setViewClass(JstlView.class);
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
return resolver;
}
// 靜態(tài)網(wǎng)頁(yè)依然由默認(rèn)servlet處理
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
表單數(shù)據(jù)驗(yàn)證
需要jar包
validation-api-1.1.0.Final.jar
hibernate-validator-5.4.1.Final.jar
需要驗(yàn)證的數(shù)據(jù)
@Pattern(regexp = "^\\w+([-_.]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,6})+$")
private String email;
控制器
public String register(@Valid UserRegDto userDto, Errors errors)