回顾Servlet
servlet
package servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.获取前端参数
String method = req.getParameter("method");
if (method.equals("add")) {
req.getSession().setAttribute("msg", "执行了add方法");
}
if (method.equals("delete")) {
req.getSession().setAttribute("msg", "执行了delete方法");
}
//2.调用业务层
//3.试图转发或者重定向
req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
pom依赖
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.9.RELEASE</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>
</dependencies>
jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${msg}
</body>
</html>
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>hello</servlet-name>
<servlet-class>servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
MVC框架要做哪些事情
- 将url映射到java类或java类的方法
- 封装用户提交的数据
- 处理请求–调用相关的业务处理–封装响应数据
- 将响应的数据进行渲染到.jsp/.html等表示层数据
RestFul风格
RESTFUL特点包括:
1、每一个URI代表1种资源;
2、客户端使用GET、POST、PUT、DELETE4个表示操作方式的动词对服务端资源进行操作:GET用来获取资源,POST用来新建资源(也可以用于更新资源),PUT用来更新资源,DELETE用来删除资源;
3、通过操作资源的表现形式来操作资源;
4、资源的表现形式是XML或者HTML;
5、客户端与服务端之间的交互在请求之间是无状态的,从客户端到服务端的每个请求都必须包含理解请求所必需的信息。
传统方式操作资源
通过不同的参数来实现不同的效果!方法单一,post 和 get
http://127.0.0.1/item/queryItem.action?id=1 查询,GET
http://127.0.0.1/item/saveItem.action 新增,POST
http://127.0.0.1/item/updateItem.action 更新,POST
http://127.0.0.1/item/deleteItem.action?id=1 删除,GET或POST
使用RESTful操作资源
可以通过不同的请求方式来实现不同的效果!如下:请求地址一样,但是功能可以不同!
http://127.0.0.1/item/1 查询,GET
http://127.0.0.1/item 新增,POST
http://127.0.0.1/item 更新,PUT
http://127.0.0.1/item/1 删除,DELETE
package controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* @author VV
* @date 2021/9/8 15:03
*/
@Controller
public class RestFulController {
@RequestMapping(value = "/item/{a}/{b}", method = RequestMethod.GET)
public String test1(@PathVariable int a, @PathVariable String b, Model model) {
String res = a + b;
model.addAttribute("msg", "结果1为" + res);
return "test";
}
@RequestMapping(value = "/item/{a}/{b}", method = RequestMethod.POST)
public String test2(@PathVariable int a, @PathVariable String b, Model model) {
String res = a + b;
model.addAttribute("msg", "结果2为" + res);
return "test";
}
}
结果跳转方式
ModelAndView
设置ModelAndView对象,根据view的名称,和视图解析器跳到指定的页面
页面:视图解析器前缀 + viewName + 视图解析器后缀
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 后缀 -->
<property name="suffix" value=".jsp" />
</bean>
Controller类
public class ControllerTest1 implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
//返回一个模型视图对象
ModelAndView mv = new ModelAndView();
mv.addObject("msg","ControllerTest1");
mv.setViewName("test");
return mv;
}
}
ServletAPI
通过设置SevletAPI,不需要视图解析器
- 通过HttpServletResponse进行输出
- 通过HttpServletResponse实现重定向
- 通过HttpServletResponse实现转发
@Controller
public class ResultController {
@RequestMapping("/result/t1")
public void test1(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.getWriter().println("Hello test1!");
}
@RequestMapping("/result/t2")
public void test2(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.sendRedirect("/index.jsp");
}
@RequestMapping("/result/t3")
public void test3(HttpServletRequest request, HttpServletResponse response) throws Exception {
//转发
request.setAttribute("msg","Hello test3!");
request.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(request,response);
}
}
SpringMVC
通过SpringMVC来实现转发和重定向-无需视图解析器
@Controller
public class ResultController {
@RequestMapping("/rsm/t1")
public String test1(){
//转发:可以搭配视图解析器
return "/index.jsp";
}
@RequestMapping("/rsm/t2")
public String test2(){
//转发二:无需视图解析器
return "forward:/index.jsp";
}
@RequestMapping("/rsm/t3")
public String test3(){
//重定向:无需视图解析器
return "redirect:/index.jsp";
}
}
数据处理
处理提交数据
1,提交的域名称和处理方法的参数名一致
提交数据:http://localhost:8080/SpringMVC_04_controller_war_exploded/hello?name=vv
处理方法:
@Controller
public class Controllertest4 {
@RequestMapping("/hello")
public String hello(String name){
System.out.println(name);
return "test";
}
}
2,提交的域名称和处理方法的参数名不一致
提交数据:http://localhost:8080/SpringMVC_04_controller_war_exploded/hello?username=vv
处理方法:
@Controller
public class Controllertest4 {
@RequestMapping("/hello")
public String hello(@RequestParam("username") String name){
System.out.println(name);
return "test";
}
}
3、提交的是一个对象
要求提交的表单域和对象的属性名一致 , 参数使用对象即可
1、实体类
public class User {
private int id;
private String name;
private int age;
//构造
//get/set
//tostring()
}
2、提交数据 : http://localhost:8080/mvc04/user?name=vv&id=1&age=15
3、处理方法 :
@RequestMapping("/user")
public String user(User user){
System.out.println(user);
return "hello";
}
后台输出 : User { id=1, name=‘vv’, age=15 }
说明:如果使用对象的话,前端传递的参数名和对象的参数名必须一致,否则就是null。
数据显示到前端
第一种 : 通过ModelAndView
我们前面一直都是如此 . 就不过多解释
public class ControllerTest1 implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
//返回一个模型视图对象
ModelAndView mv = new ModelAndView();
mv.addObject("msg","ControllerTest1");
mv.setViewName("test");
return mv;
}
}
第二种 : 通过ModelMap
ModelMap
@RequestMapping("/hello")
public String hello(@RequestParam("username") String name, ModelMap model){
//封装要显示到视图中的数据
//相当于req.setAttribute("name",name);
model.addAttribute("name",name);
System.out.println(name);
return "hello";
}
第三种 : 通过Model
Model
@RequestMapping("/ct2/hello")
public String hello(@RequestParam("username") String name, Model model){
//封装要显示到视图中的数据
//相当于req.setAttribute("name",name);
model.addAttribute("msg",name);
System.out.println(name);
return "test";
}
对比
Model 只有寥寥几个方法只适合用于储存数据,简化了新手对于Model对象的操作和理解;
ModelMap 继承了 LinkedMap ,除了实现了自身的一些方法,同样的继承 LinkedMap 的方法和特性;
ModelAndView 可以在储存数据的同时,可以进行设置返回的逻辑视图,进行控制展示层的跳转。
当然更多的以后开发考虑的更多的是性能和优化,就不能单单仅限于此的了解。