4.使用注解开发SpringMVC
- 新建一个javaWeb项目,由于可以能资源导不出的问题我们现在Maven配置中加入
<build> <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> </build>
-
配置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"> <!--1.注册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>
-
配置关联的Spring文件
<?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"> <!-- 自动扫描包,让指定包下的注解生效,由IOC容器统一管理 --> <context:component-scan base-package="com.xiao.controller"/> <!-- 让Spring MVC不处理静态资源 --> <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>
-
编写Controllor控制器
package com.xiao.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class HelloController { //相当于真实访问路径http://localhost:8080/h1 @RequestMapping("/h1") public String hello(Model model){ //封装数据 model.addAttribute("msg","HelloMvc"); return "hello";//会被视图解析器处理 } }
-
编写页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> ${msg} </body> </html>
5.Controller配置总结
第一种Controller控制器:
1.实现Controller接口
package org.springframework.web.servlet.mvc;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.ModelAndView;
//实现了这个接口就代表是一个控制器
@FunctionalInterface
public interface Controller {
//用来接收一个请求,并且返回一个模型视图
@Nullable
ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception;
}
2.编写实现Controller接口的类
package com.xiao.controller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//只要实现了Controller的类说明这就是一个控制器
public class test implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("msg", "Hello");
modelAndView.setViewName("test");
return modelAndView;
}
}
3.配置映射(bean)
<bean id="/hello" class="com.xiao.controller.test"/>
4.编写页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${msg}
</body>
</html>
第二种使用注解Controller控制器:
package com.xiao.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller //代表这个类会被spring接管,被这个注解注解的类如果返回的是String类型就会经过视图解析器
public class test02 {
@RequestMapping("/test")
public String test(Model model){
model.addAttribute("msg","帅气");
return "test";
}
}
6.RestFul风格
概述:RestFul风格就是资源定位以及资源操作的风格,不是标准,也不是协议,仅仅就是一个风格,基于这个风格设计的软件可以更加简洁更加具有层次,根易于实现缓存等机制
功能:
- 资源:互联网所有的事务都可以被抽象为功能
- 资源操作:使用POST,DELETE,PUT,GET,使用不同的方法对资源进行操作
- 分别对应:添加,删除,修改,查询
传统方式操作资源:通过不同的参数来达到不同的效果如:GET与POST
- http://127.0.0.1/item/queryltem.action?id=1 查询,GET
- http://127.0.0.1/item/saveltem.action 新增POST
- http://127.0.0.1/item/updateltem.action 跟新POST
- http://127.0.0.1/item/deleteltem.action?id=1 删除DELETE 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
代码:
@RequestMapping( path="/test/{aa}/{bb}",method= RequestMethod.GET) //请求的路径,使用参数获取的时候必须要加上:@PathVariable int aa等!
public String test(@PathVariable int aa,@PathVariable int bb, Model model){
int b1 =aa+ bb;
model.addAttribute("msg","a+b的总和是:"+b1);
return "test";
}
可简化注解为:
@GetMapping("/test/{aa}/{bb}") //请求的路径,使用参数获取的时候必须要加上:@PathVariable int aa等!
public String test(@PathVariable int aa,@PathVariable int bb, Model model){
int b1 =aa+ bb;
model.addAttribute("msg","a+b的总和是:"+b1);
return "test";
}
测试:
7.重定向与转发
使用SpringMVC实现转发的时候需要将视图解析器注释掉:
@GetMapping("/mt/q1")
public String test01(HttpServletRequest req, HttpServletResponse reqs, Model module) throws IOException {
HttpSession session = req.getSession();
module.addAttribute("msg",session.getId());
//转发
return "/test.jsp";
}
@GetMapping("/mt/q2")
public String test02(HttpServletRequest req, HttpServletResponse reqs, Model module) throws IOException {
HttpSession session = req.getSession();
module.addAttribute("msg",session.getId());
//转发方式二
return "forward:/test.jsp";
}
@GetMapping("/mt/q3")
public String test03(HttpServletRequest req, HttpServletResponse reqs, Model module) throws IOException {
HttpSession session = req.getSession();
module.addAttribute("msg",session.getId());
//重定向
return "redirect:/test.jsp";
}
注意:只有程序中的转发才能到WEB-INF文件夹下而重定向不行!