- 实验目的
掌握SpringMVC的配置(三大件)以及一般开发流程;掌握Spring MVC的常用注解;理解Spring MVC 与Spring的整合方式。
- 实验环境
IDEA2022.2
- 实验内容
(1) 配置applicationContext.xml以及web.xml文件,进行Spring MVC和Spring的相关设置;
(2) 引入SpringMVC 重构实验五的内容。
- 实验步骤
- 导入依赖
<dependencies>
<!--测试类-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--spring的webmvc,包含spring的依赖资源-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!--servlet的api-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<!--jsp的api-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<!--jstl,jsp的一些标签-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
- 配置web.xml
<!--1.注册DispatcherServlet前端控制器--> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--关联一个springMVC配置文件:【servlet-name】-servlet.xml--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-servlet.xml</param-value> </init-param> <!--启动级别-1--> <!--启动顺序,数字越小,启动越早--> <load-on-startup>1</load-on-startup> </servlet> <!--使用springmvc来拦截所有请求--> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--解决中文乱码问题,只有在post提交时会出现乱码问题--> <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>
- 配置spring配置文件springmvc_servlet.xml
<!--1,添加处理器映射器-->
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<!--2.添加处理器适配器-->
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
<!--3.视图解析器-->
<!--后续也可以使用模板解析 Thymelear Freemarker-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="InternalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
- 编写HelloController,实现Controller接口
@Override
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
//ModelAndView模型和视图
ModelAndView mv=new ModelAndView();
//封装对象,放在ModelAndView中。Model
mv.addObject("msg","HelloSpringMVC!");
//封装要跳转的视图,放在ModelAndView中
mv.setViewName("hello");//:/WEB-INF/jsp/hello.jsp
return mv;
}
- 在spring配置文件中配置该Controller实例
<bean id="/hello" class="com.blacktea.HelloController"/>
- 写过滤器,将配置文件选择不过滤,防止加载不到配置文件
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
- 使用@Controller注解
@Controller
@RequestMapping("/hi")
public class HelloController {
@RequestMapping("/hello")
public String hello(Model model) {
//向模型中添加msg的属性,可以在视图渲染层进行渲染
model.addAttribute("msg", "hello,SpringMVC");
//返回的是要跳转的msg属性,回自动拼接
return "hello";
}
}
写jsp文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>${msg}</h1>
</body>
</html>
- RequestMapping定义路径,使用注解开发,使用@RequestMapping来定义接受的路径
@Controller
@RequestMapping("subtract/{a}/{b}")
public String subtract(@PathVariable int a,@PathVariable int b, Model model){
//使用@PathVariable路径变量来传参
int res=a-b;
model.addAttribute("msg",a+"和"+b+"相减得"+res);
return "hello";
}
11、使用restful格式进行传参拼接路径
@RequestMapping("subtract/{a}/{b}")
public String subtract(@PathVariable int a,@PathVariable int b, Model model){
//使用@PathVariable路径变量来传参
int res=a-b;
model.addAttribute("msg",a+"和"+b+"相减得"+res);
return "hello";
}
12、通过ServletAPI进行跳转,通过HttpServletResponse进行输出后端的字符串等信息
@Controller
public class RestulGo {
//1.通过HttpServletResponse进行输出
@RequestMapping("result/test1")
public void test1(HttpServletRequest req, HttpServletResponse res) throws IOException {
//直接打印到前端
res.getWriter().println("hello servletResponse");
}
13、通过HttpServletRequest实现转发
@RequestMapping("/result/test3")
public void test3(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
//转发
req.setAttribute("msg","使用的Request的工具进行转发");
req.getRequestDispatcher("/WEB-INF/jsp/hello.jsp").forward(req,res);
}
14、使用SpringMVC中的跳转,转发
//转发
@RequestMapping("rsm/test1")
public String test1(){
return "test";
}
跳转的Jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>我是测试页面</h1>
</body>
</html>
//也可以省略forward,默认就是转发的方式
//转发也不会更改请求的地址
@RequestMapping("rsm/test2")
public String test2(){
return "forward:/index.jsp";
}
//重定向
//重定向会更改原来的地址
@RequestMapping("rsm/test3")
public String test3(){
return "redirect:/index.jsp";
}
}
15、数据处理,域名参数与方法参数一致
//1.前端传入的参数名称与后端名称一致
@RequestMapping("/test1")
public String test1(String name, Model model){
//1.接收到参数,可以进行数据处理
System.out.println(name);
//2.需要传递给前端的信息
model.addAttribute("msg","接收到的姓名为"+name);
//3.跳转的页面
return "hello";
}
ocalhost:8080/MySpringMVCWOrk_war_exploded/data/test1?name=哈哈哈
16、数据处理,域名参数与方法参数一致
@RequestMapping("/test2")
public String test2(@RequestParam("username")String name,Model model){
//1.接收到参数,可以进行数据处理
System.out.println(name);
//2.需要传递给前端的信息
model.addAttribute("msg","处理后的username为"+name);
//3.跳转的页面
return "hello";
}
localhost:8080/MySpringMVCWOrk_war_exploded/data/test2?username=✌
17、提交一个对象
@RequestMapping("/test3")
public String test3(User user, Model model){
//1.接收到参数,可以进行数据处理
System.out.println(user);
//2.把user对象存在视图模型中
model.addAttribute("user",user);
//3.需要传递给前端的信息
model.addAttribute("msg","信息已存入");
//4.跳转的页面
return "Date";
}
localhost:8080/MySpringMVCWOrk_war_exploded/data/test3?id=1&name=Gura&age=12345
18、提交表单
@RequestMapping("/test4")
public String test4(User user,Model model){
model.addAttribute("user",user);
model.addAttribute("msg","用户信息提交成功!");
return "Date";
}
重新写index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<h1>111</h1>
<h2>from表单提交测试</h2>
<form action="${pageContext.request.contextPath}/data/test4" method="post">
用户id:<input type="text" name="id"><br>
用户姓名:<input type="text" name="name"><br>
用户年龄:<input type="text" name="age"><br>
<input type="submit" value="提交用户信息"><br>
</form>
</body>
</html>