初始化类,建立工厂,要继承AbstractAnnotationConfigDispatcherServletInitializer
package edu.xatu;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {
//后台的根工厂
protected Class<?>[] getRootConfigClasses() {
return new Class[]{RootConfig.class};
}
//相当于Controller的工厂
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebConfig.class};
}
//配置访问路径,根据不同的请求来访问自己工厂里的方法
protected String[] getServletMappings() {
return new String[]{"*.action"};
}
}
WebConfig:要实现WebMvcConfigurer的接口,是为了按照规则起名,防止乱起名。
package edu.xatu;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration//将类放入工厂
@ComponentScan(basePackages = "edu.xatu.springmvc")//包的扫描类
@EnableWebMvc//查找最新的MVC的配置
public class WebConfig implements WebMvcConfigurer {
//配置jsp视图解析器
@Bean
public ViewResolver viewResolver(){
InternalResourceViewResolver resolver=new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/");
resolver.setSuffix(".jsp");
return resolver;
}
}
RootConfig:
package edu.xatu;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
@Configuration//将类放入工厂
@Import(WebConfig.class)//可以不用配置WebConfig里的ComponentScan和EnableWebMvc
public class RootConfig {
@Bean
public DataSource dataSource(){
DruidDataSource dataSource=new DruidDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/cms");
dataSource.setUsername("root");
dataSource.setPassword("123456");
return dataSource;
}
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource){
return new JdbcTemplate(dataSource);
}
@Bean
public DataSourceTransactionManager transactionManager(DataSource dataSource){
return new DataSourceTransactionManager(dataSource);
}
}
文件结构: