Exception while rendering JSP page in spring mvc - java

Trying out this tutorial from here.
Created a dynamic web project and the code as it is.
However when I deploy and run this on Tomcat, getting this exception:
org.apache.jasper.JasperException: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:565)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:476)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
I tried to google it and also tried modifying the controller class:
package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.portlet.ModelAndView;
#Controller
public class StudentController {
#RequestMapping(value="/student", method=RequestMethod.GET)
public ModelAndView student(){
ModelAndView mAndV = new ModelAndView("student");
mAndV.addObject("command",new Student());
return mAndV;
/*return new ModelAndView("student","command",new Student());*/
}
#RequestMapping(value="/addstudent", method=RequestMethod.POST)
public String addStudent(#ModelAttribute("SpringWeb")Student student, ModelMap model) {
model.addAttribute("name",student.getName());
model.addAttribute("age",student.getAge());
model.addAttribute("id",student.getId());
return "result";
}
}
But its not helping...
I know this must be an simple issue. But not getting what it is.

Related

One controller can be reached but others cannot

Main Application Class: (It was going to be using JSP but realized the trouble with Spring Boot):
package com.MBS.Consulting.jsp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Configuration;
#Configuration
#SpringBootApplication(scanBasePackages="com.MBS.Consulting.jsp")
public class SampleWebJspApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SampleWebJspApplication.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(SampleWebJspApplication.class, args);
}
}
WelcomeController - In sub folder of main class (this controller is accessible):
package com.MBS.Consulting.jsp.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class WelcomeController {
#GetMapping("/")
public String index() {
return "static/index";
}
#GetMapping("/Home")
public String welcome() {
return "Welcome/welcome";
}
#GetMapping("/ContactUs")
public String contactUs() {
return"Welcome/contact_Us";
}
#GetMapping("/AboutUs")
public String aboutUs() {
return "Welcome/about_us";
}
}
CustomerController - Does not even show that it is called with AOP. The package name is the same as the last controller. I do need to login using Spring Security to reach this page. It allows me to login and then gives me 404.
package com.MBS.Consulting.jsp.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.MBS.Consulting.jsp.entity.Customers;
import com.MBS.Consulting.jsp.entity.Users;
import com.MBS.Consulting.jsp.services.CustomersService;
#Controller
#RequestMapping("/Customer")
public class CustomerController {
#Autowired
private CustomersService customerService;
#GetMapping("/Home")
public String customerHome() {
return "Customer/Customer_Home";
}
}
Security config:
Not sure if I really need this or not but added it just to make sure that it couldn't be causing the problem.
package com.MBS.Consulting.jsp.config;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.DelegatingPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.Pbkdf2PasswordEncoder;
import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
#Configuration
#EnableWebSecurity
public class DemoSecurityConfig {
// add a reference to our security data source
#Autowired
#Qualifier("securityDataSource")
private DataSource securityDataSource;
#Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((auth) -> {
try {
auth
.antMatchers("/Admin/**").hasRole("ADMIN")
.antMatchers("/Billing/**").hasAnyRole("ADMIN", "CUSTOMER", "EMPLOYEE")
.antMatchers("/Contacts/**").hasAnyRole("ADMIN", "EMPLOYEE")
.antMatchers("/Customer/**").hasAnyRole("ADMIN", "CUSTOMER")
.antMatchers("/Order/**").hasAnyRole("ADMIN", "CUSTOMER", "EMPLOYEE")
.antMatchers("/Plan/**").hasAnyRole("ADMIN", "CUSTOMER", "EMPLOYEE")
.antMatchers("/Services/**").hasAnyRole("ADMIN", "CUSTOMER", "EMPLOYEE")
.antMatchers("/Welcome", "/Login").permitAll()
.and()
.formLogin()
.and()
.logout()
.permitAll()
.and()
.exceptionHandling()
.accessDeniedPage("/access-denied");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
)
.httpBasic();
return http.build();
}
}
Project structure:
I hope the image shows up due just to show the project structure and that I believe the controllers are in the correct location to not be a problem for Spring Boot.
In the logs for console I get no information at all when visit CustomerController, but I do get a 404 Error. The web address I visit is http://localhost:8080/Customer/Home to try to call CustomerController. I am unsure what will cause this and if someone could explain what I did wrong.
I did search on it and I was going to try and configure the dispatcher servlet but it should of been auto configured. I believe if it reaching one it should be able to reach the other if it is the same folder. Also I understand the it needs to be in the sub folder of the main class. Finally I checked to see if it was the mapped right since I used folders in the template folder.
While mappings were correct and the project structure is correct it was unable to reach controllers due to spring security. The security FilterChain in the screen shot is missing two asterisks on the permit all controllers.
this:
.antMatchers("/","/Welcome", "/Login").permitAll()
should be:
.antMatchers("/**","/Welcome/**", "/Login/**").permitAll()

Spring Controller ModelAndView test MockMvc empty Response

