项目中有使用重定向访问,尝试用重定向访问不同目录下的.jsp文件
重定向访问webapp下的不同jsp文件如下:
1、webapp/redirect.jsp的写法:
//方法1:使用response重定向
response.sendRedirect(request.getContextPath()+"/redirect.jsp");
//方法2:配置视图解析器重定向,视图解析器代码在最后
return "redirect:/redirect.jsp";
2、webapp/test/testOne.jsp的写法:
//方法1:使用response重定向
response.sendRedirect(request.getContextPath()+"/test/testOne.jsp");
//方法2:配置视图解析器重定向,视图解析器代码在最后
return "redirect:/test/testOne.jsp";
3、webapp/WEB-INF/pages/success.jsp的写法:
在尝试很多次路径的写法后,发现webapp/WEB-INF下的文件访问不了,会报404错误:
Description:The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
那我浏览器直接访问呢?同样404,同样的Description。
发现是被服务器保护了,WEB-INF是Java的WEB应用的安全目录。也就是客户端无法访问,只有服务端可以源访问的目录。
重定向是两次不同请求,而且是在客户端完成的。
解决方法:
客户端想要访问WEB-INF下的文件,需要配置web.xml
<servlet>
<servlet-name>success</servlet-name>
<jsp-file>/WEB-INF/pages/success.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>success</servlet-name>
<url-pattern>/success</url-pattern>
</servlet-mapping>
在浏览器输入http://localhost:8080/success 直接回车,可以访问到,
所以,在配置好web.xml之后,就可以重定向到WEB-INF下的文件了,
重定向的写法:
//方法1:使用response重定向
response.sendRedirect(request.getContextPath()+"/success");
//方法2:配置视图解析器重定向,视图解析器代码在最后
return "redirect:/success";
成功进入。
----------------------------------------分割线---------------------------------------
方法2中的视图解析器代码:
springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="cn.tds"></context:component-scan>
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="suffix" value=".jsp"/>
</bean>
<mvc:annotation-driven></mvc:annotation-driven>
</beans>