I am trying to write a simple WebApp to upload files into a MongoDB database. I am able to upload a subject for a document and a date for the object (as a string datatype). I am now trying to upload the actual file into MongoDB and it is proving difficult. I tried a MultipartFile, but it would not load the file. I then tried to get the string to the file path and that produced a Null Pointer exception (probably because the string path is to a local resource, not on the server).
How do I upload files to MongoDB using a webapp? I apologize for all the code, but I didn't know how much I should post.
Error:
java.lang.NullPointerException
at java.io.File.<init>(File.java:251)
at com.jcdc.domain.FileUpload.setFile(FileUpload.java:34)
at com.jcdc.controller.DocumentController.create(DocumentController.java:43)
at com.jcdc.controller.DocumentController$$FastClassByCGLIB$$f5f3eaff.invoke(<generated>)
at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:689)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.aop.interceptor.CustomizableTraceInterceptor.invokeUnderTrace(CustomizableTraceInterceptor.java:256)
at org.springframework.aop.interceptor.AbstractTraceInterceptor.invoke(AbstractTraceInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:90)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:622)
at com.jcdc.controller.DocumentController$$EnhancerByCGLIB$$6b66bfcf.create(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:212)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:900)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:827)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1852)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
Here are my files:
Domain Layer
FileUpload.java
package com.jcdc.domain;
import org.springframework.data.annotation.Id;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
#org.springframework.data.mongodb.core.mapping.Document
public class FileUpload {
#Id
private String id;
MultipartFile file;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public MultipartFile getFile() {
return file;
}
public void setFile(String filePath) {
File f = new File(filePath);
this.file = (MultipartFile) f;
}
}
Document.java
package com.jcdc.domain;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.DBRef;
#org.springframework.data.mongodb.core.mapping.Document
public class Document {
#Id
private String id;
private String subject;
private String date;
#DBRef
private FileUpload file;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public FileUpload getFile() {
return file;
}
public void setFile(FileUpload file) {
this.file = file;
}
}
Controller Layer
DocumentController.java
package com.jcdc.controller;
import com.jcdc.domain.Document;
import com.jcdc.domain.FileUpload;
import com.jcdc.dto.DocumentListDto;
import com.jcdc.service.DocumentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
#Controller
#RequestMapping("/documents")
public class DocumentController {
#Autowired
private DocumentService service;
#RequestMapping
public String getDocumentsPage() {
return "documents";
}
//...
#RequestMapping(value="/create", method=RequestMethod.POST)
public #ResponseBody Document create(
#RequestParam String subject,
#RequestParam String date, String filepath) {
FileUpload newFile = new FileUpload();
newFile.setFile(filepath);
System.out.println(filepath);
System.out.println(newFile.getFile().toString());
Document newDocument = new Document();
newDocument.setFile(newFile);
newDocument.setSubject(subject);
newDocument.setDate(date);
return service.create(newDocument);
}
}
View Layer
document.jsp
<div id='newForm'>
<form>
<fieldset>
<legend>Create New Record</legend>
<label for='newSubject'>Subject</label><input type='text' id='newSubject'/><br/>
<label for='newDate'>Date</label><input type='date' id='newDate'/><br/>
<label for='newFile'>File</label><input type='file' id='newFile'/><br/>
</fieldset>
<input type='button' value='Close' id='closeNewForm' />
<input type='submit' value='Submit'/>
</form>
custom.js
function submitNewRecord() {
$.post(urlHolder.add, {
subject: $('#newSubject').val(),
date: $('#newDate').val(),
file: $('#newFile').val()
},
function(response) {
if (response != null) {
loadTable();
toggleForms('hide');
toggleCrudButtons('show');
alert('Success! Record has been added.');
} else {
alert('Failure! An error has occurred!');
}
}
);
}
You can inject org.springframework.data.mongodb.gridfs.GridFsOperations to store file in MongoDB with Spring Data. If you don't want use Spring Data then Java driver for MongoDB provides com.mongodb.gridfs.GridFS. In fact GridFsTemplete which is implementation of GridFsOperations uses GridFS under the hood. See linked examples of useage.
GridFS Support in Spring Data MongoDB
Spring Data MongoDB : Save binary file, GridFS example
GridFs Example in Java
GridFS
Related
I'm writing a web app by using Spring and Hibernate but facing this kind of problem for the first time. Whenever I run my app on the server it says **"java.sql.SQLSyntaxErrorException: Table 'restaurantapp.users' doesn't exist."**The thing that I don't understand is I don't even have a table called "users" in my database and also I've never used a table "users" in my app. Code parts are below. Need help to solve this.
Entity class:
package com.jafndy.Restaurant.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="admin_login")
public class RestaurantAdmin {
#Id
#Column(name="user_id")
#GeneratedValue(strategy=GenerationType.AUTO)
private int user_id;
#Column(name="username")
private String username;
#Column(name="authority")
private String authority;
#Column(name="email")
private String email;
#Column(name="password")
private String password;
public RestaurantAdmin(int user_id, String username, String authority,
String email, String password) {
super();
this.user_id = user_id;
this.username = username;
this.authority = authority;
this.email = email;
this.password = password;
}
public RestaurantAdmin() {
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public String toString() {
return "RestaurantAdmin [user_id=" + user_id + ", username=" + username + ", authority=" + authority
+ ", email=" + email + ", password=" + password + "]";
}
}
Config classes:
package com.jafndy.Restaurant.config;
import java.beans.PropertyVetoException;
import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import com.mchange.v2.c3p0.ComboPooledDataSource;
#Configuration
#EnableWebMvc
#EnableTransactionManagement
#ComponentScan(basePackages="com.jafndy.Restaurant")
#PropertySource("classpath:persistence-mysql.properties")
public class AppConfig {
//set up variable to hold variables
#Autowired
private Environment env;
//define a bean for the view resolver
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new
InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
//define a bean for security datasource
#Bean
public DataSource securityDataSource() {
//create a connection pool
ComboPooledDataSource securityDataSource = new ComboPooledDataSource();
//set the jdbc driver class
try {
securityDataSource.setDriverClass(env.getProperty("jdbc.driver"));
}catch(PropertyVetoException exc){
throw new RuntimeException();
}
//set database connection properties
securityDataSource.setJdbcUrl(env.getProperty("jdbc.url"));
securityDataSource.setUser(env.getProperty("jdbc.user"));
securityDataSource.setPassword(env.getProperty("jdbc.password"));
//set connection pool properties
securityDataSource.setInitialPoolSize(getIntProperty("connection.pool.initialPoolSize"));
securityDataSource.setMinPoolSize(getIntProperty("connection.pool.minPoolSize"));
securityDataSource.setMaxPoolSize(getIntProperty("connection.pool.maxPoolSize"));
securityDataSource.setMaxIdleTime(getIntProperty("connection.pool.maxIdleTime"));
return securityDataSource;
}
//define a bean for Hibernate
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(securityDataSource());
sessionFactory.setPackagesToScan("com.jafndy.Restaurant.entity");
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public PlatformTransactionManager hibernateTransactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
private final Properties hibernateProperties() {
Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
hibernateProperties.setProperty("hibernate.show_sql", "true");
return hibernateProperties;
}
//helper method
//read environment property and convert it to int
private int getIntProperty(String propName) {
String propValue = env.getProperty(propName);
int intPropValue = Integer.parseInt(propValue);
return intPropValue;
}
}
package com.jafndy.Restaurant.config;
import
org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class MySpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return new Class[] {AppConfig.class};
}
#Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return new String[] {"/"};
}
}
package com.jafndy.Restaurant.config;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//add a reference to our security DataSource
#Autowired
private DataSource securityDataSource;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(securityDataSource);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").hasAnyRole("CUSTOMER","ADMIN")
.antMatchers("/systems/**").hasRole("ADMIN")
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/authenticateUser")
.permitAll()
.and()
.logout()
.permitAll()
.and()
.exceptionHandling().accessDeniedPage("/access-denied");
}
}
package com.jafndy.Restaurant.config;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
}
Controller clases:
package com.jafndy.Restaurant.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class RestaurantControllerLogin {
#GetMapping("/login")
public String loginPage() {
return "login-page";
}
}
package com.jafndy.Restaurant.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class RestaurantController {
#GetMapping("/")
public String showHome() {
return "home";
}
}
persistence-mysql.properties file
#
# JDBC connection libraries
#
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/restaurantapp?useSSL=false
jdbc.user=restaurant
jdbc.password=restaurant_1_2_3
#
# Connection pool properties
#
connection.pool.initialPoolSize=5
connection.pool.minPoolSize=5
connection.pool.maxPoolSize=20
connection.pool.maxIdleTime=3000
#
# Setup Hibernate session factory
#
hibernate.packagesToScan=com.jafndy.Restaurant.entity
login-page.jsp
<%#taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<style>
.error{
color: red;
}
.logout{
color: green;
}
</style>
</head>
<body>
<h2>Restaurant Login</h2>
<form:form action="${pageContext.request.contextPath}/authenticateUser"
method="POST">
<c:if test="${param.error != null }">
<b class="error">Invalid username or password</b>
</c:if>
<c:if test="${param.logout != null }">
<i class="logout">You've been logged out</i>
</c:if>
<p>
Username: <input type="text" name="username"/>
</p>
<p>
Password: <input type="password" name="password"/>
</p>
<input type="submit" value="Log in"/>
</form:form>
</body>
</html>
home.jsp
<!DOCTYPE html>
<html>
<head>
<style>
h1{
display: none;
}
</style>
</head>
<body>
<h1 id="h1hidden"></h1>
<button
onclick="document.getElementById('h1hidden').style.display='block'">Click to
see</button>
</body>
</html>
And my error log
org.springframework.security.authentication.InternalAuthenticationServiceException: PreparedStatementCallback; bad SQL grammar [select username,password,enabled from users where username = ?]; nested exception is java.sql.SQLSyntaxErrorException: Table 'restaurantapp.users' doesn't exist
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:119)
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:144)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:199)
at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:124)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:770)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [select username,password,enabled from users where username = ?]; nested exception is java.sql.SQLSyntaxErrorException: Table 'restaurantapp.users' doesn't exist
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:235)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72)
at org.springframework.jdbc.core.JdbcTemplate.translateException(JdbcTemplate.java:1402)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:620)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:657)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:688)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:700)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:751)
at org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl.loadUsersByUsername(JdbcDaoImpl.java:227)
at org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl.loadUserByUsername(JdbcDaoImpl.java:184)
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:104)
... 42 more
Caused by: java.sql.SQLSyntaxErrorException: Table 'restaurantapp.users' doesn't exist
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:118)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:95)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:960)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1019)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeQuery(NewProxyPreparedStatement.java:76)
at org.springframework.jdbc.core.JdbcTemplate$1.doInPreparedStatement(JdbcTemplate.java:666)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:605)
... 49 more
This is searching for users table from the user service of spring security. You need to either provide right configuration related to spring security or you can use in memory database and hardcore some dummy users along with roles. So apparently it is the problem of spring security configuration issue at this point. Hope it helps.. I am not in front of my laptop right now, will debug and post more preciously later.
Thats the kind of magic that Spring provides. When you configure Spring security with jdbcAuthentication(), Spring will use the default DaoAuthenticationProvider to authenticate incoming requests. You have created you own User class but Spring is unable to detect it, so it uses JdbcDaoImpl as the default implementation of UserDetailsService.
A closer look into the source gives the following information:
Default Schema A default database schema is assumed, with two tables "users"
and "authorities". (Source)
So, in order to use you own implementation, you have to provide a custom implementation of UserDetailsService, which loads users from your own table.
Please be patient as this is my first time learning about how to use web services.
I am trying to build a simple system that when given a parameter (String id), the web service returns a JSON object. I am somewhat following this codebase as a guide https://o7planning.org/en/11207/simple-crud-example-with-java-restful-web-service
Problem: When I run the service and go the URL http://localhost:8080/RESTfulServiceLIT_war_exploded/users/{id}, I receive a NullPointer exception in the glassfish log. It should simply display the JSON object relative to the user object returned from the id.
Here is the UserDAO class code
import java.util.*;
public class UserDAO {
private static final Map<String, User> userMap = new HashMap<String, User>();
static {
initUsers();
}
private static void initUsers() {
User u1 = new User("K1", "Student 1", "Student");
User u2 = new User("K2", "Student 2", "Student");
User u3 = new User("K3", "Student 3", "Student");
User u4 = new User("S1", "Staff 1", "Staff");
User u5 = new User("S2", "Staff 2", "Staff");
User u6 = new User("S3", "Staff 3", "Staff");
userMap.put(u1.getId(), u1);
userMap.put(u2.getId(), u2);
userMap.put(u3.getId(), u3);
userMap.put(u4.getId(), u4);
userMap.put(u5.getId(), u5);
userMap.put(u6.getId(), u6);
}
public static User getUser(String id) {
return userMap.get(id);
}
public static List<User> getAllUsers() {
Collection<User> c = userMap.values();
List<User> list = new ArrayList<User>();
list.addAll(c);
return list;
}
List<User> list;
}
Here is the Main class that has the rest service
import javax.print.attribute.standard.Media;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.MediaType;
// The Java class will be hosted at the URI path "/helloworld"
#Path("/users")
public class Main {
#GET
#Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
#Path("/{id}")
public User getUser(#PathParam("id") String id) {
return UserDAO.getUser(id);
}
// #GET
// #Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
// #Path{"/all"}
// public List<User> getUsers_JSON(){
// List<User> listOfUsers = UserDAO.getAllUsers();
// return listOfUsers;
// }
}
Here is the server log
[2018-05-22T20:09:17.937+0100] [glassfish 4.1] [WARNING] [] [javax.enterprise.web] [tid: _ThreadID=35 _ThreadName=http-listener-1(3)] [timeMillis: 1527016157937] [levelValue: 900] [[
StandardWrapperValve[MyApplication]: Servlet.service() for servlet MyApplication threw exception
java.lang.NullPointerException
at org.eclipse.persistence.jaxb.rs.MOXyJsonProvider.writeTo(MOXyJsonProvider.java:944)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.invokeWriteTo(WriterInterceptorExecutor.java:265)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:250)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
at org.glassfish.jersey.server.internal.JsonWithPaddingInterceptor.aroundWriteTo(JsonWithPaddingInterceptor.java:106)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundWriteTo(MappableExceptionWrapperInterceptor.java:86)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1130)
at org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:683)
at org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(ServerRuntime.java:424)
at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:414)
at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:312)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:292)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1139)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:460)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:386)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:334)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Thread.java:748)
]]
User class
public class User {
private String id;
private String name;
private String type;
User(){}
User(String id, String name, String type){
this.setId(id);
this.setName(name);
this.setType(type);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
The URL:
http://localhost:8080/RESTfulServiceLIT_war_exploded/users/{id}
is a path specification used by Jersey to state how you can access data. If you simply typed that string into your web browser, then you will get a NullPointerException.
What happens when you type:
http://localhost:8080/RESTfulServiceLIT_war_exploded/users/K1
?
I resolved the same issue today. Issue came when you called bean method in rest api.
so create beans.xml file in WEB-INF folder
include the following
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd"
bean-discovery-mode="all">
</beans>
I am getting the error below when trying to upload file using spring mvc.
"Etat HTTP 500 - Request processing failed; nested exception is java.lang.NullPointerException".
It is the first time i am doing this.
I have an idea of the cause but i can't till now find the solution.
Thanks to anybody who can help.
FileModel.java
package com.model;
import org.springframework.web.multipart.MultipartFile;
public class FileModel {
private MultipartFile file;
public MultipartFile getFile() {
return file;
}
public void setFile(MultipartFile file) {
this.file = file;
}
}
FileUploadController.java
package com.controller;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletContext;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.model.FileModel;
#Controller
public class FileUploadController {
public Logger logger = Logger.getLogger(FileUploadController.class);
public FileUploadController(){
System.out.println("FileUploadController");
}
#Autowired
private ServletContext context;
#RequestMapping(value = "/fileUploadPage", method = RequestMethod.GET)
public ModelAndView fileUploadPage() {
FileModel file = new FileModel();
ModelAndView modelAndView = new ModelAndView("fileUpload", "command", file);
return modelAndView;
}
#RequestMapping(value="/fileUploadPage", method = RequestMethod.POST)
public String fileUpload(#Validated FileModel file, BindingResult result, ModelMap model) throws IOException {
if (result.hasErrors()) {
System.out.println("validation errors");
return "fileUploadPage";
} else {
System.out.println("Fetching file");
MultipartFile multipartFile = file.getFile();
System.out.println("Multipart "+multipartFile);
String uploadPath = context.getRealPath("") + File.separator + "fichiers" + File.separator;
System.out.println(uploadPath);
String fileName = multipartFile.getOriginalFilename();
System.out.println(fileName);
FileCopyUtils.copy(file.getFile().getBytes(), new File(uploadPath+file.getFile().getOriginalFilename()));
model.addAttribute("fileName", fileName);
return "success";
}
}
}
FileUpload.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" isELIgnored="false"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload</title>
</head>
<body>
<form:form action="fileUploadPage" method = "POST" modelAttribute = "fileUpload" enctype = "multipart/form-data">
Please select a file to upload : <input type = "file" name = "file" />
<input type = "submit" value = "upload" />
</form:form>
</body>
</html>
Console
GRAVE: Servlet.service() for servlet [spring] in context with path [/oracle_spring_user_test_project] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at com.controller.FileUploadController.fileUpload(FileUploadController.java:56)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:777)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:706)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
You are using modelAttribute = "fileUpload" in your JSP form. So you should use #ModelAttribute spring annotation as method argument in order to indicate the argument that should be retrieved from the model. This is not necessary although it is the best practice.
The fileUpload model attribute should be populated with data from your form submitted to the fileUploadPage endpoint. So try the below snippet of code:
#RequestMapping(value="/fileUploadPage", method = RequestMethod.POST)
public String fileUpload(#ModelAttribute("fileUpload") FileModel fileUpload, BindingResult result, ModelMap model) throws IOException {
if (result.hasErrors()) {
System.out.println("validation errors");
return "fileUploadPage";
} else {
System.out.println("Fetching file");
MultipartFile file = fileUpload.getFile();
...
On Spring documentation you can read the official information regarding this annotation.
I'm quite new to Java and REST API and I have the following problem. I follow that link https://www.tutorialspoint.com/restful/restful_first_application.htm to learn how to build a REST API. I tried a few things, and I wanted to use my own package (com.ca) and updated my web.xml to the following:
<?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"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id = "WebApp_ID" version = "3.0">
<display-name>User Management</display-name>
<servlet>
<servlet-name>Jersey RESTful Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.ca</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Jersey RESTful Application</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
Nevertheless when I try to re-run the code on the server, and do a GET request I obtain the following:
java.lang.ClassNotFoundException: com.tutorialspoint.User
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1892)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1735)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at java.io.ObjectInputStream.resolveClass(ObjectInputStream.java:677)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1826)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1713)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2000)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:422)
at java.util.ArrayList.readObject(ArrayList.java:791)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1058)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2136)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2027)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:422)
at com.ca.UserDao.getAllUsers(UserDao.java:28)
at com.ca.UserService.getUsers(UserService.java:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory.lambda$static$0(ResourceMethodInvocationHandlerFactory.java:76)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:148)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:191)
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:243)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:103)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:493)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:415)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:104)
at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:277)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:272)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:268)
at org.glassfish.jersey.internal.Errors.process(Errors.java:316)
at org.glassfish.jersey.internal.Errors.process(Errors.java:298)
at org.glassfish.jersey.internal.Errors.process(Errors.java:268)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:289)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:256)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:703)
at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:416)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:370)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:389)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:342)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:229)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
It seems to still point on the previous package ( the one for the exercise), but I can't find why...Also if you have useful link about it ( how to setup the web.xml, every tag role,...) that would be helpful as well.
Thanks in advance.
UPDATE:
Here are the source files:
User.java:
package com.ca;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "user")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
private String profession;
public User(){}
public User(int id, String name, String profession){
this.id = id;
this.name = name;
this.profession = profession;
}
public int getId() {
return id;
}
#XmlElement
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
#XmlElement
public void setName(String name) {
this.name = name;
}
public String getProfession() {
return profession;
}
#XmlElement
public void setProfession(String profession) {
this.profession = profession;
}
}
UserDao.java:
package com.ca;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
public class UserDao {
public List<User> getAllUsers(){
List<User> userList = null;
try {
File file = new File("Users.dat");
if (!file.exists()) {
User user = new User(1, "Mahesh", "Teacher");
userList = new ArrayList<User>();
userList.add(user);
saveUserList(userList);
}
else{
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
userList = (List<User>) ois.readObject();
ois.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return userList;
}
private void saveUserList(List<User> userList){
try {
File file = new File("Users.dat");
FileOutputStream fos;
fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(userList);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
UserService.java:
package com.ca;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("/UserService")
public class UserService {
UserDao userDao = new UserDao();
#GET
#Path("/users")
#Produces(MediaType.APPLICATION_XML)
public List<User> getUsers(){
return userDao.getAllUsers();
}
}
Update 2.0:
Screenshot of the project folder
Now I have the following:
<html>
<head>
<title>Apache Tomcat/7.0.81 - Error report</title>
<style>
<!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}-->
</style>
</head>
<body>
<h1>HTTP Status 404 - /REST-Example/rest/UserService/users</h1>
<HR size="1" noshade="noshade">
<p>
<b>type</b> Status report
</p>
<p>
<b>message</b>
<u>/REST-Example/rest/UserService/users</u>
</p>
<p>
<b>description</b>
<u>The requested resource is not available.</u>
</p>
<HR size="1" noshade="noshade">
<h3>Apache Tomcat/7.0.81</h3>
</body>
</html>
Probably, you are missing some steps. I just followed the tutorial and everything works. The following is what I did:
Configure your system according to the instruction on tutorial site.
Create Eclipse Dynamic Web Project
Download Jersey 2.17 and expand it in a directory according to the instructions on the tutorial site.
Copy all of the JAR files except javax.servlet-api-3.0.1.jar into the WEB-INF/lib folder.
Create the classes User.java, UserDao.java, UserService.java and web.xml in the folders as shown on the screenshot.
Right click on the project (in my example: REST-Example) and select Export>WAR file to export the project to war file.
Copy the war file to the webapps folder of Tomcat and start it.
Start a browser of your choice and call http://localhost:8080/REST-Example/rest/UserService/users, where REST-Example is the name of the war file without the file extension.
If you're using Maven, it would even be simpler: you need to add one or two dependencies and Maven will take care of the rest.
I am working on a project using Struts2 and Hibernate. After employees successfully log on, they will be brought to a new page displaying an event list. This list will be a dropdown select list. I have successfully written and tested my code for logon part, but when I add the second jsp page with tag, they show me the following exception:
message tag 'select', field 'list', name 'yourEvent': The requested list key 'events' could not be resolved as a collection/array/map/enumeration/iterator type. Example: people or people.{name} - [unknown location]
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: tag 'select', field 'list', name 'yourEvent': The requested list key 'events' could not be resolved as a collection/array/map/enumeration/iterator type. Example: people or people.{name} - [unknown location]
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:555)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:476)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
org.apache.struts2.dispatcher.ServletDispatcherResult.doExecute(ServletDispatcherResult.java:164)
org.apache.struts2.dispatcher.StrutsResultSupport.execute(StrutsResultSupport.java:186)
com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:371)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:275)
org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:167)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265)
org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:239)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:239)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:191)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:73)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:91)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:252)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:161)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:193)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:189)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:563)
org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
The following is my MemberScreen.jsp with <s:select> tag inside:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Field Passes</title>
<style>
.errorMessage {
color: red;
}
</style>
</head>
<body>
<h1>Field Passes</h1>
<p align="center">Welcome <s:property value="#session['employee'].first_name"/>!</p><br>
<s:form action="FieldPassInput" method="post">
<s:select label="Event" headerKey="-1" headerValue="Select an event:" name="yourEvent" list="events" listKey="evt_dt" listValue="evt_desc" />
</s:form>
</body>
</html>
The following is my action code:
package actions;
import business.Event;
import business.EventDB;
import com.opensymphony.xwork2.ActionSupport;
import java.util.List;
public class FieldPass extends ActionSupport {
private List<Event> events;
private String yourEvent;
public List<Event> getEventStrings() {
return events;
}
public void setEventStrings(List<Event> events) {
this.events = events;
}
public String getYourEvent() {
return yourEvent;
}
public void setYourEvent(String yourEvent) {
this.yourEvent = yourEvent;
}
public FieldPass() {
events = EventDB.getEvents();
}
#Override
public String execute() throws Exception {
//throw new UnsupportedOperationException("Not supported yet.");
return SUCCESS;
}
}
The following is my code for the Event Entity:
package business;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name = "Events")
public class Event {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long evt_id;
#Temporal(TemporalType.DATE)
private Date evt_date;
private String day_of_week;
private String evt_desc;
private String evt_notes;
private String closed;
private int pass_limit;
private String lg_area;
private String lg_area_name;
public Event() {
evt_date = null;
day_of_week = "";
evt_desc = "";
evt_notes = "";
closed = "";
pass_limit = 0;
lg_area = "";
lg_area_name = "";
}
public long getEvt_id() {
return evt_id;
}
public void setEvt_id(long evt_id) {
this.evt_id = evt_id;
}
public Date getEvt_date() {
return evt_date;
}
public void setEvt_date(Date evt_date) {
this.evt_date = evt_date;
}
public String getDay_of_week() {
return day_of_week;
}
public void setDay_of_week(String day_of_week) {
this.day_of_week = day_of_week;
}
public String getEvt_desc() {
return evt_desc;
}
public void setEvt_desc(String evt_desc) {
this.evt_desc = evt_desc;
}
public String getEvt_notes() {
return evt_notes;
}
public void setEvt_notes(String evt_notes) {
this.evt_notes = evt_notes;
}
public String getClosed() {
return closed;
}
public void setClosed(String closed) {
this.closed = closed;
}
public int getPass_limit() {
return pass_limit;
}
public void setPass_limit(int pass_limit) {
this.pass_limit = pass_limit;
}
public String getLg_area() {
return lg_area;
}
public void setLg_area(String lg_area) {
this.lg_area = lg_area;
}
public String getLg_area_name() {
return lg_area_name;
}
public void setLg_area_name(String lg_area_name) {
this.lg_area_name = lg_area_name;
}
}
The following is my Hibernate data processing code:
package business;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import utility.HibernateUtil;
public class EventDB {
public static List<Event> getEvents() {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = null;
List<Event> events = null;
try {
session = sessionFactory.openSession();
String qS = "from Event";
Query q = session.createQuery(qS);
events = q.list();
} catch (Exception e) {
events = null;
} finally {
if (session != null) {
session.close();
}
}
return events;
}
}
The following code is my struts.xml:
<struts>
<!-- Configuration for the default package. -->
<package name="default" extends="struts-default">
<action name="EmployeeLogon" class="actions.Logon">
<result name="success">/MemberScreen.jsp</result>
<result name="error">/Error.jsp</result>
<result name="input">/Logon.jsp</result>
</action>
<action name="FieldPassInput" class="actions.FieldPass">
<result name="success">/MemberScreen.jsp</result>
<result name="input">/MemberScreen.jsp</result>
</action>
</package>
</struts>
The following is hibernate config:
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/FIELDPASS?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">sesame</property>
<mapping class="business.Employee"/>
<mapping class="business.Event"/>
</session-factory>
</hibernate-configuration>
For completeness, I also post my logon.jsp and its action codes here:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Employee Logon</title>
<style>
.errorMessage {
color: red;
}
</style>
</head>
<body>
<h1>Welcome to the Field Pass - Please Logon</h1>
<s:form action="EmployeeLogon" method="post">
<table>
<tr>
<s:textfield name="employeeid" id="employeeid" label="Employee ID" required="true"/>
</tr>
<tr>
<s:password name="pattempt" id="pattempt" label="Password" required="true"/>
</tr>
<tr>
<s:submit value="Logon"/>
</tr>
</table>
</s:form>
${msg}
</body>
</html>
package actions;
import business.Employee;
import business.EmployeeDB;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
public class Logon extends ActionSupport implements SessionAware {
private Employee employee;
private String employeeid;
private String pattempt;
private Map session;
public String getEmployeeid() {
return employeeid;
}
public void setEmployeeid(String employeeid) {
this.employeeid = employeeid;
}
public String getPattempt() {
return pattempt;
}
public void setPattempt(String pattempt) {
this.pattempt = pattempt;
}
#Override
public void setSession(Map session) {
this.session = session;
}
public Logon() {
}
#Override
public String execute() throws Exception {
//throw new UnsupportedOperationException("Not supported yet.");
String rval = ERROR, msg = "";
Map request = (Map)ActionContext.getContext().get("request");
employee = EmployeeDB.getEmployee(Integer.parseInt(employeeid));
if (employee != null) {
employee.setPassAttempt(Integer.parseInt(this.pattempt));
if (employee.isAuthenticated()) {
session.put("employee", employee);
msg = "Member authenticated";
rval = SUCCESS;
} else if (!employee.getMsg().isEmpty()) {
msg = employee.getMsg();
rval = INPUT;
}
} else {
msg = "Hibernate returned null member.";
rval = INPUT;
}
request.put("msg", msg);
return rval;
}
#Override
public void validate() {
try {
int pat = Integer.parseInt(this.pattempt);
if (pat <= 0) {
throw new Exception("Bad password");
}
} catch (Exception e) {
addFieldError("pattempt", "Password issue: " + e.getMessage());
}
}
}
package business;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
#Entity
public class Employee {
#Id
private int emp_id;
private String last_name;
private String first_name;
private String middle_initial;
#Temporal(TemporalType.DATE)
private Date hire_date;
private int dept_id;
private int password;
private String admin;
#Transient
private int passattempt;
#Transient
private String msg;
public Employee() {
emp_id = 0;
last_name = "";
first_name = "";
middle_initial = "";
hire_date = null;
dept_id = 0;
password = 0;
passattempt = -1;
msg = "";
}
public int getEmp_id() {
return emp_id;
}
public void setEmp_id(int emp_id) {
this.emp_id = emp_id;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getMiddle_initial() {
return middle_initial;
}
public void setMiddle_initial(String middle_initial) {
this.middle_initial = middle_initial;
}
public Date getHire_date() {
return hire_date;
}
public void setHire_date(Date hire_date) {
this.hire_date = hire_date;
}
public int getDept_id() {
return dept_id;
}
public void setDept_id(int dept_id) {
this.dept_id = dept_id;
}
public int getPassword() {
return password;
}
public void setPassword(int password) {
this.password = password;
}
public String getAdmin() {
return admin;
}
public void setAdmin(String admin) {
this.admin = admin;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public void setPassAttempt(int patt) {
this.passattempt = patt;
}
public boolean isAuthenticated() {
if (this.password > 0) {
if (this.password == this.passattempt) {
return true;
} else {
msg = "Member not authenticated";
}
}
return false;
}
}
package business;
import javax.persistence.NoResultException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import utility.HibernateUtil;
public class EmployeeDB {
public static Employee getEmployee(int emp_id) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = null;
Employee e = null;
try {
String qS = "from Employee e where e.emp_id = :emp_id";
session = sessionFactory.openSession();
Query q = session.createQuery(qS);
q.setParameter("emp_id", emp_id);
e = (Employee)q.uniqueResult();
} catch (NoResultException ex) {
return null;
} finally {
session.close();
}
return e;
}
}
Can any Struts2 expert tell me what's wrong is my code so that I cannot populate data from database into my select dropdown list in MemberScreen.jsp? Thank you for your time and help.