一、引用接口开发
1.首先在web.xml中配置DispatcherServlet
<?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">
<!-- 配置DispatcherServlet:请求分发器,前端控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- DispatcherServlet绑定Spring配置问文件 -->
<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>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd ">
<!--处理器映射器-->
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<!--处理器适配器-->
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!-- 后缀 -->
<property name="suffix" value=".jsp"/>
</bean>
<bean id="/hello" class="com.kuang.controller.HelloController"/>
</beans>
3.在servlet层填写业务逻辑
package com.kuang.controller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloController implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
ModelAndView mv = new ModelAndView();
//业务代码 attributeName:业务名字、attrValue:业务值
mv.addObject("msg","HelloSpringMVC");
//视图跳转
mv.setViewName("hello");
return mv;
}
}
4.创建视图内容
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${msg}
</body>
</html>
二、注解开发
1.配置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>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<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>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
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">
<!-- 自动扫描包,让指定包下的注解生效,由IOC容器统一管理 -->
<context:component-scan base-package="com.kuang.controller"/>
<!-- 让SpringMVC不处理静态资源 -->
<mvc:default-servlet-handler/>
<!--
支持mvc注解驱动:
在spring中一般采用@RequestMapping注解来完成映射关系
想要使@RequestMapping注解生效
必须向上下文注册DefaultAnnotationHandlerMapping
和一个A你弄他汀MethodHandlerAdapter实例
这两个实例分别在类级别和方法级别处理
而annotation-driven配置帮助我们自动完成上述两个实例的注入
-->
<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>
3.配置Controller层
package com.kuang.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;
@Controller//代表这个类被Spring托管
//被这个注解的类,中的所有方法,如果返回值是String,并且有具体页面可以跳转,那么就会被视图解析器解析
public class ControllerTest2 {
// @PathVariable可以直接在url中传输变量
@RequestMapping(value = "/t2/{a}/{b}",method = RequestMethod.GET)
public String test1(@PathVariable int a,@PathVariable int b, Model model){
int res = a+b;
model.addAttribute("msg","ControllerTest2"+res);
return "test";
}
@RequestMapping(value = "/t2/{a}/{b}",method = RequestMethod.POST)
public String test2(@PathVariable int a,@PathVariable int b, Model model){
int res = a+b;
model.addAttribute("msg","ControllerTest3"+res);
return "test";
}
}
4.配置前端页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${msg}
</body>
</html>
三、将数据传回前端
1.Model:只有几个方法,适用于存储数据
//@RequestParam重命名参数,前端发送username就可以连接到name,username和name不能同时使用
@GetMapping("/t1")
public String test1(@RequestParam("username") String name, Model model){
// 1.接收前端参数
System.out.println("接收到前端的参数为:"+name);
// 2.将返回的结果传输给前端
model.addAttribute("msg",name);
// 3.视图跳转
return "test";
}
2.Modelmap:继承了LinkedMap,除了实现自身的一些方法,集成LinkedMap的方法和特性
3.LinkedMap:可以在存储数据的同时进行设置返回的逻辑视图,进行控制转换层的跳转
4ModelAndView:
@Override
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
ModelAndView mv = new ModelAndView();
mv.addObject("msg","ControllerTest1");
mv.setViewName("test");
return mv;
}
四、JSON的使用
JSON作为前后端交互的纽带,负责将后端的JavaScript对象转换为iString类型传回前端,也可以将JSON字符串转换为JavaScript对象,传回后端。
1.JSON使用流程
1.1导入JSON包
1.2将乱码配置在spring-servlet.xml中(如2.2)
1.3新建ObjectMapper对象,传入实体类,将其转换成Spring
@Controller
public class UserController {
@RequestMapping(value = "/j1")
@ResponseBody//添加该注解就不会走视图解析器,会直接返回一个字符串
public String json1() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
// 创建一个对象
User user = new User(123,"高崧豪", 23);
String str = mapper.writeValueAsString(user);
return str;
}
}
此处可以将@ResponseBody删除,将@Controller更换为@RestController有同样的效果
2.JSON字符串乱码问题
2.1在RequestMapping中配置字符解析格式(在Controller层操作)
@Controller
public class UserController {
@RequestMapping(value = "/j1",produces = "application/json;charset=utf-8")
@ResponseBody//添加该注解就不会走视图解析器,会直接返回一个字符串
public String json1() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
// 创建一个对象
User user = new User(123,"高崧豪", 23);
String str = mapper.writeValueAsString(user);
return str;
}
}
2.2在springmvc-servlet.xml中解决JSON乱码问题
<!-- JSON乱码问题配置 -->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
五、其他知识点
1.重定向在controller层,与转发的区别是return部分,页面链接部分也有区别
@RequestMapping(value = "/t2/{a}/{b}",method = RequestMethod.POST)
public String test2(@PathVariable int a,@PathVariable int b, Model model){
int res = a+b;
model.addAttribute("msg","ControllerTest3"+res);
return "redirect:/a.jsp";
}
2.转发在controller层,与重定向的区别是return部分,页面链接部分也有区别
@RequestMapping(value = "/t2/{a}/{b}",method = RequestMethod.GET)
public String test1(@PathVariable int a,@PathVariable int b, Model model){
int res = a+b;
model.addAttribute("msg","ControllerTest2"+res);
return "test";
}
@RequestMapping(value = "/t2/{a}/{b}",method = RequestMethod.GET)
public String test1(@PathVariable int a,@PathVariable int b, Model model){
int res = a+b;
model.addAttribute("msg","ControllerTest2"+res);
return "forward:/a.jsp";
}
3.过滤器,解决页面传入参数时的乱码问题
3.1编写过滤器java代码
package com.kuang.filter;
import javax.servlet.*;
import java.io.IOException;
public class EncodingFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("utf-8");
servletResponse.setCharacterEncoding("utf-8");
filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
}
}
3.2在web.xml中配置过滤器文件
<filter>
<filter-name>encoding</filter-name>
<filter-class>com.kuang.filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3.3url-patten中需设定为/*这样可以覆盖.jsp文件
|