前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring MVC体系结构和处理请求控制器

Spring MVC体系结构和处理请求控制器

作者头像
xiaozhangStu
发布2023-05-04 19:21:20
3500
发布2023-05-04 19:21:20
举报
文章被收录于专栏:xiaozhangStuxiaozhangStu

Spring MVC体系结构和处理请求控制器

基于注解的处理器

配置
代码语言:javascript
复制
<context:component-scan />
扫描组件
代码语言:javascript
复制
<mvc:annotation-driven />
注解驱动

@Controller

@Controller用于标记在一个类上,使用它标记的类就是一个SpringMvc Controller对象,分发处理器会扫描使用该注解的类的方法,并检测该方法是否使用了@RequestMapping注解。 @Controller只是定义了一个控制器类,而使用@RequestMapping注解的方法才是处理请求的处理器。 @Controller标记在一个类上还不能真正意义上说它就是SpringMvc的控制器,应为这个时候Spring还不认识它,这个时候需要把这个控制器交给Spring来管理

@RequestMapping

通过请求URL进行映射

1.注解 @RequestMapping 可以用在类定义处和方法定义处。 类定义处:规定初步的请求映射,相对于web应用的根目录; 方法定义处:进一步细分请求映射,相对于类定义处的URL。如果类定义处没有使用该注解,则方法标记的URL相对于根目录而言;

2.@RequestMapping除了可以指定URL映射外,还可以指定“请求方法、请求参数和请求头”的映射请求 注解的value、method、params及headers分别指定“请求的URL、请求方法、请求参数及请求头”。它们之间是与的关系,联合使用会使得请求的映射更加精细。   2.1 method属性可以指定请求的类型,http中规定请求有四种类型:get,post,put,delete。其值在枚举类型RequestMethod中有规定。

@RequestParam

value----参数名 required ----是否必须 defaultValue----默认值

代码语言:javascript
复制
@RequestMapping("/welcome")
public String Welcome(@RequestParam(value="username",
                                                                        required=false)                                                                    String username){
        ……代码省略
}
​

DispatcherServlet

SpringMVC的核心就是DispatcherServlet,DispatcherServlet实质也是一个HttpServlet。DispatcherSevlet负责将请求分发,所有的请求都有经过它来统一分发。

ModelAndView

当控制器处理完请求时,通常会将包含视图名称或视图对象以及一些模型属性的ModelAndView对象返回到DispatcherServlet。

1、返回指定页面

void setView(View view); void setViewName(String viewName);

2、返回所需数值

ModelAndView addObject(String attributeName, Object attributeValue); ModelAndView addAllObjects(Map<String,?> modelMap);

Model

数据结构:Map类型 常用方法:添加模型数据

代码语言:javascript
复制
Model.addAttribute(String attributeName,Object attributeValue);
​

在Model中增加模型数据,若不指定key, 则默认使用对象的类型作为key

用map代替model入参是可行的但是一般作为Spring MVC的标准用法,推荐使用Model

ViewResolver

视图解析器

代码语言:javascript
复制
<bean  class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <property name="suffix" value=".jsp"/>
</bean>
​

框架特点

清晰地角色划分 灵活的配置功能 提供了大量的控制器接口和实现类 真正做到与View层的实现无关(JSP、Velocity、Xslt等) 国际化支持 面向接口编程 Spring提供了Web应用开发的一整套流程,不仅仅是MVC,他们之间可以很方便的结合一起

使用idea创建springmvc项目

创建项目
命名
等待jar包下载完毕
创建所需的文件夹
配置环境
配置文件
在resources内创建配置文件
applicationContext.xml
代码语言:javascript
复制
<?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">
​
</beans>
Spring-mvc-servlet.xml
代码语言:javascript
复制
<?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 http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--    /WEB-INF/page/意为页面的路径,.jsp为页面格式-->
        <property name="prefix" value="/WEB-INF/page/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--加载注解驱动-->
    <mvc:annotation-driven></mvc:annotation-driven>
    <!--扫描控制器类所在的包-->
    <context:component-scan base-package="control"/>
