Spring MVC
1、回顾Servlet
- 添加Maven依赖
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/jsp-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
- 创建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 {
String method = req.getParameter("method");
if (method.equals("add")){
req.getSession().setAttribute("msg","执行了add方法");
}
if (method.equals("delete")){
req.getSession().setAttribute("msg","执行了delete方法");
}
req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}
}
- 注册servlet
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.jerry.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
- 测试
2、使用注解开发Spring MVC
2.1、配置web.xml,一般配置好的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>
<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>
<!--所有请求都会被SpringMVC拦截-->
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
2.2、编写参数配置文件 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
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="controller"/>
<!--让SpringMVC不处理静态资源-->
<mvc:default-servlet-handler />
<!--自动完成实例注入-->
<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>
2.3、根据需要编写接口文件
package controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
@RequestMapping("/hello")
public String hello(Model model){
model.addAttribute("msg","SpringMvc,hello,test-annotation");
return "hello";
}
}
2.4、编写相应的jsp页面。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>annotation</title>
</head>
<body>
${msg}
</body>
</html>
3、restFul 风格
原本的URL格式 localhost://8080/test?a=1&b=2
restFul 的 URL localhost://8080/test/a/b
总的来说,restFul 风格使得数据更加安全,更加便捷
4、结果跳转方式(转发和重定向)
4.1、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>
4.2、ServletAPI
不需要试图解析器
1.通过HttpServletResponse进行输出
2.通过HttpServletResponse实现重定向
3.通过HttpServletResponse实现转发
通过SpringMVC来实现转发和重定向——无需视图解析器
@Controller
public class ResultSpringMVC {
@RequestMapping("/t1")
public String test1(Model model){
model.addAttribute("msg","无解析器的转发");
return "/WEB-INF/jsp/test.jsp";
}
@RequestMapping("/t2")
public String test2(Model model){
model.addAttribute("msg","无解析器的转发二");
return "forward:/WEB-INF/jsp/test.jsp";
}
@RequestMapping("/t3")
public String test3(Model model){
model.addAttribute("msg","无解析器的重定向");
return "redirect:/index.jsp";
}
}
5、SpringMVC数据处理
5.1、数据提交处理
5.1.1、提交的域名称和处理方法的参数名一致
- 访问地址为:localhost:8080/user/test1?name=jerry
@GetMapping("/test1")
public String test1(String name,Model model){
//System.out.println("前端接受的数据为:"+name);
model.addAttribute("msg","test1的数据是:"+name);
return "test";
}
5.1.2、提交的域名称和处理方法的参数名不一致
- 访问地址:localhost:8080/user/test2?username=jerry
需要在字段前面加上@RequestParam(“要传入的参数名”)
@GetMapping("/test2")
public String test2(@RequestParam("username") String name, Model model){
System.out.println("前端接受的数据为:"+name);
model.addAttribute("msg","test2的数据是:"+name);
return "test";
}
5.1.3 、前端接受的是一个对象(Object)
- 访问地址: localhost:8080/user/test3?name=xiao&id=1&age=1
- 先创建对象的实体类(此处注解使用了Lombok)
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private int age;
}
- 创建对应的请求格式(此处是get方式)
@GetMapping("/test3")
public String testObj(User user){
System.out.println(user);
return "test";
}
5.2、数据显示在前端
5.2.1、通过ModelAndView
public class ControllerTest2 implements Controller {
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView mv= new ModelAndView();
mv.addObject("msg","前端显示数据测试");
mv.setViewName("test");
return mv;
}
}
5.2.2、通过ModelMap
@RequestMapping("/test4")
public String testModelMap(@RequestParam("name") String name, ModelMap modelmap){
//封装将要显示的数据,相当于req.setAttribute("msg",name)
modelmap.addAttribute("msg",name);//msg是前端需要获取的字段名(${msg})
System.out.println(name);
return "test";
}
5.2.3、通过Model
@GetMapping("/test2")
public String test2(@RequestParam("username") String name, Model model){
System.out.println("前端接受的数据为:"+name);
model.addAttribute("msg","test2的数据是:"+name);
return "test";
}
- 注:model一般就可以满足日常的使用
6、解决乱码问题
6.1、自己尝试解决,但是不能解决某些情况的乱码问题
- 自定义过滤器filter
package filter;
import javax.servlet.*;
import java.io.IOException;
public class EncodingFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
chain.doFilter(request,response);
}
}
- 在web.xml中配置
<!--配置Encoding过滤器-->
<filter>
<filter-name>encoding</filter-name>
<filter-class>filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
6.2、由于以上方式不能解决所有的乱码问题,所以采用以下SpringMVC提供的解决办法
- 直接在web.xml 中配置
<!--使用SpringMVC提供的乱码过滤器,解决乱码问题-->
<filter>
<filter-name>enconding</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>enconding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>