Spring mvc el 仅在 WEB-INF 中的 jsp 时工作



我刚刚学习了servlet,现在开始学习Spring MVC。我只是无法让我的头被这个包裹起来

普通的 jsp servlet 我使用 EL 访问 session.attribute,而不将 jsp 放在 WEB-INF 中,但是对于 Spring MVC,似乎我必须将 JSP 文件放在 WEB-INF 中才能让 EL 工作,为什么会这样? 还是我只是做错了什么?

示例 Servlet(工作示例):

索引.jsp

<form id="form" action="form-el" method="POST">
        <label for="firstName">First Name: </label>
        <input type="text" name="firstName">
        <button type="submit">Click Me</button>
</form>
<div id="result>
  <p>${name}
</div>

Servlet:

public class formServlet extends HttpServlet
{
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        String firstName = request.getParameter("firstName");
        String url ="/index.jsp";
        ServletContext cs = getServletContext();
        HttpSession session = request.getSession();
        session.setAttribute("firstName", firstName);
        session.setAttribute("lastName", lastName);
        cs.getRequestDispatcher(url).forward(request, response);
    }
}

弹簧:(工作示例)

文件结构:

|-WebContent
    |-WEB-INF
         |-html
             -index.jsp
         - offers-dispatcher-servlet.xml
         - web.xml 

索引.jsp

${name}

offers-dispatcher-servlet.xml

<context:component-scan base-package="com.caveofprogramming.pring.web.controllers">
</context:component-scan>
<mvc:annotation-driven></mvc:annotation-driven>
<mvc:resources mapping="/resources/**" location="/" />
<bean id="jspViewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/html/"></property>
<property name="suffix" value=".jsp"></property>
</bean>

控制器

@Controller

公共类 OffersController {

@RequestMapping("/")
public String showHome(HttpSession session){
    // Return logical name of the view to use. The actual job of figuring out
    // what view to load is something called "viewResolver"
    session.setAttribute("name", "Tim");
    return "index";
}

====

===============================

现在,如果我将索引.jsp移动到 WEB-INF 之外并更改 offers-dispatcher-servlet.xml

<bean id="jspViewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>  <!-- Change directory -->
<property name="suffix" value=".jsp"></property>
</bean>

新文件结构:

|-WebContent
    |-WEB-INF
         - offers-dispatcher-servlet.xml
         - web.xml
     -index.jsp 

这不再有效,返回空...有人可以帮忙解释一下吗? 谢谢。

将 JSP 放在 WEB-INF 之外是一个安全问题。恶意用户可以打开 http://yoursite.com/db.jsp 并从异常消息中获取有关应用程序(最差 - 数据库凭据)的一些见解。所以总是把jsp放在你的WEB-INF文件夹中

首先,

WEB-INF 资源可供 Web 应用程序的资源加载器访问,并且不直接对公众可见。

如果您使用 maven,则此项目将在构建 WAR 文件期间自动创建并填充此文件夹,并且仅在生成的 WAR 文件中可见

没有理由在 WEB-INF 文件夹之外找到 JSP 页面,因为它不安全。您可以为您的起始页(index.jsp)或其他静态资源(css,js文件)执行此操作。在这种情况下,您应该使用视图解析器将资源添加到上下文文件中,例如

<mvc:resources location="/js/" mapping="/js/**"/>

最新更新