前言:
除了mybatis 不是零配置,有些还是有xml的配置文件在里面的。
注解是Spring的一个构建的一个重要手段,减少写配置文件,下面解释一下一些要用到的注解:
@Configuration 作用于类上面,声明当前类是一个配置类(相当于一个Spring的xml文件)
@ComponentScan(“xxx”) 作用于类上面,自动扫描xxx包名下所有使用@Service、@Component、@Repository和@Controller的类,并注册为Bean
@Bean 作用与类和方法上,相当于Spring配置文件bean节点
@EnableWebMvc 作用于类,开启一些默认配置,如一些ViewResolver或者MessageConverter
@RequestMapping 作用于类、方法,配置URL和方法之间的映射
@RequestBody 作用于参数前,允许request的参数在request体中,而不是在直接链接在地址后面
@ResponseBody 作用于返回值、方法上,支持将返回值放在response体中,而不是返回一个页面。
@RequestParam 作用于参数前,将form的对应name值映射到当前参数中。
从一开始。
先搭建一个 Spring + Spring MVC 的web 项目
创建项目。
然后 点击 Finish 完成 创建项目。
这里开始配置我们的pom.xml文件:
4.0.0
com.oukele.ssm
MyDemo
1.0-SNAPSHOT
war
MyDemo Maven Webapp
http://www.example.com
UTF-8
1.8
1.8
org.springframework
spring-context
5.1.3.RELEASE
org.springframework
spring-core
5.1.3.RELEASE
org.springframework
spring-beans
5.1.3.RELEASE
org.springframework
spring-web
5.1.3.RELEASE
org.springframework
spring-webmvc
5.1.3.RELEASE
javax.servlet
javax.servlet-api
4.0.1
provided
javax.servlet
jstl
1.2
View Code
导入静态资源(jsp 页面 ........)。
在WEB-INF中,直接粘贴boostrap的标准资源,并新建一个views文件夹,将index.jsp拉进去,将自己写的Login.jsp(想要示例的登陆页面的话在本文的最下面有个github地址可以去下载)复制进去,效果如下(顺便删了web.xml):
目录结构如下:
在 main 目录 下 新建 java 文件夹 (注意 java 文件夹 的颜色哦 )
在 java 文件夹 新建几个包 比如 --> com --> oukele --> config (先这样吧。)
开始配置 SpringWebConfig类 (类似 spring-web.xml):
新建一个SpringWebConfig 类,实现 WebMvcConfigurer接口,并配置一些必要的方法。
packagecom.oukele.config;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.ComponentScan;importorg.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.*;importorg.springframework.web.servlet.view.InternalResourceViewResolver;importorg.springframework.web.servlet.view.JstlView;
@Configuration//声明当前类是一个配置类 类似于 ( spring-web.xml )
@EnableWebMvc//若无此注解 WebMvcConfigurer 接口 将无效
@ComponentScan("com.oukele")//自动扫描spring注解 比如@Service、@Component、@Repository和@Controller的类,并注册为Bean
public class SpringWebConfig implementsWebMvcConfigurer {//添加一个ViewResolver 解析 view
@Bean//相当于Spring配置文件bean节点
publicInternalResourceViewResolver getViewResolver() {
InternalResourceViewResolver viewResolver= newInternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
viewResolver.setViewClass(JstlView.class);
viewResolver.setExposeContextBeansAsAttributes(true);returnviewResolver;
}//注册静态资源,比如(css,js,.....)
@Overridepublic voidaddResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/**").addResourceLocations("/WEB-INF/css/");
registry.addResourceHandler("/js/**").addResourceLocations("/WEB-INF/js/");
registry.addResourceHandler("/fonts/**").addResourceLocations("/WEB-INF/fonts/");
}//根目录直接跳转到登录页面 Login.jsp
@Overridepublic voidaddViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("Login");
}
}
与xml配置文件 对比:
注意 @ComponentScan("com.oukele")这样写,扫描oukele 目录所有使用spring注解的类,这里我有点粗心大意了。^_^ 有点小尴尬了。
配置WebInit类 ( 相当于 web.xml 文件 ):
新建一个WebInit类 实现WebApplicationIntializer接口实现方法,方法的内容如:
packagecom.oukele.config;importorg.springframework.web.WebApplicationInitializer;importorg.springframework.web.context.support.AnnotationConfigWebApplicationContext;importorg.springframework.web.servlet.DispatcherServlet;importjavax.servlet.ServletContext;importjavax.servlet.ServletException;importjavax.servlet.ServletRegistration;public class WebInit implementsWebApplicationInitializer {
@Overridepublic void onStartup(ServletContext servletContext) throwsServletException {
AnnotationConfigWebApplicationContext ctx= newAnnotationConfigWebApplicationContext();
ctx.register(SpringWebConfig.class);//注册springWebConfig类
ctx.setServletContext(servletContext);
ServletRegistration.Dynamic dynamic=servletContext.addServlet("dispatcher",new DispatcherServlet(ctx));//将 配置类 添加到DispatcherServlet上下文中
dynamic.addMapping("/");
dynamic.setLoadOnStartup(1);
}
}
与 web.xml 文件 对比:
添加Controller:
新建一个LoginController类
在 oukele 这层包 下 再新建 一个 web 包出来 将 LoginController类放到里面去。
新建一个LoginController 类
packagecom.oukele.web;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestParam;
@Controllerpublic classLoginController {
@RequestMapping("/login")public String login(@RequestParam("username") String username, @RequestParam("pwd") String pwd) {
String forword= null;if (username.equals("oukele") && pwd.equals("oukele")) {
forword= "index";//登录成功跳转到index.jsp
} else{
System.out.println("no such user");
forword= "Login";//登录失败跳转到Login.jsp继续登录操作
}returnforword;
}
}
到这里 我们试试能否启动这个web项目吧。
添加到Tomcat 运行:
这里 默认显示的就是登陆页面。
运行结果:
开始整合Mybatis.
重新配置一下pom.xml文件
4.0.0
com.oukele.ssm
MyDemo
1.0-SNAPSHOT
war
MyDemo Maven Webapp
http://www.example.com
UTF-8
1.8
1.8
org.springframework
spring-context
5.1.3.RELEASE
org.springframework
spring-core
5.1.3.RELEASE
org.springframework
spring-beans
5.1.3.RELEASE
org.springframework
spring-web
5.1.3.RELEASE
org.springframework
spring-jdbc
5.1.3.RELEASE
org.springframework
spring-test
5.1.3.RELEASE
test
org.springframework
spring-webmvc
5.1.3.RELEASE
org.mybatis
mybatis
3.4.6
org.mybatis
mybatis-spring
1.3.2
org.mariadb.jdbc
mariadb-java-client
2.3.0
com.mchange
c3p0
0.9.5.2
javax.servlet
javax.servlet-api
4.0.1
provided
javax.servlet
jstl
1.2
junit
junit
4.12
test
View Code
在oukele 这层包下 新建 entity 、dao 包
在entity包新建一个Student类
packagecom.oukele.entity;public classStudent {//学号
privateString number;//姓名
privateString name;//性别
privateString sex;//年龄
private intage;//地址
privateString address;publicString getNumber() {returnnumber;
}public voidsetNumber(String number) {this.number =number;
}publicString getName() {returnname;
}public voidsetName(String name) {this.name =name;
}publicString getSex() {returnsex;
}public voidsetSex(String sex) {this.sex =sex;
}public intgetAge() {returnage;
}public void setAge(intage) {this.age =age;
}publicString getAddress() {returnaddress;
}public voidsetAddress(String address) {this.address =address;
}
@OverridepublicString toString() {return "Student{" +
"number='" + number + '\'' +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
", address='" + address + '\'' +
'}';
}
}
View Code
在dao包新建一个StudentMapper接口
packagecom.oukele.dao;importcom.oukele.entity.Student;importorg.apache.ibatis.annotations.Param;importorg.apache.ibatis.annotations.Select;public interfaceStudentMapper {//使用xml配置文件
Student getUserById(String number);//不使用配置文件使用注解
@Select("Select * from student where number = #{number}")
Student getUserByIdForAnnotation(String number);
@Select("Select * from student where name = #{student.name} and age = #{student.age}")
Student checkUser(@Param("student") Student student);
}
在main 目录下 新建一个resources 的文件夹。(注意看 resources文件夹的图标)
在resources中新建一个 mybatis-config.xml 文件
在 resources中新建一个mapper文件夹,此文件夹中新建一个StudentMapper.xml
select * from student where number =#{number}
开始配置SpringDaoConfig类。
在config包新建SpringDaoConfig类
packagecom.oukele.config;importcom.mchange.v2.c3p0.ComboPooledDataSource;importorg.mybatis.spring.SqlSessionFactoryBean;importorg.mybatis.spring.mapper.MapperScannerConfigurer;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.core.io.ClassPathResource;importorg.springframework.core.io.Resource;importjavax.sql.DataSource;importjava.beans.PropertyVetoException;
@Configuration//声明当前类是一个配置类
public classSpringDaoConfig {
@Beanpublic DataSource dataSource() throwsPropertyVetoException {
ComboPooledDataSource dataSource= newComboPooledDataSource();
dataSource.setJdbcUrl("jdbc:mariadb://localhost:3306/test");
dataSource.setDriverClass("org.mariadb.jdbc.Driver");
dataSource.setUser("oukele");
dataSource.setPassword("oukele");returndataSource;
}/*@Bean(name = "sqlSessionFactory") 如果不写就默认方法的名字*/@Bean("sqlSessionFactory")public SqlSessionFactoryBean sqlSessionFactory() throwsPropertyVetoException {
SqlSessionFactoryBean sqlSessionFactory= newSqlSessionFactoryBean();
ClassPathResource resource= new ClassPathResource("mapper/StudentMapper.xml");
sqlSessionFactory.setTypeAliasesPackage("com.oukele.entity");
sqlSessionFactory.setMapperLocations(newResource[]{resource});
sqlSessionFactory.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
sqlSessionFactory.setDataSource(this.dataSource());returnsqlSessionFactory;
}
@BeanpublicMapperScannerConfigurer getMapperScannerConfigurer() {
MapperScannerConfigurer configurer= newMapperScannerConfigurer();
configurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
configurer.setBasePackage("com.oukele.dao");returnconfigurer;
}
}
与xml文件对比:
到这里基本完成了ssm配置,我们来测试一下是否能使用。
在main包新建一个test文件夹(注意test文件夹的颜色),在test文件夹 中: --> com --> oukele --> StudentTest测试类
StudentTest类:
packagecom.oukele;importcom.oukele.config.SpringDaoConfig;importcom.oukele.dao.StudentMapper;importcom.oukele.entity.Student;importorg.junit.Test;importorg.junit.runner.RunWith;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.test.context.ContextConfiguration;importorg.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes= {SpringDaoConfig.class})public classStudentTest {
@AutowiredprivateStudentMapper studentMapper;
@Testpublic voidgetIdInfo(){
Student student= studentMapper.getUserById("A101");
System.out.println(student);
}
@Testpublic voidgetName(){
Student student= studentMapper.getUserByIdForAnnotation("B211");
System.out.println(student);
}
@Testpublic voidgetNameAndSex(){
Student student= newStudent();
student.setName("小兰");
student.setAge(18);
Student result=studentMapper.checkUser(student);
System.out.println(result);
}
}
View Code
测试结果:
1 Student{number='D331', name='小兰', sex='女', age=18, address='海南某个地方'}2 Student{number='B211', name='小明', sex='男', age=19, address='广西某个地方'}3 Student{number='A101', name='小华', sex='男', age=18, address='广东某个地方'}
我们到Logincontroller去使用。
修改一下 index.jsp页面:
1
2
3
4
主页面5
6
7
Hello World!
8 欢迎登录,${student.name} !!!!9
10
View Code
运行结果:
测试数据:
create tablestudent(number varchar(10) not null,
namevarchar(10) not null,
sexvarchar(4) not null,
ageint,
addressvarchar(100)
)default charset =utf8;insert into student values("A101","小华","男",18,"广东某个地方"),
("B211","小明","男",19,"广西某个地方"),
("C111","小花","女",17,"珠海某个地方"),
("D331","小兰","女",18,"海南某个地方")