1 为什么学Spring MVC
1轻量级 简单易学
2与Spring无缝接合
3 约定大于配置
4基于请求响应的MVC框架
5功能强大 RESTful 数据验证 格式化 本地化 主题等
2体验Spring MVC
1:导入依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>MVC</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>MVC1</module>
</modules>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
</project>
<?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">
<!--Spring自己的Servlet 手动配置 之后自己写的Servlet都由Spring创建-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--关联一个SpringMVC配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
//任何servlet都会被拦截
<url-pattern>/</url-pattern> <!--/*会匹配jsp页面 会进入死循环-->
</servlet-mapping>
</web-app>
<?xml version="1.0" encoding="utf-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--处理器映射器-->
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<!--处理器适配器-->
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
<!--页面访问的Servlet 会寻找下面的类-->
<bean id="/hello" class="com.kuang.controller.HelloController"/>
</beans>
4
package com.kuang.controller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloController implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
//ModelAndView 模型和视图
ModelAndView mv = new ModelAndView();
//封装对象,放在ModelAndView中
mv.addObject("msg","Hello");
//封装要跳转的视图 放在modelAndView中
mv.setViewName("hello"); //WEB-INf/jsp/hello.jsp
return mv;
}
}
2.2 执行流程分析
实现部分全部由Spring处理
1 浏览器输入URL地址 实际上是访问了一个控制器 这里相当于我们自己写的servlet
2 ServletdispacherServlet根据请求 找到Contraoller处理器
3查找到对应的处理器后返回信息给ServletdispacherServlet
4获取了ModelAndView数据后 解析ModelAndView视名字 拼接视图名字 返回给ServletdispacherServlet
5 ServletdispacherServlet 找到对应试图 将数据渲染到视图
我们要做的就是在控制器中写调用dao层的方法
3注解开发Spring MVC
<?xml version="1.0" encoding="utf-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--使下面路径下的类的注解生效-->
<context:component-scan base-package="com.kuang.controller"/>
<!--让springmvc不处理静态资源 比如js html css -->
<mvc:default-servlet-handler/>
<!--支持MVC注解生效 并自动注入之前的俩个映射器-->
<mvc:annotation-driven/>
<!--视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
web.xml不变
package com.kuang.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
//下面俩个注解 共同完成了下面这句话
//<bean id="/hello class="com.kuang.controller.HelloController"/>
//相当于 < class="com.kuang.controller.HelloController"/>
@Controller
public class HelloController {
//@ResponseBody 跳过视图解析器 直接返回字符串
@RequestMapping("/hello")//这个hello相当于servlet名字 <bean id="/hello">
public String redirect(Model model){
model.addAttribute("msg","李嘉伟");
return "hello";//返回值代表跳转到哪个jsp页面(如果返回值是String 并且有该jsp 就会被自动视图解析)
}
}
4Restful风格
传统URL传参:location:8080/method?add=1
RestFul风格 :location:8080/method/1/2/3
传统法式代码和url
对应的url地址http://localhost:8080/jiawei?a=1&b=2
@Controller
public class MyController {
@RequestMapping("/jiawei")
public String sayhello(int a, int b ,Model model){//ab 直接从网页传进来
int res = a+b;
model.addAttribute("msg","res");
return "hello";
}
}
restful风格代码
对应的url地址http://localhost:8080/jiawei/1/5
@Controller
public class MyController {
@RequestMapping("/jiawei/{a}/{b}")
public String sayhello(@PathVariable int a, @PathVariable int b , Model model){
int res = a+b;
model.addAttribute("msg",res);
return "hello";
}
}
限定请求方式
指定请求方式后如果不是该类型的请求会报405错误 也可以用另一种方式 就是把注解换了
还有:GetMapping
PostMapping
putmapping
deletemapping
patchmapping 等等
下面说明同一个url为什么可以处理俩个方法
RestFul风格 的好处
隐藏了方法名字
高效 因为支持缓存
简洁
5结果跳转方式
如果配置了视图解析器
直接返回一个字符串默认方式就是 请求转发方式跳转
重定向不需要视图解析器
如果要重定向 return :“全路径”;
package com.kuang.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
@Controller
public class MyController {
@GetMapping ("/jiawei")
public String sayhello( ){
return "redirect:/index.jsp";
}
}
如果没有视图解析器
重定向还是和上面一样
请求转发写全路径即可
数据传输问题
1
url: http://localhost:8080/jiawei?name=hello
@Controller
public class MyController {
@RequestMapping("/jiawei")
public String sayhello( String name){
System.out.println(name);
return "hello";
}
}
如果地址传递username 那么程序就拿不到
2
rul: http://localhost:8080/jiawei?username=hello
@Controller
public class MyController {
@RequestMapping("/jiawei")
public String sayhello( @RequestParam("username") String name){
System.out.println( name);
return "hello";
}
}
这种方式将前端的username参数和name对应 这种写法还能标记 这个参数时前端传过来的 所以为了 看的清晰 不管名字是否一致 最好都写上
3
url :rul: http://localhost:8080/jiawei?name=zhangsan&age=16&address=beijing
一次传入多个参数 情况 代码写一个bean类即可 他会自动匹配User类中的字段 匹配不到的为null
package com.kuang.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
@Controller
public class MyController {
@RequestMapping("/jiawei")
public String sayhello( User user){
System.out.println( name);
return "hello";
}
}
乱码问题
加一个过滤器
<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>
JSON
前后端分离时代:
后端提供接口 ,提供数据
前端独立部署 ,负责渲染后端数据:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript">
var user ={
name:"李嘉伟",
age:3,
sex:"男"
}
//将js对象转换成JSON对象
var json = JSON.stringify(user);
JSON.parse()
console.log(json)
console.log(user)
</script>
</head>
</html>
JackJson
整合SSml
导入依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.lijiawei</groupId>
<artifactId>ssmbuild</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</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.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
目录结构
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-e1kqQQcq-1583221281421)(C:\Users\李嘉伟\AppData\Roaming\Typora\typora-user-images\image-20200225171817509.png)]
applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="classpath:spring-mvc.xml"/>
<import resource="classpath:spring-dao.xml"/>
<import resource="classpath:spring-service.xml"/>
</beans>
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="com.kuang.pojo"/>
</typeAliases>
<mappers>
<mapper class="com.kuang.dao.BookMapper"/>
</mappers>
</configuration>
spring-dao.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 https://www.springframework.org/schema/context/spring-context.xsd">
<!-- spring 读取url的配置文件-->
<context:property-placeholder location="classpath:url.properties"/>
<!-- 连接池-->
<bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${c3p0.driver}"/>
<property name="jdbcUrl" value="${c3p0.url}"/>
<property name="user" value="${c3p0.username}"/>
<property name="password" value="${c3p0.password}"/>
<property name="maxPoolSize" value="10"/>
<property name="minPoolSize" value="3"/>
<property name="autoCommitOnClose" value="false"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="com.kuang.dao"/>
</bean>
<bean id="TransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="datasource"/>
</bean>
</beans>
spring-mvc.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:mvc="http://www.springframework.org/schema/mvc"
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/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
<context:component-scan base-package="com.kuang.controller"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
spring-service.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 https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.kuang.service"/>
<bean id="BookServiceImpl" class="com.kuang.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
</beans>
url.properties
c3p0.driver=com.mysql.jdbc.Driver
c3p0.url = jdbc:mysql://localhost:3306/test?useSSL=true&useUnicode=true&characterEncoding=UTF-8
c3p0.username=root
c3p0.password=123456
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:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<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>
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
contaoller
package com.kuang.controller;
import com.kuang.pojo.Books;
import com.kuang.service.Bookservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@Controller
public class BookController {
@Autowired
@Qualifier("BookServiceImpl")
private Bookservice bookservice;
//查询全部书籍
@RequestMapping("/All")
public String All(Model model){
List<Books> books = bookservice.queryAllBook();
model.addAttribute("msg",books);
return "book";
}
}
Bookmapper
package com.kuang.dao;
import com.kuang.pojo.Books;
import java.util.List;
public interface BookMapper {
int addBook(Books books);
int deleteBook(int id);
int updateBook(int id , Books books);
Books queryBook(int id);
List<Books> queryAllBook();
}
BookMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kuang.dao.BookMapper">
<insert id="addBook" parameterType="Books">
insert into test.books (bookName, bookCounts, detail)
values (#{bookName},#{bookCounts},#{detail});
</insert>
<delete id="deleteBook" parameterType="int">
delete from test.books where bookID = #{id}
</delete>
<update id="updateBook" parameterType="Books">
update test.books set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail} where id=#{id}
</update>
<select id="queryBook" resultType="Books">
select * from test.books where id= #{id};
</select>
<select id="queryAllBook" resultType="Books">
select * from test.books;
</select>
</mapper>
Books实体类
package com.kuang.pojo;
public class Books {
private int bookID;
private String bookName;
private String bookCounts;
private String detail;
@Override
public String toString() {
return "Books{" +
"bookID=" + bookID +
", bookName='" + bookName + '\'' +
", bookCounts='" + bookCounts + '\'' +
", detail='" + detail + '\'' +
'}';
}
public Books() {
}
public Books(int bookID, String bookName, String bookCounts, String detail) {
this.bookID = bookID;
this.bookName = bookName;
this.bookCounts = bookCounts;
this.detail = detail;
}
public int getBookID() {
return bookID;
}
public void setBookID(int bookID) {
this.bookID = bookID;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getBookCounts() {
return bookCounts;
}
public void setBookCounts(String bookCounts) {
this.bookCounts = bookCounts;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
}
service
package com.kuang.service;
import com.kuang.dao.BookMapper;
import com.kuang.pojo.Books;
import java.util.List;
public interface Bookservice {
public int addBook(Books books) ;
public int deleteBook(int id);
public int updateBook(int id, Books books) ;
public Books queryBook(int id) ;
public List<Books> queryAllBook() ;
}
serviceimpl
package com.kuang.service;
import com.kuang.dao.BookMapper;
import com.kuang.pojo.Books;
import java.util.List;
public class BookServiceImpl implements Bookservice {
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
public int addBook(Books books) {
return bookMapper.addBook(books);
}
public int deleteBook(int id) {
return bookMapper.deleteBook(id);
}
public int updateBook(int id, Books books) {
return bookMapper.updateBook(id,books);
}
public Books queryBook(int id) {
return bookMapper.queryBook(id);
}
public List<Books> queryAllBook() {
return bookMapper.queryAllBook();
}
}
SSM整合完毕