文章目录
前言
在前面的章节中,我们将jsp放置于webapp目录下,这种方式通过路径可以被访问到,不太安全,我们可以将其放置于WEB-INF目录下,这样就只能通过控制器或视图解析器来访问界面了,这种方式只做了解即可,因为这种模式下我们可以使用FreeMarker、Thymeleaf等。
一、视图解析器
1. DispatcherServlet.properties
springmvc内置了视图解析器,我们仅做配置即可
2. spring-mvc.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="org.example.springmvc"></context:component-scan>
<mvc:annotation-driven></mvc:annotation-driven>
<!--静态资源配置-->
<mvc:resources mapping="/**" location="/resources"></mvc:resources>
<!--视图解析器-->
<bean name="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
3. Controller
package org.example.springmvc.params.controller;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Create by zjg on 2024/4/29
*/
@Controller
public class ResourcesController {
@RequestMapping("hello-resources")
public String params(HttpServletRequest request){
System.out.println(request.getCharacterEncoding());
return "params/resources";
}
}
视图解析器对显式使用forward和redirect的会有影响,这里根据视图解析器前缀和后缀拼接路径即可,转发和重定向后面会有介绍
二、视图控制器
1.spring-mvc.xml
1.1 视图控制器
这一步相当于上面的Controller,直接输入index路径就可以访问的对应的视图
<!--视图控制器-->
<mvc:view-controller path="resources" view-name="params/resources"/>
1.2 重定向视图控制器
上面提到视图解析器不能对重定向生效,但是我们可以配置重定向控制器来达到这种效果。
<!--重定向视图控制器-->
<mvc:redirect-view-controller path="params.resources" redirect-url="resources"/>
1.3 Controller
package org.example.springmvc.params.controller;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Create by zjg on 2024/4/29
*/
@Controller
public class ResourcesController {
@RequestMapping("hello-resources")
public String params(HttpServletRequest request){
System.out.println(request.getCharacterEncoding());
return "redirect:params.resources";
}
}
这是一个歪点子,重定向要么把界面放置于webapp下,要么定义重定向控制器走转发访问到界面。