0

I realise that this is basic. I am completely clueless and can't find any simple tutorial that is updated.

Using Spring 4.0 and Netbean's default stuff for Spring...

  1. How do I make the controller.DefaultController handle the GET & POST requests for the various URIs?

  2. How to make ${msg} appear?

applicationContext.xml

    <?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?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:p="http://www.springframework.org/schema/p"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">




    <context:annotation-config/>
    <context:component-scan base-package="learn"/>

    <bean id="test" class="learn.Test"></bean>

    <!--bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
          p:location="/WEB-INF/jdbc.properties" />

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource"
    p:driverClassName="${jdbc.driverClassName}"
    p:url="${jdbc.url}"
    p:username="${jdbc.username}"
    p:password="${jdbc.password}" /-->

    <!-- ADD PERSISTENCE SUPPORT HERE (jpa, hibernate, etc) -->

</beans>

dispatcher-servlet.html

<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?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:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>

    <!--
    Most controllers will use the ControllerClassNameHandlerMapping above, but
    for the index controller we are using ParameterizableViewController, so we must
    define an explicit mapping for it.
    -->
    <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="index.htm">indexController</prop>
                <prop key="index.htm">indexController</prop>
                <prop key="index">indexController</prop>
                <prop key="index.html">indexController</prop>
                <prop key="submitPage.html">indexController</prop>
            </props>
        </property>
    </bean>

    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp" />

    <!--
    The index controller.
    -->
    <bean name="indexController"
          class="org.springframework.web.servlet.mvc.ParameterizableViewController"
          p:viewName="index" />

<!--
Changing to this does not work. Why? What should I do?
<bean name="indexController"
      class="controller.DefaultController"/>
-->

</beans>

WEB-INF/jsp/index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Welcome to Spring Web MVC project</title>
    </head>

    <body>
        <p>Hello! This is the default welcome page for a Spring Web MVC project.</p>
        <p><i>To display a different welcome page for this project, modify</i>
            <tt>index.jsp</tt> <i>, or create your own welcome page then change
                the redirection in</i> <tt>redirect.jsp</tt> <i>to point to the new
                welcome page and also update the welcome-file setting in</i>
            <tt>web.xml</tt>.</p>

        <p>msg: ${msg}</p>

        <form action="/submitPage.html">
            <input type="text" id="zzz" name="zzz">
            <input type="submit" value="Submit!!">
        </form>
    </body>
</html>

src/controller/DefaultController

package controller;

import learn.Test;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class DefaultController {

   @RequestMapping(value = "/", method = RequestMethod.GET)
   public String index(ModelMap map) {

       map.put("msg", "/");
       return "grrr";
   }


   @RequestMapping(value = "/index", method = RequestMethod.GET)
   public String indexPure(ModelMap map) {

       map.put("msg", "/index");
       return "qwerty";
   }


   @RequestMapping(value = "/index.html", method = RequestMethod.GET)
   public String indexHTML(ModelMap map) {

       map.put("msg", "/index.html");
       return "asdfgh";
   }


   @RequestMapping(value="/submitPage.html", method=RequestMethod.POST)
   public @ResponseBody Object box(@RequestBody Test testRequest) {
       //Do stuff here
       return testRequest.getResult();
   }
}

src/learn/Test

package learn;
import org.springframework.stereotype.Component;
@Component
public class Test {
    private static final long serialVersionUID = 1000000;

    private String zzz;
        public String getZzz(){return zzz;}
        public void setZzz(String zzz){this.zzz = zzz;}

    public String getResult(){
        return "result = " + zzz;
    }
}

index.xhtml

<?xml version="1.0" encoding="UTF-8"?>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<%@ page language="java" session="false" contentType="text/html;charset=utf-8" %>
<jsp:forward page='index.html'/>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>TODO supply a title</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    </head>
    <body>
        <div>TODO write content</div>
    </body>
</html>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" 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_3_1.xsd">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.xhtml</welcome-file>
    </welcome-file-list>
</web-app>

Files: LearnSpring

