I just learned servlet and now getting to learning Spring MVC. I just couldn't get my head wrapped around this
Normal jsp servlet I use EL to access session.attribute without putting jsp within WEB-INF, but with Spring MVC it seems like I have to put JSP file within WEB-INF for EL to work why is this? or am I just doing something wrong?
Example Servelet (Working example):
Index.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);
}
}
Spring: (Working example)
File structure:
|-WebContent
|-WEB-INF
|-html
-index.jsp
- offers-dispatcher-servlet.xml
- web.xml
Index.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
@Controller
public class 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";
}
=============================
Now if I move index.jsp outside of WEB-INF and change 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>
New File structure:
|-WebContent
|-WEB-INF
- offers-dispatcher-servlet.xml
- web.xml
-index.jsp
This no longer works, returns null... could someone help to explain? Thank you.
WebContent
), and changed prefix of ViewResolver, it has to work. Check did you deployment tool does copied thisindex.jsp
into root of application. – Ken Bekov