.pagina jsp forma POST con @Requestmapping tramite la Molla non funziona

Quando provo a chiamare il mio post di form in una pagina jsp utilizzando un pulsante invia la pagina sembra essere il ricarico, ma nulla di ciò che accade nel mio @Requestmapping metodo viene chiamato.

Questa è la Primavera-annotato con metodo java:

 @RequestMapping(value = "/TimeTracking.jsp", method = RequestMethod.POST)
    public String changeTheWeek(HttpServletRequest request) {

      if ("Previous Week".equals(request.getParameter("changeWeek"))) {
          this.subtractOneWeek();
      } if ("Next Week".equals(request.getParameter("changeWeek")))
      {
        this.addOneWeek();  
      }

        return "redirect:TimeTracking.jsp";
    }

Qui è la pagina jsp forma:

<form name="ChangeWeek" method="POST" action="TimeTracking.jsp">
        <span> <input name="changeWeek" type="submit" value="Previous Week"/> Hours for the week of
            <%=currentWeek.firstDayOfThisWeek()%> until <%=currentWeek.lastDayOfThisWeek()%>
            <input name="changeWeek" type="submit" value="Next Week"/>
        </span>
</form>

Ecco il mio spring-servlet.xml file:

<?xml version="1.0" encoding="windows-1252"?>
<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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" 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-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd
   http://www.springframework.org/schema/mvc
   http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
   http://www.springframework.org/schema/tx
   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

<!-- Use @Component annotations for bean definitions -->
<context:component-scan base-package="controllers, daos, map, models, session, testControllers"  scoped-proxy="targetClass" />
<!-- added this because I think it makes annotations work? -->
<context:annotation-config />

<!-- Use @Controller annotations for MVC controller definitions -->
<mvc:annotation-driven />

<bean
    class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"
    lazy-init="false" />

<!-- Add JPA support -->
<bean id="emf"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" lazy-init="false" >
    <property name="persistenceUnitName" value="SpaceTime" />
    <property name="jpaDialect" ref="jpaDialect" />
    <property name="jpaVendorAdapter" ref="jpaAdapter" />
    <property name="loadTimeWeaver">
        <bean
            class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
    </property>
</bean>
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"
    lazy-init="false" />
<bean id="jpaAdapter"
    class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
    lazy-init="true">
    <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
    <property name="database" value="MYSQL" />
    <property name="showSql" value="false" />
</bean>
<!-- Ref: http://static.springsource.org/spring/docs/2.5.x/reference/metadata.html#metadata-annotations-required -->
<bean
    class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor" />
<bean id="myDataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://192.168.0.44:3306/userexample" />
    <property name="username" value="nathan" />
    <property name="password" value="nathan" />
</bean>
<!-- Add Transaction support -->
<bean id="myTxManager" class="org.springframework.orm.jpa.JpaTransactionManager" lazy-init="false" >
    <property name="entityManagerFactory" ref="emf" />  
</bean>

<!-- Use @Transaction annotations for managing transactions -->
<tx:annotation-driven transaction-manager="myTxManager"
    proxy-target-class="false" />
<!-- View resolver -->
<bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/" />
    <!-- <property name="suffix" value=".jsp"/> -->
</bean>
<!-- Use @Transaction annotations for managing transactions -->
<tx:annotation-driven transaction-manager="myTxManager" />

</beans>

Ecco il web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
 <servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
  org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>jsp-pages/LogIn.jsp</welcome-file>
</welcome-file-list>
</web-app>

Qui l’intera classe java (e non solo il metodo)

package controllers;

import javax.servlet.http.HttpServletRequest;

import models.CurrentWeek;
import models.User;

import org.joda.time.MutableDateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

/**
 * this is the controller for current week, it lets you change the current week
 * and get values from the current week
 * 
     * @author CorayThan
 * 
 */