I have this simple example setup to unit test spring Controller ModelAndView with MockMvc, but the response is always empty, even though in debug I can see that the controller code is executed.
Here's the code:
/src/main/java/controller/MvcController.java
package controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class MvcController {
#RequestMapping("/hello/{id}")
public ModelAndView hello(#PathVariable("id") String id) {
Map<String, String> model = new HashMap<>();
ModelAndView modelAndView = new ModelAndView("hello", model);
return modelAndView;
}
}
/src/main/webapp/WEB-INF/jsp/hello.jsp
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="e"
uri="https://www.owasp.org/index.php/OWASP_Java_Encoder_Project"%>
<%# page contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
</head>
<body>HELLO WORLD
</body>
</html>
/src/test/java/controller/MvcControllerTest.java
package controller;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#RunWith(SpringRunner.class)
#SpringBootTest(classes = { MvcController.class })
public class MvcControllerTest {
#Autowired
private MvcController mvcController;
private MockMvc mockMvc;
#Before
public void init() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
this.mockMvc = MockMvcBuilders.standaloneSetup(mvcController).setViewResolvers(resolver).build();
}
#Test
public void testHello() throws Exception {
RequestBuilder requestBuilder = MockMvcRequestBuilders.get("/hello/XWQHEDg9e72t");
ResultActions result = mockMvc.perform(requestBuilder);
MvcResult mvcResult = result.andReturn();
MockHttpServletResponse mockHttpServletResponse = mvcResult.getResponse();
String response = mockHttpServletResponse.getContentAsString();
assertThat(response).contains("HELLO WORLD");
}
}
The key word in MockMvc is mock. This framework does not set up a full Servlet container with a JSP engine. As such, it doesn't render the view that your controller returns and the MockHttpServletResponse does not contain a body (for this use case).
You can use MockHttpServletResponse#getForwardedUrl() to get the url of the JSP that the Servlet container would've forwarded the request to, constructed from your view name and the prefix and suffix of your InternalResourceViewResolver.

Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present]

I am getting the error
"Resolved[org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present]"
I tried all the options provided on previous posts it didn't work please tell me what I am doing wrong this is my first spring-boot application.
My controller
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import java.io.File;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
#RestController
public class SpringBootJdbcController {
#Autowired
JdbcTemplate jdbc;
#Autowired
private SpringBootJdbcService springBootJdbcService;
#RequestMapping("/insert")
public String index() {
jdbc.execute("insert into user(name,email)values('javatpoint','java#javatpoint.com')");
return "data inserted Successfully";
}
#CrossOrigin(origins = "http://localhost:4200")
#ResponseStatus(HttpStatus.OK)
#RequestMapping(value = "/uploadFile", method = RequestMethod.POST, consumes = "multipart/form-data")
public void uploadFiles(#RequestParam("file") MultipartFile file) throws Exception {
System.out.println("hello hello hello");
System.out.println("file---------" + file);
springBootJdbcService.readConfigData(file);
}
}
My Application.properties
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=11MB
api call postman image :-
I don't understand what is the problem. Its my first spring-boot application please help.

I am not able to invoke a simple rest controller

This is my controller code, and I am trying to invoke it using a url http://localhost:8089/webservroj/UserInfo?UserId=123 but it gives an error 404.
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.cas.models.UserInformationModel;
#RestController
#RequestMapping("/")
public class UserInformationController {
UserInformationModel jon =new UserInformationModel(19, "jon", "LA");
#RequestMapping(value="UserInfo", method=RequestMethod.GET)
public UserInformationModel getUserInformation(#RequestParam int UserId){
return jon;
}}

Spring MVC catch http errors (400.404, ....)

Good afternoon. For several days struggling over the issue. I would like to help with Spring beans (resolver) to catch all the errors in the application. Catching exceptions made almost immediately, but with capture http error is not handled.
The essence of the problem resolver can not intercept the http error.
I do not want to use the web.xml and controller, because I hope that the decision is still using the Spring context.
Implementation of catch exceptions:
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<map>
...
<entry key="java.lang.Throwable" value=".error" />
</map>
</property>
<property name="defaultErrorView" value=".error"/>
</bean>
I set up mappings for the 40x errors in web.xml then handle them in a controller (which extends SimpleMappingExceptionResolver and handles the 500 ones as well)
<error-page>
<error-code>404</error-code>
<location>/404</location>
</error-page>
#RequestMapping(value = "/404")
public String handle404(final HttpServletRequest request, final Model model) {
final String originalUri = (String)
request.getAttribute("javax.servlet.forward.request_uri");
// etc.
return "404";
}
I've got a question about the same thing here
One way is to use HandlerExceptionResolver interface.
An alternative to the HandlerExceptionResolver interface is the #ExceptionHandler annotation. You use the #ExceptionHandler method annotation within a controller to specify which method is invoked when an exception of a specific type is thrown during the execution of controller methods. For example:
package com.spring3;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class HelloWorldController {
#ExceptionHandler(Exception.class)
public ModelAndView handleMyException(Exception exception) {
ModelAndView mv = new ModelAndView("redirect:errorMessage.html?error=" + exception.getMessage());
return mv;
}
#RequestMapping(value = "/errorMessage", method = RequestMethod.GET)
public ModelAndView handleMyExceptionOnRedirect(#RequestParam("error") String error) {
ModelAndView mv = new ModelAndView("uncaughtExceptionSpring");
v.addObject("error", error);
return mv;
}
#RequestMapping("/hello")
public ModelAndView helloWorld() throws Exception {
String message = "Hello World, Spring 3.0!";
return new ModelAndView("hello", "message", message);
}
}
Spring MVC exception handling and show custom view Part1, 2, 3, 4

Categories