简体   繁体   English

在Spring中将.jsp映射到Controller

[英]Mapping a .jsp to a Controller in Spring

I am just starting with spring so I started with a SpringMVC on Heroku. 我刚刚从春天开始,所以我开始在Heroku上使用SpringMVC。 By choosing the Spring MVC Template in Eclipse I got a very basic Application. 通过在Eclipse中选择Spring MVC模板,我得到了一个非常基本的应用程序。 Now I am trying to modify this. 现在我想修改这个。

However if I create another .jsp and I visit the URL given in the Controller I get an 404, that's pretty clear, because I never mapped the Controller to the .jsp . 但是,如果我创建另一个.jsp并访问Controller中给出的URL,我会得到一个404,这很清楚,因为我从未将Controller映射到.jsp But how should I do this? 但是我该怎么做呢?

Here is everything I changed (Even if I'm not sure that you will need it): 这是我改变的一切(即使我不确定你是否需要它):

The Controller: 控制者:

@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";
    }

}

The Entity: 实体:

@Entity
public class Booking {

    @Id
    @GeneratedValue
    private Integer id;


// Lots of getters setters an attributes ...

}

The Service: 服务:

@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: 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: 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: 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>

return "NumAvailableBikes"; 返回“NumAvailableBikes”; should be changed to return "booking"; 应改为返回“预订”;

First consider how your dispatcher servlet is configured. 首先考虑如何配置调度程序servlet。 Currently it is mapped to the following url pattern: 目前它映射到以下url模式:

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

This means that only urls which contain the booking directory directly after the context root will be mapped. 这意味着只会映射在上下文根之后直接包含booking目录的URL。 So a url like `contextroot/AvailableBikes' will never get picked up and processed by the dispatcher. 所以像'contextroot / AvailableBikes'这样的网址永远不会被调度员接收和处理。 I would recommend changing your url pattern to: 我建议将您的网址格式更改为:

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

This mapping serves as almost a catch all mapping. 此映射几乎可以捕获所有映射。 It will match all urls which are not mapped to another servlet. 它将匹配未映射到另一个servlet的所有URL。 Please note: it will also create the need for you to setup configuration to map static resources such as css and js files. 请注意:它还将使您需要设置配置以映射静态资源,如css和js文件。 This is explained in the Spring documentation. 这在Spring文档中有解释。

Once you have made this change I think you should be able to hit the Controller with a URL like rootcontext/AvailableBikes . 一旦你做了这个改变,我认为你应该能够使用像rootcontext/AvailableBikes这样的URL命中Controller。 Setup a debug point in the controller to confirm. 在控制器中设置调试点以进行确认。 Also note that you will not use a url containing a direct path to the .jsp file but the path specified in the request mapping. 另请注意,您不会使用包含.jsp文件的直接路径的URL,而是使用请求映射中指定的路径。 Your jsp file should be available @ webcontent directory/WEB-INF/jsp/NumAvailableBikes.jsp . 您的jsp文件应该可用@ webcontent directory/WEB-INF/jsp/NumAvailableBikes.jsp

In order to display the booking.jsp which should be available @ webcontent dir/WEB-INF/jsp/booking.jsp the controller must be modified to return the String booking. 为了显示应该可用的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";
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM