一、Spring开发步骤
1、导入maven座标
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
2、在web.xml文件配置前端控制器(DispatcherServlet)
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispathcerServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<paaram-value>classpath:springmvc.xml</paaram-value>
</init-param>
</servlet>
<servletd-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servletd-mapping>
3、开发控制器(Handler)
@Controller
public class UserController{
@RequestMapping("/save")
public String save(){
....
return "success.jsp"
}
}
4、添加springmvc.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<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:component-scan base-package="com.itheima"></context:component-scan>
</beans>
二、Springmvc执行流程
前端控制器(DispatcherServlet)
- 接收用户请求,以及做出响应
- 它负责调用其他组件处理用户的请求,控制整个流程的执行,想当于一个中央处理器
- 它降低了组件之间的耦合行,利于组件之间的扩展
处理器映射器(HandlerMapping)
- 根据用户请求的 URL 路径,通过注解或者 XML 配置,寻找匹配的 Handler 即处理器
处理器适配器(HandlerAdapter)
- 根据映射器找到的处理器(Handler)信息,按照特定规则执行相关的 Handler (常称为 Controller)
处理器(Hander)
- 这就是开发中要编写的具体业务逻辑控制器,执行相关的请求处理逻辑,并且返回相应的数据和视图信息,然后封装到 ModeAndView 对象中
视图解析器(View resolver)
- 通过ModelAndView 对象中的 View 信息将逻辑视图名解析成物理视图名,即具体的页面地址,然后再生成 View 视图对象,最后对 View 进行渲染处理结果通过页面展示给用户
视图(View)
- 本身是一个接口,实现类支持不同 View 类型 (JSP、FreeMarker、Excel 等)
三、SpringMVC常规配置
3.1 Controller加载控制
为了防止重复扫描Controller,可以在spring.mvc中做如下配置
<context:component-scan base-package="com.itheima">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:include-filter>
</context:component-scan>
除此之外也可以只扫描controller包
<context:component-scan base-package="com.itheima.controller">
</context:component-scan>
3.2 静态资源放行
默认情况下访问静态资源时也会被前端控制器拦截,出现404错误。可做如下配置:
方式一:
<mvc:resources mapping="/img/**" location="/img/"></mvc:resources>
<mvc:resources mapping="/js/**" location="/js/"></mvc:resources>
方式二:
<mvc:default-servlet-handler></mvc:default-servlet-handler>
3.3 中文乱码处理
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
四、传参
2.1 普通类型
@RequestMapping("/requestParameter1")
public String requestParameter1(@RequestParam( "username") String name, int age){
System.out.println("name:"+name);
System.out.println("age:"+age);
return "success";
}
请求地址:
http://localhost/requestParameter1?username=zhangsan&age=20
2.2 Pojo类型
2.2.1 属性均为普通类型
实体类:
public class User implements java.io.Serializable {
private String name;
private int age;
getXxx/setXxx略
}
控制器:
@RequestMapping("/requestParameter2")
public String requestParameter2(User user){
System.out.println(user);
System.out.println(name);
return "success";
}
请求地址:
http://localhost/requestParameter2?name=zhangsan&age=20
2.2.2 属性为引用类型
实体类:
public class Address implements java.io.Serializable{
private String province;
private String city;
getXxx/setXxx略
}
控制器
@RequestMapping("/requestParameter3")
public String requestParameter2(User user){
System.out.println(user);
System.out.println(name);
return "success";
}
请求地址:
http://localhost/requestParameter2?address.province=hubei&address.city=wuhan
2.2.3 属性为集合(集合元素是普通类型)
实体类:
public class User implements java.io.Serializable {
private String name;
private int age;
private List<String> nick; //使用集合作为属性(集合里面存的是普通类型)
getXxx/setXxx略
}
控制器
@RequestMapping("/requestParameter3")
public String requestParameter3(User user){
System.out.println(user);
System.out.println(name);
return "success";
}
请求地址:
http://localhost/requestParameter3?nick=xiaoming&nick=xiaozhang
2.2.4 属性为集合(集合元素为引用类型)
实体类:
public class User implements java.io.Serializable {
private String name;
private int age;
private List<Address> addresses; //使用装有引用类型的集合作为属性
getXxx/setXxx略
}
控制器:
@RequestMapping("/requestParameter4")
public String requestParameter4(User user){
System.out.println(user);
System.out.println(name);
return "success";
}
请求地址:
http://localhost/requestParameter4?address[0].province=jiangsu&address[0].city=nanjing&address[1].province=hubei&address[1].city=wuhan
2.2.5 Map集合
实体类:
public class User implements java.io.Serializable {
private String name;
private int age;
private Map<String,Address> addressMap; //使用map集合作为参数
getXxx/setXxx略
}
控制器:
@RequestMapping("/requestParameter5")
public String requestParameter5(User user){
System.out.println(user);
System.out.println(name);
return "success";
}
请求地址:
http://localhost/requestParameter5?addressMap['home'].province=jiangsu&address['home'].city=nanjing&address['work'].province=hubei&address['work'].city=wuhan
2.3 数组类型、集合类型作为参数
2.3.1 数组类型作为参数
控制器
@RequestMapping("/requestParameter6")
public String requestParameter6(String[] nick){
if(nick!=null){
for (String s : nick) {
System.out.println(s);
}
}
return "success";
}
请求地址:
http://localhost/requestParameter6?nick=zhangsan&nick=lisi
2.3.2 集合类型作为参数
控制器
@RequestMapping("/requestParameter7")
public String requestParameter7(@RequestParam("nick") List<String> nick){
if(nick!=null){
for (String s : nick) {
System.out.println(s);
}
}
return "success";
}
请求地址
http://localhost/requestParameter6?nick=zhangsan&nick=lisi
五、自定义类型转换器
1、开法转换器类
package com.itheima.converter;
import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyDateConverter implements Converter<String, Date> {
String[] patterns = new String[]{"yyyy-MM-dd","yyyy/MM/dd","yyyy年MM月dd日"};
@Override
public Date convert(String s) {
for (String pattern : patterns) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date date = null;
try {
date = sdf.parse(s);
return date;
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
}
2、在springmvc.xml文件中注册自定义转换器
<mvc:annotation-driven conversion-service="conversionServiceFactoryBean"></mvc:annotation-driven>
<!--创建-->
<bean id="conversionServiceFactoryBean" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<!--创建MyDateConverter对象-->
<bean class="com.itheima.converter.MyDateConverter"></bean>
</set>
</property>
</bean>
六、请求映射(@RequestMapping)
@Controller
@RequestMapping("/goods")
public class GoodsController {
@RequestMapping(value="/add",method = {RequestMethod.POST,RequestMethod.GET})
public void add(){
System.out.println("goods add()...");
}
}
@RequestMapping可作用于方法和类之上。如上代码访问路径应为:
http://localhost/goods/add
七、页面跳转
7.1 请求转发
1、配置视图解析器
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
2、使用视图解析器
@RequestMapping("/jump1")
public String jump1(){
return "success";
}
7.2 重定向
@RequestMapping("/jump2")
public String jump2(){
return "redirect:/jsp/success.jsp";
}
配或不配视图解析器都会重定向跳转
7.3 带数据页面跳转
7.3.1 使用Model对象
@RequestMapping("/jump4")
public String jump4(Model model){
Student s = new Student();
s.setName("大宝");
s.setBrithday(new Date());
model.addAttribute("student",s);
return "success";
}
7.3.2 使用ModelAndView对象
@RequestMapping("/jump5")
public ModelAndView jump5(){
Student s = new Student();
s.setName("大宝");
s.setBrithday(new Date());
ModelAndView mv = new ModelAndView();
mv.addObject("student",s); //设置数据
mv.setViewName("success"); //设置视图的逻辑名
return mv;
}
也可以使用下面方法
@RequestMapping("/jump5")
public ModelAndView jump5(ModelAndView mv ){
Student s = new Student();
s.setName("大宝");
s.setBrithday(new Date());
mv.addObject("student",s); //设置数据
mv.setViewName("success"); //设置视图的逻辑名
return mv;
}
八、响应JSON数据
1 、pom.xml文件中添加jackson座标
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.9</version>
</dependency>
2、方法前添加@ResponseBody注解
@RequestMapping("/json5")
@ResponseBody
public List<Student> json5(){
Student s = new Student();
s.setName("大宝");
s.setBrithday(new Date());
Student s1 = new Student();
s1.setName("小宝");
s1.setBrithday(new Date());
List<Student> list = new ArrayList<>();
list.add(s);
list.add(s1);
return list;
}
3、springmvc.xml文件开启注解驱动
<mvc:annotation-driven></mvc:annotation-driven>