@Controller
public class CurrentWeekController {

@Autowired
private User user;

@Autowired
private CurrentWeek currentWeek;

/**
 * @return the user
 */
public User getUser() {
    return user;
}

/**
 * @param user the user to set
 */
public void setUser(User user) {
    this.user = user;
}

/**
 * @return the currentWeek
 */
public CurrentWeek getCurrentWeek() {
    if (currentWeek==null) {
        this.createNewCurrentWeek();
    }
    return currentWeek;
}

/**
 * @param currentWeek the currentWeek to set
 */
public void setCurrentWeek(CurrentWeek currentWeek) {
    this.currentWeek = currentWeek;
}

/**
 * no arg constructor
 */
public CurrentWeekController() {

}

/**
 * this is a post method called when a button is clicked on the time tracking
 * jsp page. It reloads the page with a different week
 * @param pageWeek
 * @param request
 * @return
 */

  @RequestMapping(value = "/TimeTracking.jsp", method = RequestMethod.POST)
    public String changeTheWeek(HttpServletRequest request) {

      if ("Previous Week".equals(request.getParameter("changeWeek"))) {
          this.subtractOneWeek();
      } if ("Next Week".equals(request.getParameter("changeWeek")))
      {
        this.addOneWeek();  
      }

        return "redirect:TimeTracking.jsp";
    }

/**
 * this is the default method to show the time tracking page
 * @return
 */
// @RequestMapping(value = "/TimeTracking.jsp")
//   public ModelAndView showTimeTracking() {
//       
//       return new ModelAndView("/TimeTracking.jsp", "command", this.getCurrentWeek());
//   }

/**
 * This creates a current week object by accepting a calendar. If that
 * calendar is set to Saturday, it will set all the days in that current
 * week object as calendars otherwise it will set all the days in that week
 * starting with the current day and counting back to Monday (the first day
 * of the week)
 * 
 * @param calendar
 * @return
 */
public CurrentWeek createCurrentWeek(MutableDateTime theCurrentDate) {

    int day = checkForNull(theCurrentDate);

    switch (day) {

    case 7:
        MutableDateTime sunday = (MutableDateTime) theCurrentDate.clone();
        this.getCurrentWeek().setSunday(sunday);
        theCurrentDate.addDays(-1);
        day--;
    case 6:
        MutableDateTime saturday = (MutableDateTime) theCurrentDate.clone();
        this.getCurrentWeek().setSaturday(saturday);
        theCurrentDate.addDays(-1);
        day--;
    case 5:
        MutableDateTime friday = (MutableDateTime) theCurrentDate.clone();
        this.getCurrentWeek().setFriday(friday);
        theCurrentDate.addDays(-1);
        day--;
    case 4:
        MutableDateTime thursday = (MutableDateTime) theCurrentDate.clone();
        this.getCurrentWeek().setThursday(thursday);
        theCurrentDate.addDays(-1);
        day--;
    case 3:
        MutableDateTime wednesday = (MutableDateTime) theCurrentDate
                .clone();
        this.getCurrentWeek().setWednesday(wednesday);
        theCurrentDate.addDays(-1);
        day--;
    case 2:
        MutableDateTime tuesday = (MutableDateTime) theCurrentDate.clone();
        this.getCurrentWeek().setTuesday(tuesday);
        theCurrentDate.addDays(-1);
        day--;
    case 1:
        MutableDateTime monday = (MutableDateTime) theCurrentDate.clone();
        this.getCurrentWeek().setMonday(monday);
        break;
    default:
        this.setCurrentWeek(null);
        break;

    }
    return this.getCurrentWeek();

}

/**
 * @param theCurrentDate
 * @return
 */
private int checkForNull(MutableDateTime theCurrentDate) {
    int day = 0;
    if (theCurrentDate != null) {
        day = theCurrentDate.getDayOfWeek();
    }
    return day;
}

/**
 * makes a new current week
 * 
 * @return
 */

public CurrentWeek createNewCurrentWeek() {
    MutableDateTime dateTime = MutableDateTime.now();
    CurrentWeek currentWeek = new CurrentWeek();
    this.setCurrentWeek(currentWeek);

    return createCurrentWeek(dateTime);
}

/**
 * subtracts one week from a currentweek
 * 
 * 
 * @return
 */
public void subtractOneWeek() {

    MutableDateTime newMonday = (MutableDateTime) this.getCurrentWeek().getMonday().clone();
    newMonday.addDays(-7);

    this.setCurrentWeek(createCurrentWeek(newMonday));


}

/**
 * adds one week to a currentweek
 * 
 * @param currentWeek
 * @return
 */
public void addOneWeek() {

    MutableDateTime newMonday = (MutableDateTime) this.getCurrentWeek().getMonday().clone();
    newMonday.addDays(7);

    this.setCurrentWeek(createCurrentWeek(newMonday));
}

/**
 * TODO: make this method into a method that accepts a current week and
 * checks if you can add a week to it without going entirely into the future
 * 
 * @param currentWeek
 * @return
 */
public CurrentWeek checkIfCurrentWeekIsEntirelyInFuture() {
    return this.getCurrentWeek();

}

/**
 * returns the first day of the week as a date time
 * 
 * @return
 */

public String firstDayOfThisWeek() {

    MutableDateTime firstDay = (MutableDateTime) this.getCurrentWeek().getMonday().clone();
    firstDay.addDays(-1);

    DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("MM/dd/yyyy");

    return dateFormatter.print(firstDay);
}

/**
 * returns the last day of this week as a date time
 * 
 * @return
 */

public String lastDayOfThisWeek() {


    MutableDateTime firstDay = (MutableDateTime) this.getCurrentWeek().getMonday().clone();
    firstDay.addDays(5);

    DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("MM/dd/yyyy");

    return dateFormatter.print(firstDay);
}

}

