目录
7.HiddenHttpMethodFilter,解决put和delete
1.什么是MVC
mvc是一种软件架构的思想,将软件按照模型、视图、控制来划分
Model:模型层,指工程中的javaBean,作用处理数据(1.存储业务数据 2.业务处理层面)
View:视图层,指工程中的html或thymeleaf等页面,用户交互的界面
Controller:控制层,指工程中的servlet,作用是接受请求和响应浏览器
2.三层架构的正确说法
三层架构分为表述层(或表示层view)、业务逻辑层、数据访问层,表述层表示前台页面和后台 servlet
3.实例操作
1.创建maven工程并导入依赖
<dependencies>
<!-- SpringMVC --> 导入SpringMVC的jar包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.1</version>
</dependency>
<!-- 日志 --> 日志功能
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<!-- ServletAPI --> 导入servlet包
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- Spring5和Thymeleaf整合包 -->
<dependency> 导入thymeleaf包
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.12.RELEASE</version>
</dependency>
</dependencies>
2.创建webapp以及在xml文件中进行配置
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servletclass>
//扩展因为我们一般把文件放在resources文件夹下
<!-- 通过初始化参数指定SpringMVC配置文件的位置和名称 -->
<init-param>
<!-- contextConfigLocation为固定值 -->
<param-name>contextConfigLocation</param-name>
<!-- 使用classpath:表示从类路径查找配置文件,例如maven工程中的src/main/resources -->
<param-value>classpath:springMVC.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<!--
设置springMVC的核心控制器所能处理的请求的请求路径
/所匹配的请求可以是/login或.html或.js或.css方式的请求路径
但是/不能匹配.jsp请求路径的请求
-->
<url-pattern>/</url-pattern>
</servlet-mapping>
3.配置springmvc的配置文件(标准型)
固定的配置,为了使得thymeleaf能产生作用
<!-- 配置Thymeleaf视图解析器 -->
<bean id="viewResolver"
class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
<property name="order" value="1"/>
<property name="characterEncoding" value="UTF-8"/>
<property name="templateEngine">
<bean class="org.thymeleaf.spring5.SpringTemplateEngine">
<property name="templateResolver">
<bean
class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
<!-- 视图前缀 -->
<property name="prefix" value="/WEB-INF/templates/"/> 在经过处理前面添加文件路径
<!-- 视图后缀 -->
<property name="suffix" value=".html"/> 在经过处理的后面添加html
<property name="templateMode" value="HTML5"/>
<property name="characterEncoding" value="UTF-8" /> 设置编码
</bean>
</property>
</bean>
</property>
</bean>
4.因为我们在这个过程中会使用到注解的形式,所以我们会在springmvc.xml文件中添加扫描组件
<context:component-scan base-package="com.atguigu.mvc.controller"/>
扫描:扫描的路径
在扫描中有两个标签,一个是指定扫描,一个是排除扫描
5.在使用注解的时候,我们还需要添加一些常用的标签
上面只能访问静态资源.如下是可以访问动态资源,会先经过Dispactch处理之后,然后再由他处理,两方面处理
<mvc:default-servlet-handler/>
开启注解驱动,这样就能使用mvc的注解功能
<mvc:annotation-driven/>
6.通过注解的方式进行默认的访问首页
@RequestMapping("/") 这是请求方式:/请求,只有这样的请求方式才能经过thymeleaf的渲染,才能将树数据库中的东西展现在页面上
public String index() {
//设置视图名称
return "index";
}
7.可以通过默认的访问防止,(因为每一次都需要写这个/,所以直接抽取再springmvc.xml中即可)
<!--配置默认的servlet处理静态资源-->
<mvc:default-servlet-handler /> 首先被Dispatchservler处理,之后再被tomcat处理
这两个不能少
<!--开启mvc的注解驱动-->
<mvc:annotation-driven />
设置默认访问方式
<mvc:view-controller path="/" view-name="index"></mvc:view-controller>
4.springmvc常见的四种请求方式
处理get请求的映射-->@GetMapping
处理post请求的映射-->@PostMapping
处理put请求的映射-->@PutMapping
处理delete请求的映射-->@DeleteMapping
1.GetMapping在RequestMapping中的一个method的一个属性
@RequestMapping(
value = {"/testRequestMapping", "/test"},//这个是获取请求路径
method = {RequestMethod.GET, RequestMethod.GET} ) //这个是请求方式
<a th:href="@{/testRequestMapping}">测试get请求-->/testRequestMapping</a><br>>
使用thymeleaf语法
2.PostMapping在RequestMapping中
@RequestMapping(
value = {"/testRequestMapping", "/test"},//这个是获取请求路径
method = {RequestMethod.GET, RequestMethod.POST} ) //这个是请求方式
<form th:action="@{/test}" method="post">
<input type="submit">
</form>
3.PutMapping和DeleteMapping在RequestMapping中
@RequestMapping(
value = {"/testRequestMapping", "/test"},//这个是获取请求路径
method = {RequestMethod.GET, RequestMethod.DELETE OR PUT } ) //这个是请求方式
<form th:action="@{/test}" method="post">
<input type="submit" name="_method" value="delete或者put">
</form>
5.获取请求中附带的参数
1.获取参数
<a th:href="@{/test(username='admin',password='admin')}">测试params属性 </a>
可以利用param来过去响应的参数信息
@RequestMapping( value = {"/testRequestMapping", "/test"} ,method = {RequestMethod.GET, RequestMethod.POST} ,params = {"username","password!=123456"} )
2.获取占位符参数
1.发送请求
原始方式:/deleteUser?id=1 原始的方式
rest方式:/user/delete/1 现在的方式
th:href="@{/test/1}"
2.获取请求
RequestMapping("/test/{id}")
public String testRest(@PathVariable("id") String id, @PathVariable("username")
String username){
System.out.println("id:"+id+",username:"+username);
return "success";
}
3.get请求过程中获取参数
<a th:href="@{/testParam(username='admin',password=123456)}">测试获取请求参数--
>/testParam</a><br>
@RequestMapping("/testParam")
public String testParam(String username, String password){
System.out.println("username:"+username+",password:"+password);
return "success";
}
4.请求form表单中获取参数
<form th:action="@{/testpojo}" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
性别:<input type="radio" name="sex" value="男">男<input type="radio"
name="sex" value="女">女<br>
年龄:<input type="text" name="age"><br>
邮箱:<input type="text" name="email"><br>
<input type="submit">
</form>
获取参数。要求pojo对应的列一致
@RequestMapping("/testpojo")
public String testPOJO(User user){
System.out.println(user);
return "success";
}
5.解决请求参数的乱码问题
在springmvc中配置过滤器
<filter>
<filter-name>CharacterEncodingFilter</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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
6.域对象共享数据
1.ServletAPI向request域对象共享数据
@RequestMapping("/testServletAPI")
public String testServletAPI(HttpServletRequest request){
request.setAttribute("testScope", "hello,servletAPI");
return "success";
}
2.使用ModelAndView向request域对象共享数据
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
ModelAndView mav = new ModelAndView();
//向请求域共享数据
mav.addObject("testScope", "hello,ModelAndView");
//设置视图,实现页面跳转
mav.setViewName("success");
return mav;
}
3.最常用的就是Model方法
@RequestMapping("/testModel")
public String testModel(Model model){
model.addAttribute("testScope", "hello,Model");
return "success";
}
4.使用map向request域对象共享数据和使用ModelMap向request域对象共享数据
@RequestMapping("/testMap")
public String testMap(Map<String, Object> map){
map.put("testScope", "hello,Map");
return "success";
}
@RequestMapping("/testModelMap")
public String testModelMap(ModelMap modelMap){
modelMap.addAttribute("testScope", "hello,ModelMap");
return "success";
}
5.最早的session方法
@RequestMapping("/testSession")
public String testSession(HttpSession session){
session.setAttribute("testSessionScope", "hello,session");
return "success";
}
6.application域共享数据
@RequestMapping("/testApplication")
public String testApplication(HttpSession session){
ServletContext application = session.getServletContext();
application.setAttribute("testApplicationScope", "hello,application");
return "success";
}
7.HiddenHttpMethodFilter,解决put和delete
需要添加过滤器在web.xml中
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filterclass>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
在view视图层书写的时候,需要一个的规则
<form th:action="@{/test}" method="post">
<input type="submit" name="_method" value="delete或者put">
</form>
8.view在浏览器中进行展示
随便起名字:¥{在域对象遍历的集合}
<tr th:each="employee : ${employeeList}">
<td th:text="${employee.id}"></td>
<td th:text="${employee.lastName}"></td>
<td th:text="${employee.email}"></td>
<td th:text="${employee.gender}"></td>
<td>
Vue的异步请求
<a class="deleteA"@click="deleteEmployee"th:href="@{'/employee/'+${employee.id}}">delete</a>
<a th:href="@{'/employee/'+${employee.id}}">update</a>
</td>
<script type="text/javascript">
var vue = new Vue({
el:"#dataTable",
methods:{
//event表示当前事件
deleteEmployee:function (event) {
//通过id获取表单标签
var delete_form = document.getElementById("delete_form");
//将触发事件的超链接的href属性为表单的action属性赋值
delete_form.action = event.target.href;
//提交表单
delete_form.submit();
//阻止超链接的默认跳转行为
event.preventDefault();
}
}
});
</script>
控制层的方法
@RequestMapping(value = "/employee/{id}", method = RequestMethod.DELETE)
public String deleteEmployee(@PathVariable("id") Integer id){
employeeDao.delete(id);
return "redirect:/employee";
}
SpringMVC处理ajax请求
<!--此时必须使用post请求方式,因为get请求没有请求体-->
<form th:action="@{/test/RequestBody}" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit">
</form>
获取
@RequestMapping("/test/RequestBody")
public String testRequestBody(@RequestBody String requestBody){
System.out.println("requestBody:"+requestBody);
return "success";
}
SpringMVC处理ajax请求(在这里我们需要利用到用@RequestBody获取json)
在pom.xml中导入json的jar包
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.1</version>
</dependency>
在springmvc中开启<mvc:annation-driven/>的注解驱动
在view视图层进行vue的设置,需要将对象进行转换
书写的格式 测试@alick,绑定触发事件
<input type="button" value="测试@RequestBody获取json格式的请求数"@click="testRequestBody()"><br>
导入axios和vue的jar包这样就方便我们操作
<script type="text/javascript" th:src="@{/js/vue.js}"></script>
<script type="text/javascript" th:src="@{/js/axios.min.js}"></script>
在js中书写vue代码,进行格式的转换
<script type="text/javascript">
var vue =new Vue({
el:"div中的id"
方法 methods:{
绑定的点击事件的名字testRequestBody(){
axios.post(
"发送请求的地址"
{username:“参数”,password=“参数”}
)。then(response=》{
console.log(response。data)//这是成功之后返回的数据
})
}
}
})
在视图层也需要用到json进行格式的转换,之后 才能进行利用
相应到list集合
@RequestMapping("/test/ResponseBody/json")
@ResponseBody
public List<User> testResponseBody(){
User user1 = new User(1001,"admin1","123456",23,"男");
User user2 = new User(1002,"admin2","123456",23,"男");
User user3 = new User(1003,"admin3","123456",23,"男");
List<User> list = Arrays.asList(user1, user2, user3);
return list;
}
@RequestMapping("/test/ResponseBody/json")
@ResponseBody
public Map<String, Object> testResponseBody(){
User user1 = new User(1001,"admin1","123456",23,"男");
User user2 = new User(1002,"admin2","123456",23,"男");
User user3 = new User(1003,"admin3","123456",23,"男");
Map<String, Object> map = new HashMap<>();
map.put("1001", user1);
map.put("1002", user2);
map.put("1003", user3);
return map;
}
//响应浏览器实体类对象
@RequestMapping("/test/ResponseBody/json")
@ResponseBody
public User testResponseBody(){
return user;
}
总结:
- 讲述了springmvc整合了控制层和视图层之间的联系
- 注解的方式像@Requestmapping和RequestBody等等
- springmvc。xml的一些必须配置
- 解决了ajax和axios还有json等等的一些类的问题