回顾MVC
- 模型(service、dao)、视图(jsp)、控制器(Servlet)
- 将业务逻辑分离
Servlet-Maven依赖
<!-- 依赖 -->
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.60</version>
</dependency>
</dependencies>
Spring是基于Java实现的web框架
特点:
- 轻量级 简单易学
- 不需要很多依赖
- 基于请求响应
- 兼容Spring 我们可以将SpringMVC需要的bean 注册到springIOC容器的
- 约定优于配置
- 功能强大 RESULT风格的url 数据验证 格式化 本地化 主题
基于请求分发设计DispatcherServlet(也是Servlet) 将请求 doService来接受请求 对于请求进行调度
快速搭建SpringMVC环境
- 更改web.xml配置 注册DispatcherServlet
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置关联文件 servlet.xml -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
- 创建springmvc-servlet.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"
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/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
<context:component-scan base-package="com.jian"></context:component-scan>
<!-- springmvc不处理静态资源 -->
<mvc:default-servlet-handler></mvc:default-servlet-handler>
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="defaultCharset" value="utf-8"></property>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"></property>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
public class HelloController implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
//ModelAndView 模型和视图
ModelAndView modelAndView = new ModelAndView();
//封装对象、放在ModelAndView模型内
modelAndView.addObject("name","李子建");
//封装要跳转的视图放在ModelAndView中
modelAndView.setViewName("hello");//:Web-inf/jsp/hello.jsp
return modelAndView;
}
}
SpringMVC的执行原理
- DispatchServlet是SpringMVC的控制中心 用于接受和拦截请求
- http://localhost:8080/hello 表示访问hello的控制器
- HandlerMapping 根据url来解析需要使用哪个控制器
- handlerExcution 将解析后的结果交给DispatchServlet
- HandlerAdapt 处理器适配器 适配器有很多种是按照规则执行Handler
- 执行Handler 将具体的信息返回给HandlerAdapt 如ModelAndView
- HandlerAdapt 将返回值传递给DispatchServlet
- DispatchServlet调用视图解析器 来解析返回给用户
注解开发
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>encoding</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>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
springmvc.xml
<?x ml 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"
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/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
<context:component-scan base-package="com.jian"></context:component-scan>
<!-- springmvc不处理静态资源 -->
<mvc:default-servlet-handler></mvc:default-servlet-handler>
<mvc:annotation-driven></mvc:annotation-driven>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
@Controller
//被指个注释的类 的 方法只要有返回值是字符串的并且有对应的页面跳转 就会被视图器解析
public class HelloAnnotation {
@RequestMapping("/hello")
public String hello(Model model){
model.addAttribute("name","李子建");
return "hello";//返回视图的名字
}
}
RestFul风格
// @RequestMapping(value = "/add/{a}",method = RequestMethod.GET)
@GetMapping("/add/{a}")
public String test(@PathVariable int a,Model model){
System.out.println(a);
return "hello";
}
@GetMapping("/test1")
public String test1(HttpServletRequest request, HttpServletResponse response){
// return "redirect:/add/10";
return "forward:/add/10";//配置了视图解析器默认就是转发不用写forward
}
@GetMapping("/test2")
public String test2(String name, @RequestParam("userage") int age){
System.out.println(name);
System.out.println(age);
return "hello";
}
/**
* Model是精简版(大部分情况直接可以用它)
* Modelmap继承了Linkedhashmap
*
*/
@RestController
public class MyTest {
@GetMapping("/test1")
@ResponseBody
public String test1( Model model) throws JsonProcessingException {
model.addAttribute("name","李子建");
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS,false);
User user = new User("李子建", 18,new Date());
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
String string = objectMapper.writeValueAsString(user);
return string;
}
}
@GetMapping("/test2")
public String test2(){
ArrayList<User> users = new ArrayList<>();
users.add(new User("李子建",18,new Date()));
users.add(new User("李干",18,new Date()));
String o = JSON.toJSONString(users);
return o;
}