E, infine, qui è pieno TimeTracking.pagina jsp che la forma è in:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<jsp:useBean id="timeTracking"
class="controllers.TimeTrackingController" scope="request" />
<jsp:useBean id="currentWeek" class="controllers.CurrentWeekController"
scope="request" />
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Time Tracking Page</title>
<script type="text/javascript" src= "../javascriptpages/timeTracking.js"></script>

</head>

<body>

<div>
    <h1>User Time Tracking Page</h1>
</div>
<div id="content">

<form name="ChangeWeek" method="POST" action="TimeTracking.jsp">
        <span> <input name="changeWeek" type="submit" value="Previous Week"/> Hours for the week of
            <%=currentWeek.firstDayOfThisWeek()%> until     <%=currentWeek.lastDayOfThisWeek()%>
            <input name="changeWeek" type="submit" value="Next Week"/>
        </span>
</form>


        <table border="1">
            <tr>
                <th>Sunday</th>
                <th>Monday</th>
                <th>Tuesday</th>
                <th>Wednesday</th>
                <th>Thursday</th>
                <th>Friday</th>
                <th>Saturday</th>
            </tr>
            <tr>
                    <td><%=timeTracking.totalWorkTimeForOneDate(currentWeek.getCurrentWeek().getSunday())%>    </td>
                <td><%=timeTracking.totalWorkTimeForOneDate(currentWeek.getCurrentWeek().getMonday())%></td>
                <td><%=timeTracking.totalWorkTimeForOneDate(currentWeek.getCurrentWeek().getTuesday())%></td>
                <td><%=timeTracking.totalWorkTimeForOneDate(currentWeek.getCurrentWeek().getWednesday())%></td>
                <td><%=timeTracking.totalWorkTimeForOneDate(currentWeek.getCurrentWeek().getThursday())%></td>
                <td><%=timeTracking.totalWorkTimeForOneDate(currentWeek.getCurrentWeek().getFriday())%></td>
                <td><%=timeTracking.totalWorkTimeForOneDate(currentWeek.getCurrentWeek().getSaturday())%></td>
            </tr>
        </table>

        <input type="button" value="<%=timeTracking.displayClockButton()%>"
            onClick="clockInOrOutReloadPage()">