</beans>
编写web.xml
代码语言:javascript
复制
<?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">
    <!--配置该元素用来声明应用范围(整个WEB项目)内的上下文初始化参数
  如果我们有配置ContextLoaderListener, Spring会去web.xml中看我们是否有定义contextConfigLocation这个参数,如果有则Spring容器(Bean工厂)会把定义在该xml文件中的bean加载到容器中,那如果没有定义contextConfigLocation参数就要报FileNotFoundException了
  -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <!--创建监听器 作用就是启动Web容器时,自动装配ApplicationContext的配置信息-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>spring-mvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
​
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <!--值越小,servlet的优先级越高,就越先被加载-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <!-- 如果你的DispatcherServlet拦截 *.do这样的URL,就不存在访问不到静态资源的问题。如果你的DispatcherServlet拦截“/”,拦截了所有的请求,同时对*.js,*.jpg的访问也就被拦截了。-->
    <servlet-mapping>
        <servlet-name>spring-mvc</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    <!-- 配置session过期时间120分钟 -->
    <session-config>
        <session-timeout>120</session-timeout>
    </session-config>
    <!-- 配置字符集过滤器 -->
    <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>
    <!--配置错误页面-->
    <error-page>
        <error-code>404</error-code>
        <location>/WEB-INF/page/errors/error.jsp</location>
    </error-page>
    <error-page>
        <error-code>500</error-code>
        <location>/WEB-INF/page/errors/error.jsp</location>
    </error-page>
    <error-page>
        <error-code>414</error-code>
        <location>/WEB-INF/page/errors/error.jsp</location>
    </error-page>
    <error-page>
        <error-code>505</error-code>
        <location>/WEB-INF/page/errors/error.jsp</location>
    </error-page>
    <error-page>
        <error-code>400</error-code>
        <location>/WEB-INF/page/errors/error.jsp</location>
    </error-page>
    <error-page>
        <exception-type>java.lang.NullPointerException</exception-type>
        <location>/WEB-INF/page/errors/error.jsp</location>
    </error-page>
    <!-- Session过率器 -->
  <filter>
        <filter-name>sessionValidateFilter</filter-name>
        <filter-class>filter.SessionValidateFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>sessionValidateFilter</filter-name>
        <url-pattern>/page/*</url-pattern>
    </filter-mapping>
</web-app>
代码语言:javascript
复制
package filter;
​
import java.io.IOException;
​
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
​
public class SessionValidateFilter implements Filter{
​
    @Override
    public void destroy() {
        // TODO Auto-generated method stub
​
    }
​
    //是否从登陆页面过来的过滤
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        System.out.println("执行了");
        HttpServletRequest request =(HttpServletRequest)req;    //将req强转成HttpServletRequest就可以调用它的方法了
        HttpServletResponse response =(HttpServletResponse)resp;
        HttpSession session = request.getSession();
        if(session.getAttribute("name")!=null) {
            chain.doFilter(request,response);
        }else {
            response.sendRedirect("../login.jsp");
        }
    }
​
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub
​
    }
​
}
​

控制台中文乱码问题

打开idea安装目录,选择xxxxx.vmoptions 在下面加上-Dfile.encoding=UTF-8

打开IntelliJ IDEA>File>Setting>Editor>File Encodings,将Global Encoding、Project Encoding、Default encodeing for properties files这三项都设置成UTF-8

如果是web项目,在菜单栏找到run->Edit Configrations,设置 vm option为 -Dfile.encoding=utf-8

顺便说一句tomcat里的配置

on ‘update‘action选项 选择update classes and resources

如果出现out文件夹下内容与web下不一致,请重新配置tomcat

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2023-02-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Spring MVC体系结构和处理请求控制器
    • 基于注解的处理器
      • @Controller
        • @RequestMapping
          • @RequestParam
            • DispatcherServlet
              • ModelAndView
                • ViewResolver
                  • 框架特点
                    • 使用idea创建springmvc项目
                      • 控制台中文乱码问题
                      相关产品与服务
                      容器服务
                      腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
                      领券
                      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档