SpringMVC 本质也是解耦

先提前插一嘴
这里用到的是简单的maven项目:
在添加web应用时报错
Artifacts Web facet resources 爆红
参考:https://blog.csdn.net/weixin_43739266/article/details/122133398 添加web依赖

要为项目添加web项目依赖否则无法tomcat访问
为了介绍MVC我打算直接用一个例子来看:、

| 首先位于WEB-INF下文件夹jsp建一个hello.jsp 用于显示 |
没用springboot之前我们需要手动编写xml文件:
来看几步死的:
1.web.xml的配置 需要更改的就是 classpath:你的.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> |
| |
| <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> |
| </web-app> |
2.你对应路径下的 Springmvc.xml
| classpath 下即resource下创建的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="controller.hello"/> |
| </beans> |
3.controller层编写
| package controller; |
| |
| |
| import org.springframework.web.servlet.mvc.Controller; |
| import org.springframework.web.servlet.ModelAndView; |
| |
| import javax.servlet.http.HttpServletRequest; |
| import javax.servlet.http.HttpServletResponse; |
| |
| |
| |
| |
| public class hello implements Controller { |
| public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { |
| |
| ModelAndView mv = new ModelAndView(); |
| |
| mv.addObject("msg","HelloSpringMVC!"); |
| |
| mv.setViewName("hello"); |
| return mv; |
| } |
| } |
是的你咋看咋不顺眼 改为注解形式:
| package controller; |
| |
| import org.springframework.stereotype.Controller; |
| import org.springframework.ui.Model; |
| import org.springframework.web.bind.annotation.RequestMapping; |
| |
| @Controller |
| @RequestMapping("/gao") |
| public class hello { |
| @RequestMapping("/hello") |
| public String hello(Model model) { |
| model.addAttribute("msg", "高低远近"); |
| return "hello"; |
| } |
| } |
最终体的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"> |
| |
| |
| <context:component-scan base-package="controller"/> |
| |
| <mvc:default-servlet-handler /> |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| <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> |
等会总结 这里还有个蛋疼的问题就是关于jdk编译改码的问题还有lib包问题
参考:https://blog.csdn.net/qq_46906413/article/details/131815212


正常web下项目要有lib文件所有资源识别在此:

是的感觉不是框架阶段 还是javaweb阶段 还得手动导包!
然后tomcat启动测试就行
那来看下过程:

来看看之前的:那两个省略的:
| <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/> |
| <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/> |
两个的作用呢:
- HandlerMapping
把请求映射为 HandlerExecutionChain 对象(包含一 个Handler 处理器(页面控制器)对象、多个HandlerInterceptor 拦截器)对象,通过这种策略模式,很容易添加新 的映射策略
- HandlerAdapter
处理器功能处理方法的调用,HandlerAdapter 将会根据适配的结果调用真正的处理器的功能处 理方法,完成功能处理;并返回一个ModelAndView 对象(包含模型数据、逻辑视图名)
当然还有其他组件 这就是Springmvc的强大之处例如:
filter过滤器拦截器
locale resolve国际化
multipartresolver文件上传
......
| @Controller 被spring接管 返回值若为string 则进行跳转 |
| @RequestMapping("") 是一个总的 |
参考:https://blog.csdn.net/weixin_61034310/article/details/135324203
ResultFul
| package controller; |
| |
| import org.springframework.stereotype.Controller; |
| import org.springframework.ui.Model; |
| import org.springframework.web.bind.annotation.*; |
| |
| @Controller |
| public class ResultFulController { |
| |
| |
| |
| |
| |
| |
| |
| @PostMapping("/haha/{a}/{b}") |
| |
| public String hello(@PathVariable int a,@PathVariable int b, Model model){ |
| int res=a+b; |
| model.addAttribute("msg",res); |
| return "hello"; |
| } |
| @GetMapping("/hahaha/{a}/{b}") |
| public String hello2(@PathVariable int a,@PathVariable int b, Model model){ |
| int res=a+b; |
| model.addAttribute("msg",res); |
| return "hello"; |
| } |
| } |
| package controller; |
| |
| import org.springframework.stereotype.Controller; |
| import org.springframework.ui.Model; |
| import org.springframework.web.bind.annotation.RequestMapping; |
| import org.springframework.web.bind.annotation.RequestParam; |
| import pojo.User; |
| |
| @Controller |
| @RequestMapping("/user") |
| public class Usercontroller { |
| |
| |
| @RequestMapping("/one") |
| |
| public String haha(@RequestParam("user") String name, Model model) { |
| model.addAttribute("msg", name); |
| return "hello"; |
| } |
| |
| @RequestMapping("/two") |
| |
| public String haha(User user, Model model) { |
| model.addAttribute("msg", user.getName()); |
| return "hello"; |
| } |
| } |
再来看一个拦截功能 即登录实现

| <%-- |
| Created by IntelliJ IDEA. |
| User: Administrator |
| Date: 2024/5/21 |
| Time: 10:24 |
| To change this template use File | Settings | File Templates. |
| --%> |
| <%@ page contentType="text/html;charset=UTF-8" language="java" %> |
| <html> |
| <head> |
| <title>Title</title> |
| </head> |
| |
| <h1>登录页面</h1> |
| <hr> |
| |
| <body> |
| <form action="${pageContext.request.contextPath}/user/login"> |
| 用户名:<input type="text" name="username"> <br> |
| 密码:<input type="password" name="pwd"> <br> |
| <input type="submit" value="提交"> |
| </form> |
| </body> |
| </html> |
| |
| <%-- |
| Created by IntelliJ IDEA. |
| User: Administrator |
| Date: 2024/5/21 |
| Time: 10:24 |
| To change this template use File | Settings | File Templates. |
| --%> |
| <%@ page contentType="text/html;charset=UTF-8" language="java" %> |
| <html> |
| <head> |
| <title>Title</title> |
| </head> |
| <body> |
| |
| <h1>登录成功页面</h1> |
| <hr> |
| |
| ${user} |
| <a href="${pageContext.request.contextPath}/user/logout">注销</a> |
| </body> |
| </html> |
| |
| |
| <%-- |
| Created by IntelliJ IDEA. |
| User: Administrator |
| Date: 2024/5/24 |
| Time: 15:43 |
| To change this template use File | Settings | File Templates. |
| --%> |
| <%@ page contentType="text/html;charset=UTF-8" language="java" %> |
| <html> |
| <head> |
| <title>$Title$</title> |
| </head> |
| <body> |
| <h1>首页</h1> |
| <hr> |
| <%--登录--%> |
| <a href="${pageContext.request.contextPath}/user/jumplogin">登录</a> |
| <a href="${pageContext.request.contextPath}/user/jumpSuccess">成功页面</a> |
| </body> |
| </html> |
| |
| |
| package controller; |
| |
| import org.springframework.stereotype.Controller; |
| import org.springframework.web.bind.annotation.RequestMapping; |
| |
| import javax.servlet.http.HttpSession; |
| |
| @Controller |
| @RequestMapping("/user") |
| public class Usercontroller { |
| |
| |
| @RequestMapping("/jumplogin") |
| public String jumpLogin() throws Exception { |
| return "login"; |
| } |
| |
| |
| @RequestMapping("/jumpSuccess") |
| public String jumpSuccess() throws Exception { |
| return "success"; |
| } |
| |
| |
| @RequestMapping("/login") |
| public String login(HttpSession session, String username, String pwd) throws Exception { |
| |
| System.out.println("接收前端==="+username); |
| session.setAttribute("user", username); |
| return "success"; |
| } |
| |
| |
| @RequestMapping("logout") |
| public String logout(HttpSession session) throws Exception { |
| |
| session.invalidate(); |
| return "login"; |
| } |
| } |
| |
| package config; |
| |
| import org.springframework.web.servlet.HandlerInterceptor; |
| import org.springframework.web.servlet.ModelAndView; |
| |
| import javax.servlet.ServletException; |
| import javax.servlet.http.HttpServletRequest; |
| import javax.servlet.http.HttpServletResponse; |
| import javax.servlet.http.HttpSession; |
| import java.io.IOException; |
| |
| public class loginconfig implements HandlerInterceptor { |
| |
| public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException { |
| |
| System.out.println("uri: " + request.getRequestURI()); |
| if (request.getRequestURI().contains("login")) { |
| return true; |
| } |
| |
| HttpSession session = request.getSession(); |
| |
| |
| if(session.getAttribute("user") != null) { |
| return true; |
| } |
| |
| |
| request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response); |
| return false; |
| } |
| |
| public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { |
| |
| } |
| |
| public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { |
| |
| } |
| } |
| |
| <mvc:interceptors> |
| <mvc:interceptor> |
| <mvc:mapping path="/**"/> |
| <bean id="loginInterceptor" class="config.loginconfig"/> |
| </mvc:interceptor> |
| </mvc:interceptors> |
还有就是文件上传下载 也是死东西可以直接运用:
参考:https://cloud.tencent.com/developer/article/1594124
文章更详细参考:https://pdai.tech/md/spring/spring-x-framework-springmvc.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?