本篇文章为你整理了SpringMVC(springmvc与springboot区别)的详细内容,包含有springmvc的工作原理 springmvc与springboot区别 springmvc常用注解 springmvc是什么 SpringMVC,希望能帮助你了解 SpringMVC。
SpringMVC是Spring 为【展现层表示层表述层控制层】提供的基于 MVC 设计理念的优秀的 Web 框架,是目前最主流的MVC 框架。
url配置:/
init-param:contextConfigLocation,设置springmvc.xml配置文件路径【管理容器对象】
load-on-startup :设置DispatcherServlet优先级【启动服务器时,创建当前Servlet对象】
作用:为当前URL设置请求参数
注意:如设置指定请求参数,但URL中未携带指定参数,会报如下错误
400【Parameter conditions "lastName" not met for actual request parameters:】
params = "lastName=lisi",
headers = "User-Agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.84 Safari/537.36")
public String saveEmp(){
System.out.println("添加员工信息!!!!");
return SUCCESS;
示例代码
a th:href="@{/EmpController/testPathVariable/1001}" 测试PathVariable注解 /a br
/**
* testPathVariable
* @return
@RequestMapping("/testPathVariable/{empId}")
public String testPathVariable(@PathVariable("empId") Integer empId){
System.out.println("empId = " + empId);
return SUCCESS;
5.4 源码解析HiddenHttpMethodFilter
public static final String DEFAULT_METHOD_PARAM = "_method";
private String methodParam = DEFAULT_METHOD_PARAM;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
HttpServletRequest requestToUse = request;
if ("POST".equals(request.getMethod()) request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == null) {
String paramValue = request.getParameter(this.methodParam);
if (StringUtils.hasLength(paramValue)) {
String method = paramValue.toUpperCase(Locale.ENGLISH);
if (ALLOWED_METHODS.contains(method)) {
requestToUse = new HttpMethodRequestWrapper(request, method);
filterChain.doFilter(requestToUse, response);
* Simple {@link HttpServletRequest} wrapper that returns the supplied method for
* {@link HttpServletRequest#getMethod()}.
private static class HttpMethodRequestWrapper extends HttpServletRequestWrapper {
private final String method;
public HttpMethodRequestWrapper(HttpServletRequest request, String method) {
super(request);
this.method = method;
@Override
public String getMethod() {
return this.method;
第六章 SpringMVC处理请求数据
使用Servlet处理请求数据
String param = request.getParameter();
LastName: input type="text" name="lastName" br
Email: input type="text" name="email" br
Salary: input type="text" name="salary" br
input type="submit" value="添加员工信息"
/form
/**
* 获取请求参数POJO
* @return
@RequestMapping(value = "/saveEmp",method = RequestMethod.POST)
public String saveEmp(Employee employee){
System.out.println("employee = " + employee);
return SUCCESS;
@RequestMapping("/requestParam1")
public String requestParam1(@RequestParam(value = "sName",required = false,
defaultValue = "zhangsan")
String stuName,
Integer stuAge){
System.out.println("stuName = " + stuName);
System.out.println("stuAge = " + stuAge);
return SUCCESS;
@RequestMapping(value = "/testGetHeader")
public String testGetHeader(@RequestHeader("Accept-Language")String al,
@RequestHeader("Referer") String ref){
System.out.println("al = " + al);
System.out.println("ref = " + ref);
return SUCCESS;
a th:href="@{/setCookie}" 设置Cookie信息 /a br
a th:href="@{/getCookie}" 获取Cookie信息 /a br
/**
* 设置Cookie
* @return
@RequestMapping("/setCookie")
public String setCookie(HttpSession session){
// Cookie cookie = new Cookie();
System.out.println("session.getId() = " + session.getId());
return SUCCESS;
* 获取Cookie
* @return
@RequestMapping("/getCookie")
public String getCookie(@CookieValue("JSESSIONID")String cookieValue){
System.out.println("cookieValue = " + cookieValue);
return SUCCESS;
@RequestMapping("/useRequestObject")
public String useRequestObject(HttpServletRequest request){}
第七章 SpringMVC处理响应数据
7.1 使用ModelAndView
ModelAndView是模型数据与视图对象的集成对象,源码如下
public class ModelAndView {
/** View instance or view name String. */
//view代表view对象或viewName【建议使用viewName】
@Nullable
private Object view;
/** Model Map. */
//ModelMap集成LinkedHashMap,存储数据
@Nullable
private ModelMap model;
设置视图名称
public void setViewName(@Nullable String viewName) {
this.view = viewName;
* 获取视图名称
@Nullable
public String getViewName() {
return (this.view instanceof String ? (String) this.view : null);
获取数据,返回Map【无序,model可以为null】
@Nullable
protected Map String, Object getModelInternal() {
return this.model;
* 获取数据,返回 ModelMap【有序】
public ModelMap getModelMap() {
if (this.model == null) {
this.model = new ModelMap();
return this.model;
* 获取数据,返回Map【无序】
public Map String, Object getModel() {
return getModelMap();
设置数据
public ModelAndView addObject(String attributeName, @Nullable Object attributeValue) {
getModelMap().addAttribute(attributeName, attributeValue);
return this;
mv.setViewName("response_success");
//设置数据【将数据共享到域中(request\session\servletContext)】
mv.addObject("stuName","zhouxu");
return mv;
@GetMapping("/testMapResponsedata")
public String testMapResponsedata(Map String,Object map
/* Model model
ModelMap modelMap*/){
map.put("stuName","zhangsan");
// model.addAttribute("stuName","lisi");
// modelMap.addAttribute("stuName","wangwu");
return "response_success";
@GetMapping("/testScopeResponsedata")
public String testScopeResponsedata(HttpSession session){
session.setAttribute("stuName","xinlai");
return "response_success";
@Controller
@SessionAttributes(value = "stuName") //将request域中数据,同步到session域中
public class TestResponseData {
* 使用ModelAndView处理响应数据
* @return
@GetMapping("/testMvResponsedata")
public ModelAndView testMvResponsedata(){
ModelAndView mv = new ModelAndView();
//设置逻辑视图名
mv.setViewName("response_success");
//设置数据【将数据共享到域中(request\session\servletContext)】
mv.addObject("stuName","zhouxu");
return mv;
8.1 源码解析CharacterEncodingFilter
public class CharacterEncodingFilter extends OncePerRequestFilter {
//需要设置字符集
@Nullable
private String encoding;
//true:处理请乱码
private boolean forceRequestEncoding = false;
//true:处理响应乱码
private boolean forceResponseEncoding = false;
public String getEncoding() {
return this.encoding;
public boolean isForceRequestEncoding() {
return this.forceRequestEncoding;
public void setForceResponseEncoding(boolean forceResponseEncoding) {
this.forceResponseEncoding = forceResponseEncoding;
public void setForceEncoding(boolean forceEncoding) {
this.forceRequestEncoding = forceEncoding;
this.forceResponseEncoding = forceEncoding;
@Override
protected void doFilterInternal(
HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String encoding = getEncoding();
if (encoding != null) {
if (isForceRequestEncoding() request.getCharacterEncoding() == null) {
request.setCharacterEncoding(encoding);
if (isForceResponseEncoding()) {
response.setCharacterEncoding(encoding);
filterChain.doFilter(request, response);
为CharacterEncodingFilter中属性encoding赋值
为CharacterEncodingFilter中属性forceRequestEncoding赋值
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 forceRequestEncoding /param-name
param-value true /param-value
/init-param
/filter
filter-mapping
filter-name CharacterEncodingFilter /filter-name
url-pattern /* /url-pattern
/filter-mapping
无论方法返回是ModelAndView还是String,最终SpringMVC底层,均会封装为ModelAndView对象
//DispatcherServlet的1061行代码
ModelAndView mv = null;
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
//DispatcherServlet的1078行代码
processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
ThymeleafView对象中344行代码【SpringMVC底层处理响应乱码】
//computedContentType="text/html;charset=UTF-8"
response.setContentType(computedContentType);
WebEngineContext对象中783行代码【SpringMVC底层将数据默认共享到request域】
this.request.setAttribute(name, value);
ThymeleafViewResolver的837行代码
//底层使用反射的方式,newInstance()创建视图对象
final AbstractThymeleafView viewInstance = BeanUtils.instantiateClass(getViewClass());
10.2 视图对象【View】
概述:View接口的实现类或子接口,称之为视图对象
作用:视图渲染
将数据共享域中
跳转路径【转发或重定向】
有20+种功能
配置了 mvc:view-controller 标签之后会导致其他请求路径都失效,添加 mvc:annotation-driven 解决
servlet-name default /servlet-name
servlet-class org.apache.catalina.servlets.DefaultServlet /servlet-class
init-param
param-name debug /param-name
param-value 0 /param-value
/init-param
init-param
param-name listings /param-name
param-value false /param-value
/init-param
load-on-startup 1 /load-on-startup
/servlet
servlet-mapping
servlet-name default /servlet-name
url-pattern / /url-pattern
/servlet-mapping
DispatcherServlet与DefaultServlet的URL配置均为:/,导致DispatcherServlet中的配置将DefaultServlet配置的/覆盖了【DefaultServlet失效,无法加载静态资源】
!-- 解决静态资源加载问题--
mvc:default-servlet-handler /mvc:default-servlet-handler
!-- 添加上述标签,会导致Controller无法正常使用,需要添加mvc:annotation-driven解决 --
mvc:annotation-driven /mvc:annotation-driven
创建RedirectView对象【ThymeleafViewResolver的775行代码】
// Process redirects (HTTP redirects)
if (viewName.startsWith(REDIRECT_URL_PREFIX)) {
vrlogger.trace("[THYMELEAF] View \"{}\" is a redirect, and will not be handled directly by ThymeleafViewResolver.", viewName);
final String redirectUrl = viewName.substring(REDIRECT_URL_PREFIX.length(), viewName.length());
final RedirectView view = new RedirectView(redirectUrl, isRedirectContextRelative(), isRedirectHttp10Compatible());
return (View) getApplicationContext().getAutowireCapableBeanFactory().initializeBean(view, REDIRECT_URL_PREFIX);
a href="#" @click="deleteEmp" 删除 /a
form id="delForm" th:action="@{/emps/}+${emp.id}" method="post"
input type="hidden" name="_method" value="DELETE"
/form
/div
script type="text/javascript" src="static/js/vue_v2.6.14.js" /script
script type="text/javascript"
new Vue({
el:"#app",
data:{},
methods:{
deleteEmp(){
alert("hehe");
//获取响应表单
var formEle = document.getElementById("delForm");
formEle.submit();
//取消超链接默认行为
event.preventDefault();
/script
以上就是SpringMVC(springmvc与springboot区别)的详细内容,想要了解更多 SpringMVC的内容,请持续关注盛行IT软件开发工作室。
郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系,我们将第一时间修改或删除,多谢。