I use spring boot to do a simple web page.
Here are the codes:
src/main/java/Application.java
#SpringBootApplication
public class Application
{
public static void main(String[] args)
{
SpringApplication.run(Application.class, args);
}
}
src/mian/java/Config.java
#Configuration
#EnableWebMvc
public class Config extends WebMvcConfigurerAdapter
{
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer)
{
configurer.enable();
}
#Bean
public InternalResourceViewResolver viewResolver()
{
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
}
src/main/java/TestController.java
#Controller
public class TestController
{
String name = "Peter!";
#RequestMapping("/test")
public String admin(ModelAndView mv)
{
System.out.println("in controller");
mv.addObject("name", name);
return "test";
}
}
src/main/webapp/WEB-INF/views/test.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
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>Just for test</title>
</head>
<body>
${name}
</body>
</html>
I start the project from the Application.java,
and put http://localhost:8080/test in the browser,
but the browser just show the source code of test.jsp.
It seems spring boot treat jsp as txt file...
How to fix it?
add this dependency to your pom.xml
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<scope>provided</scope>
</dependency>
Related
I have a controller
#Controller
public class FirstController {
#GetMapping("/hello")
public String helloPage(#RequestParam("name") String name,
Model model){
model.addAttribute("message", name);
return "first/hello";
}
}
And view hello.html
<!doctype html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1>Hello world!</h1>
<p th:text="${message}"></p>
</body>
</html>
I enter the required parameters: http://localhost:8080/hello?name=Tom
But all that the page displays is "Hello world!"
P.S. I'm working with spring core and therefore I had to write the configs by hand, here's what is in the configs:
#Configuration
#ComponentScan("com.nosferat.springapp")
#EnableWebMvc
public class SpringConfig implements WebMvcConfigurer {
#Bean
public ViewResolver viewResolver() {
var viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".html");
return viewResolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
Maybe it has something to do with the config
Why do you have a return "first/hello"? you should use return "hello", by the way this may be the answer to your question
i also highly suggest you to use Spring boot so your life will be easier
When I go to http://localhost:8080/ for my spring boot form it just gives me a whitelabel error page. This is my Controller code
package net.codejava;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class MvcController {
#RequestMapping("/")
public String home() {
System.out.println("Going home...");
return "index";
}
}
and here's my index.jsp code
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Volunteer Management Form</title>
</head>
<body>
<h1>Volunteer Management Form</h1>
</body>
</html>
I cannot work out why it won't show I do however get "Going home..." printed in the console
i think that you have problem with the view resolver add this to your application.properties:
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
and move your index.jsp to /WEB-INF/jsp/
the second method is to set resolver by using WebConfig class like that :
add this class to your source package :
#EnableWebMvc
#Configuration
#ComponentScan("net.codejava")
public class WebConfig implements WebMvcConfigurer {
#Bean
public ViewResolver internalResourceViewResolver() {
InternalResourceViewResolver bean = new
InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
return bean;
}
}
update 16/03/2022
there is some problems with the the newer versions of Spring boot so we should add this been also like the following :
#Configuration
#EnableWebMvc
#ComponentScan
public class MvcConfig extends WebMvcConfigurerAdapter {
#Bean
WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>
enableDefaultServlet() {
return (factory) -> factory.setRegisterDefaultServlet(true);
}
#Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver resolver = new
InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/view/");
resolver.setSuffix(".html");
return resolver;
}
#Override
public void
configureDefaultServletHandling(DefaultServletHandlerConfigurer
configurer) {
configurer.enable();
}
}
Not sure how did you setup JSP on spring boot because there's some specific dependencies that you need to have. Also, people nowadays use Thymeleaf or Freemarker for templating instead of JSP on spring boot. I was able to follow and run the github project from https://www.baeldung.com/spring-boot-jsp with these urls
http://localhost:8080/spring-boot-jsp/book/viewBooks
http://localhost:8080/spring-boot-jsp/book/addBook
I am trying to create a sample Spring MVC project but static file are not getting loaded.I am getting below mentioned error.
http://localhost:8080/BPMEI/static/css/bootstrap.css Failed to load resource: the server responded with a status of 404 (Not Found)
I will be grateful if someone can help me out to fix this issue.
Project Structure
Configuration Code
package com.dgsl.bpm.configuration;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.dgsl.bpm")
public class WebConfiguration extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("/");
}
}
Initializer code
package com.dgsl.bpm.configuration;
public class WebInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebConfiguration.class);
ctx.setServletContext(container);
ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
}
JSP Code
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Student Enrollment Form</title>
<link href="<c:url value='/static/css/bootstrap.css' />" rel="stylesheet"></link>
</head>
<body>
To F2:if you let it download itself instead of me downloading css files and telling Spring where they are,you must let the js files or somethings publish to the web which is not controlled by yourself.The building-owner’s purpose is how to load the static file in a Spring MVC project.I think the problem is on the code of addResourceLocations,it should be addResourceLocations ("classpath:/static/");
may be you made a wrong mapping.
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
this code should works, i tested it on my local machine.
addResourceLocations("/static/") the last slash is mandatory
in sping-core-4.2.5-release.jar StringUtils.java has the following code
public static String applyRelativePath(String path, String relativePath) {
int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);
if (separatorIndex != -1) {
String newPath = path.substring(0, separatorIndex);
if (!relativePath.startsWith(FOLDER_SEPARATOR)) {
newPath += FOLDER_SEPARATOR;
}
return newPath + relativePath;
}
else {
return relativePath;
}
}
if not end with a slash, this method will return relativePath
FYI, when i view your attached picture, i found "bootstrap.min.css" in your project. don't forget to use right file name. i wish my suggestion can help you
change addResourceHandlers like
#Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("/");
}
and also change css file name 'bootstrap.min.css'
Change your addResourceHandlers definition like below and try:-
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
}
Please use the context path in your url:
<c:url value='${pageContext.request.contextPath}/static/css/bootstrap.css' />
This will give you the url value:
BPMEI/static/css/bootstrap.css
Let me know if that works.
Spring boot Maven dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
#Service
public class MailContentBuilder {
private TemplateEngine templateEngine;
#Autowired
public MailContentBuilder(TemplateEngine templateEngine) {
this.templateEngine=templateEngine;
}
public String build(String templateName,String user,String email) throws IOException {
Context context=new Context();
context.setVariable("user", "Alpha");
context.setVariable("email", "alpha#gmail.com");
String test=templateEngine.process(templateName, context);
return test;
}
}
this is my mail sender method.
MimeMessage mimeMessage=javaMailSender.createMimeMessage();
//mimeMessage.setContent(mailContentBuilder.build("changepassword","alpha","ema il#email.com"), "text/html");
MimeMessageHelper helper=new MimeMessageHelper(mimeMessage);
helper.setTo(auth0UserService.getUser(userid).getEmail());
helper.setFrom(fromUsername);
helper.setSubject("Password Change Confirmation");
helper.setText(mailContentBuilder.build("changepassword","alpha","email#email.com"), true);
javaMailSender.send(mimeMessage);
this is my template, in src/resources/templates
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Change password</title>
</head>
<body >
helloooo th:text="${user}"
</body>
</html>
This is what it sends, it does not follow the expression language, but writes to the page as it is. no use of variables.
helloooo th:text="${user}"
th:text has to be an attribute to an html tag, so something like
<p th:text="helloooo ${user}" />
should work, judging from a glance at http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#using-texts
I've made an application using `Spring Boot http://localhost:8080/vehicleApp, the contents of my JSP file are getting printed rather than the expected output.
Below is the code:
VehicleApplication.java (main class)
package com.Vehicle.prototype;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class VehicleApplication {
public static void main(String[] args) {
SpringApplication.run(VehicleApplication.class, args);
System.out.println("Vehicle Application started");
}
}
MvcConfig.java
package com.vehicle.prototype.config;
#Configuration
#EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
VehicleController.java
package com.vehicle.prototype.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class VehicleController {
#RequestMapping(value="vehicleApp")
public String home(Model model) {
model.addAttribute("greetings", "hello");
return "vehicleApp";
}
}
src/main/webapp/WEB-INF/jsp/vehicleApp.jsp
(These same contents are getting printed as it is)
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!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=ISO-8859-1">
<title>JSP Page</title>
</head>
<body>
<h1>${greetings}</h1>
</body>
</html>
Please let me know what am I missing?
Thank You