</div>

</body>
</html>
InformationsquelleAutor CorayThan | 2012-08-07



3 Replies
  1. 4

    Nel web.xml hai mappatura per *.l’estensione html, durante il tentativo di accedere la pagina che viene mappata come .jsp.

    È necessario modificare la mappatura per

    @RequestMapping(valore = “TimeTracking”)

    e correggere l’azione del form html per action ="TimeTracking.html"

    Inoltre, se siete nuovi a Spring MVC e si desidera utilizzare le sue caratteristiche, si prega di controllare Spring MVC Vetrina demo http://blog.springsource.org/2010/07/22/spring-mvc-3-showcase/

    • Così ho fatto quelle modifiche, ma ancora non funziona. Quando faccio clic sul pulsante di invio mi da un errore 404 “RequestURI=/SpaceTime/jsp-pages/TimeTracking.html” Ma anche se cambio la richiesta mappata metodo per non restituire il tempo di monitoraggio pagina a tutti ancora dice che non può risolvere il monitoraggio in tempo pagina!
    • Non si entra metodo controller?(è possibile impostare un punto di interruzione in modalità di debug)
    • Ho provato, e non mi sembra di entrare in mio controller metodo a tutti. Così deve essere la mia jsp forma che è scritto in modo non corretto?
    • La cosa più semplice da fare è sostituire il posr con il metodo get e tenta di aprire la pagina dal browser per vedere che è mappata correttamente – è possibile configurare lo strumento per org.springframework spazio dei nomi a livello di DEBUG, il più hardocore metodo è quello di impostare un punto di interruzione nella primavera DispatcherServlet classe
    • Sembra che l’indirizzo che si forma deve essere preceduto ..\ in altre parole non si deve accedere primavera controllato pagine tramite jsp-pagine sub percorso a tutti!
    • Ho provato a modificarlo per OTTENERE, ma ora, quando ho costruito il progetto maven dà l’errore: “Ago 07, 2012 11:40:31 AM org.springframework.web.servlet.DispatcherServlet noHandlerFound ATTENZIONE: Nessuna mappatura trovato per richiesta HTTP con URI [/SpaceTime/jsp-pages/TimeTracking.html] in DispatcherServlet con il nome di ‘primavera’”
    • vedi commento precedente è /SpaceTime/TimeTracking.html
    • dopo il tuo metodo funziona nel browser per tornare al post, corretto jsp forma, se necessario, in modo che il tuo metodo è eseguita, se il metodo viene eseguito, ma dopo il ritorno alla visualizzazione del nome dà errore 404, quindi controllare il vostro nome e ViewResolver configurazione
    • Penso che potrebbe in realtà essere sempre da qualche parte ora! Ora mi sto un altro errore: “java.lang.IllegalStateException: Nessun Ambito registrati per l’ambito ‘Sessione'” che credo abbia qualcosa a che fare con una fava io con scope di Sessione
    • grazie mille Boris! Penso di si può prendere da qui. Sembra essere stato il tentativo di accedere alla primavera controllato pagina tramite jsp-pagine.
    • provare sessione invece di Sessione, ma in realtà io sono su uno smartphone non può aiutare)))

  2. 0

    url modello è *.html. Quindi, cambiare la tua azione per TimeTracking.html. E modifica la tua richiesta di mappatura per /TimeTracking.html

  3. 0

    Modificare il web.xml url-pattern di primavera servlet a * o modificare il nome dell’azione TimeTracking.html e anche requestmapping valore dell’attributo /TimeTracking.html. Dalla pagina jsp quello che ho capito è che stiamo usando input di tipo pulsante, invece di presentare e c’è un evento sul pulsante inoltre, provare a cambiare il tipo di input per presentare con il nome di azione e requestmapping’ valore di attributo modificato TimeTracking.html.

Lascia un commento