theAnonymous
  • 1,701
  • 2
  • 28
  • 62
  • did you enable in your applicationContext.xml? Note that you never defined your DefaultController in your xml file so spring will never register this class as a bean – roy Apr 20 '17 at 10:37
  • No, that file is still at the default. How do I enable it? – theAnonymous Apr 20 '17 at 10:39
  • 1
    Check this article http://techidiocy.com/annotation-config-vs-component-scan-spring-core/ and this answer http://stackoverflow.com/a/7456501/6877737 – roy Apr 20 '17 at 10:44
  • I have made some changes, but am still unable to display the custom messages. If I change the controller class to my own controller, everything would be 404. – theAnonymous Apr 20 '17 at 12:28
  • what are grrr, qwerty, asdfgh names? – Gurkan Yesilyurt Apr 23 '17 at 11:54

1 Answers1

1

You are mixing XML configuration and annotation based configuration of Handler Mappings, that is possible but must be done with care, at the moment they overlap and is hard to say what is happening. I suppose you started with an example using XML and continued with some annotation based code. I dont' understand yet what does submitPage, I will refactor to a basic example get-post with only one mapping, /index.html, declared with annotations.

The applicationContext.xml can stay empty

The dispatcherServlet.xml must contain two beans only:

       <bean name="indexController" class="controller.DefaultController"/>
       <bean id="viewResolver"
         class="org.springframework.web.servlet.view.InternalResourceViewResolver"
         p:prefix="/WEB-INF/jsp/"
         p:suffix=".jsp" />

ParameterizableViewController, that is used only for very simple pages, is not needed. Also the mappings of SimpleUrlHandlerMapping are not needed: the handler mappings are now defined only by the annotations in the controller.

The DefaultController may become:

@Controller
public class DefaultController {

   @RequestMapping(value = "/index.html", method = RequestMethod.POST)
   public String indexPure(ModelMap map, HttpServletRequest request) {

       final String zzz = request.getParameter("zzz");
       map.put("msg", "You sent [" + zzz + "]");
       return "index";
   }


   @RequestMapping(value = "/index.html", method = RequestMethod.GET)
   public String indexHTML(ModelMap map) {

       map.put("msg", "Please send something");
       return "index";
   }

}

In these controller method the return value is the view name while the model is used to pass the msg to the view. Give a look to @RequestMapping Javadoc for a list of other parameters supported.

In the JSP page:

  • the method='post' is missing.
  • you cannot use /submitPage.html or /index.html because the URL must be resolved relatively to context-path, use

    <form method='post' action="<c:url value='/index.html'/>">
    
  • use <c:out value='${msg}'/> to html-escape the message

To use <c: tags declare at top, after the <%@page directive:

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

Then the index.xhtml page should be replaced with index.jsp containing:

        <%@ page
    language="java"
    session="false"
    contentType="text/html;charset=utf-8" %>
<jsp:forward page='index.html'/>

You might have problems in running JSP depending on the servlet version declared in web.xml If this is the case give more infos about web.xml and pom.xml

In web.xml pattern is wrong

   <url-pattern>*.htm</url-pattern>

use

  <url-pattern>/</url-pattern>

Not sure about using redirect.jsp as welcome page, use

    <welcome-file-list>
     <welcome-file>index.jsp</welcome-file>
     <welcome-file>index.html</welcome-file>
    </welcome-file-list>

and use index.jsp to forward or add index.xhtml to the list

Testo Testini
  • 2,200
  • 18
  • 29
  • Hi, I really appreciate your long and detailed answer. However, I am getting 404 error messages. I have updated the qn with web.xml and index.xhtml, please take a look and let me know what I'm doing wrong. Thanks. – theAnonymous Apr 27 '17 at 02:04
  • Hi, I have updated the project but it's still showing 404 at `http://localhost:8080/TestSpring/WEB-INF/jsp/index.jsp` – theAnonymous Apr 28 '17 at 01:37
  • Hello, thanks for your patience. `/TestSpring/index.html`, `/TestSpring/index.jsp`, `/TestSpring/index.html`, `/TestSpring/WEB-INF/jsp/index.html` and `/TestSpring/WEB-INF/jsp/index.jsp` returns the 404 error. – theAnonymous Apr 28 '17 at 03:00
  • try my project, that in my machine works, use import project / maven https://ufile.io/rgnfp – Testo Testini Apr 28 '17 at 04:02
  • Ah I forgot..is an eclipse project.. I dont have netbeans.. but perhaps just replacing the files on (a copy of) your project may work – Testo Testini Apr 28 '17 at 04:22
  • 1
    Works on Eclipse, not on Netbeans.......... Not sure what's happening. Thanks for the project. – theAnonymous Apr 28 '17 at 06:20