在Spring中将.jsp映射到Controller

时间:2013-01-16 10:32:55

标签: java spring spring-mvc heroku

我刚刚从春天开始,所以我开始在Heroku上使用SpringMVC。通过在Eclipse中选择Spring MVC模板,我得到了一个非常基本的应用程序。现在我试图修改它。

但是,如果我创建另一个.jsp并访问Controller中给出的URL,我会得到一个404,这很清楚,因为我从未将Controller映射到.jsp。但是我应该怎么做呢?

以下是我改变的一切(即使我不确定你是否需要它):

控制器:

@Controller
public class BookingController {

    @Autowired
    BookingService bookingService;

    @RequestMapping("/AvailableBikes")
    public String getAvailableBikes(Model model){
        // TOOD: Fix Date
        int availableBookings = bookingService.getAvailableBookings(Calendar.getInstance().getTime());
        model.addAttribute("NumAvailableBikes", Integer.toString(availableBookings));

        return "NumAvailableBikes";
    }

}

实体:

@Entity
public class Booking {

    @Id
    @GeneratedValue
    private Integer id;


// Lots of getters setters an attributes ...

}

服务:

@Service
public class BookingServiceImpl implements BookingService {

    @Override
    public void addBooking(Booking booking) {
        // TODO Auto-generated method stub

    }

    @Override
    public int getAvailableBookings(Date bookingDay) {
        // TODO Auto-generated method stub
        return 12;
    }

    @Override
    public void removeBooking(Booking booking) {
        // TODO Auto-generated method stub
    }

}

booking.jsp:

<!doctype html>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<html>
<head>
    <meta charset="utf-8">
    <title>Spring MVC and Hibernate Template</title>

    <meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css" rel="stylesheet">
    <link href="http://twitter.github.com/bootstrap/assets/css/bootstrap-responsive.css" rel="stylesheet">

</head>

<body>

Test!

<h2>${NumAvailableBikes}</h2>

</body>

的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"
    id="WebApp_ID" version="2.5">
    <display-name>Spring-Hibernate-Template</display-name>

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

    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/booking/*</url-pattern>
    </servlet-mapping>
</web-app>

的applicationContext.xml:

<?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:jdbc="http://www.springframework.org/schema/jdbc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
                           http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:annotation-config />
    <context:component-scan base-package="org.stuttgart.fahrrad" />

    <mvc:annotation-driven/>

    <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <tx:annotation-driven />
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
        <property name="dataSource" ref="dataSource"/>

    </bean>

    <beans profile="default">
        <jdbc:embedded-database id="dataSource"/>        
        <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <property name="jpaVendorAdapter">
                <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
            </property>
            <property name="jpaProperties">
                <props>
                    <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
                    <prop key="hibernate.hbm2ddl.auto">create</prop>
                </props>
            </property>
        </bean>
    </beans>

    <beans profile="prod">
        <bean class="java.net.URI" id="dbUrl">
            <constructor-arg value="#{systemEnvironment['DATABASE_URL']}"/>
        </bean>

        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
            <property name="url" value="#{ 'jdbc:postgresql://' + @dbUrl.getHost() + @dbUrl.getPath() }"/>
            <property name="username" value="#{ @dbUrl.getUserInfo().split(':')[0] }"/>
            <property name="password" value="#{ @dbUrl.getUserInfo().split(':')[1] }"/>
        </bean>

        <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <property name="jpaVendorAdapter">
                <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
            </property>
            <property name="jpaProperties">
                <props>
                    <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
                    <prop key="hibernate.show_sql">true</prop>
                    <!-- change this to 'verify' before running as a production app -->
                    <prop key="hibernate.hbm2ddl.auto">update</prop>
                </props>
            </property>
        </bean>
    </beans>

</beans>

2 个答案:

答案 0 :(得分:3)

返回“NumAvailableBikes”;应该改为返回“预订”;

答案 1 :(得分:2)

首先考虑如何配置调度程序servlet。目前它映射到以下url模式:

<servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/booking/*</url-pattern>
</servlet-mapping>

这意味着只会映射在上下文根之后直接包含booking目录的URL。所以像'contextroot / AvailableBikes'这样的网址永远不会被调度员接收和处理。我建议将您的网址格式更改为:

<servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

这种映射几乎可以捕获所有映射。它将匹配未映射到另一个servlet的所有URL。请注意:它还将使您需要设置配置以映射静态资源,如css和js文件。这在Spring文档中有解释。

完成此更改后,我认为您应该可以使用rootcontext/AvailableBikes之类的网址点击Controller。在控制器中设置调试点以进行确认。另请注意,您不会使用包含.jsp文件的直接路径的URL,而是使用请求映射中指定的路径。您的jsp文件应该在webcontent directory/WEB-INF/jsp/NumAvailableBikes.jsp

为了显示@ booking.jsp应该可用的webcontent dir/WEB-INF/jsp/booking.jsp,必须修改控制器以返回String预订。

   @RequestMapping("/AvailableBikes")
    public String getAvailableBikes(Model model){
        // TOOD: Fix Date
        int availableBookings = bookingService.getAvailableBookings(Calendar.getInstance().getTime());
        model.addAttribute("NumAvailableBikes", Integer.toString(availableBookings));

        return "booking";
    }