简体   繁体   中英

How to add a front end to Spring MVC

I was following this tutorial to make a simple MVC Spring project that accesses data with JPA .

Now I would like to add a front end, probably as a JSP page.

Before I just made a Dynamic Web App that contained web folder and I just defined servlet-url mapping in the web.xml . See pic below:

在此处输入图片说明

However now, the project structure is different and I can't find any good reference to how to include Web Content in the Spring project.

在此处输入图片说明

It looks like you now are using a maven project. Web files are in src/main/webapp by default with maven projects.

So put the WEB-INF, jsp files etc in there, and normally you are good to go.

See also https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html

That tutorial uses Spring Boot to kickstart Spring MVC project. You are doing it manually. Therefore, you will need view resolver bean definition. Put your JSP's in WEB-INF folder and add this bean definition:

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

Or if you are doing it via annotations:

@Bean
public InternalResourceViewResolver internalResourceViewResolver (){
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/");
        resolver.setSuffix(".jsp");
        return resolver;
}

Also, probably worth of mentioning, if you are actually using Spring Boot to kickstart Spring MVC project and if you want to use like Thymeleaf template engine, then you don't even have to create view resolver bean definition. Spring Boot will scan your classpath and create default internal view resolver for Thymeleaf .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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