Issue with Spring Framework static resource set up - java

I have configured my spring project to cater to static resources using below settings in XML file:
<annotation-driven />
<resources mapping="/resources/**" location="/resources/" />
But when I try to access the static content directly, say using below URL:
http://localhost:8080/main/resources/css/app.css
Instead of showing up the static CSS content in the browser, the request is going to the following method in Controller:
#RequestMapping(value = "/{countryID}/{stateId}/{cityId}", method = RequestMethod.GET)
public String city(#PathVariable("countryID") String countryID, #PathVariable("stateId") String stateId, #PathVariable("cityId") String cityId, Locale locale, Model model) {
System.out.println("input "+stateId);
System.out.println("input "+countryID);
System.out.println("input "+cityId);
model.addAttribute("serverTime", "");
return "home";
}
Once the request leads to this method instead of showing up the staic CSS file, I see the JSP page returned by return call "home".
I have checked and rechecked but dont really sight any issue with set up.
Please have a look and let me what might be going wrong here.
Below is the Main Controller that my application is using.
import java.util.Locale;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping("/")
public class MainController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String country(Locale locale, Model model) {
System.out.println("nothing but home page");
return "home";
}
#RequestMapping(value = "/{countryID}", method = RequestMethod.GET)
public String country(#PathVariable("countryID") String countryID, Locale locale, Model model) {
System.out.println("input country "+countryID);
return "home";
}
#RequestMapping(value = "/{countryID}/{stateId}", method = RequestMethod.GET)
public String state(#PathVariable("countryID") String countryID, #PathVariable("stateId") String stateId, Locale locale, Model model) {
System.out.println("input "+stateId);
System.out.println("input "+countryID);
model.addAttribute("serverTime", "");
return "home";
}
#RequestMapping(value = "/{countryID}/{stateId}/{cityId}", method = RequestMethod.GET)
public String city(#PathVariable("countryID") String countryID, #PathVariable("stateId") String stateId, #PathVariable("cityId") String cityId, Locale locale, Model model) {
System.out.println("input "+stateId);
System.out.println("input "+countryID);
System.out.println("input "+cityId);
model.addAttribute("serverTime", "");
return "home";
}
#RequestMapping(value = "/{countryID}/{stateId}/{cityId}/{destId}", method = RequestMethod.GET)
public String dest(#PathVariable("countryID") String countryID, #PathVariable("stateId") String stateId, #PathVariable("cityId") String cityId, #PathVariable("destId") String destId, Locale locale, Model model) {
System.out.println("input "+stateId);
System.out.println("input "+countryID);
System.out.println("input "+cityId);
System.out.println("input "+destId);
model.addAttribute("serverTime", "");
return "home";
}
}
And below is the application XML file :
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- <beans:bean class="org.springframework.web.servlet.view.tiles3.TilesViewResolver" />
<beans:bean class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<beans:property name="definitions">
<beans:list>
<beans:value>/WEB-INF/views.xml</beans:value>
</beans:list>
</beans:property>
</beans:bean> -->
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.travel.main" />
</beans:beans>

The problem is, your #RequestMapping in the controler has precedence over the resource-mapping. To change this, you have to do two things:
Add the attribute order="0" to your resources-tag.
Change the order of your tags to:
<resources mapping="/resources/**" location="/resources/" order="0" />
<annotation-driven />
Then it should work.

It seems http://localhost:8080/main/resources/css/app.css is mapped to /{countryID}/{stateId}/{cityId}:
countryId=resources
stateId=css
cityId=app.css
It seems the resources are only mapped when there is no Controller that matches the URL, so you can try to add to that controller a different path: You can change #RequestMapping("/") to #RequestMapping("/mainController") or add something like /city/ in the matcher of the city method: city/{countryID}/{stateId}/{cityId}.

Give a try the following options:
Remove #RequestMapping("/") from the MainController.
Add a View Resolver to your Spring configuration. For instance, InternalResourceViewResolver.
Take a look at the Spring doc.
Move the resources directory to the same level as views. That is,/WEB-INF/views and /WEB-INF/resources.
I hope that helps!

Related

SEVERE: Servlet.init() call for Servlet [appServlet] caused an exception

While implementing CRUD with a spring, this error occurred and has not been able to proceed with CRUD for several hours...
"Line 7 of the xml document of the servlet context resource [/web-inf/spring/appservlet/slaplet-slap.xml] is invalid."
Even if line 7 is erased, line 6 is an error and line 5 is an error if erased once again, so I don't think this is an empty tag problem.
Just in case, I'll put the controller and dao.
I'm worried that it'll be uncomfortable to watch. sorry..
help me!!
Controller
#Controller
#RequestMapping("/article")
public class ArticleController {
private static final Logger logger = LoggerFactory.getLogger(ArticleController.class);
private final ArticleService articleService;
#Inject
public ArticleController(ArticleService articleService) {
this.articleService = articleService;
}
#RequestMapping(value = "/write", method = RequestMethod.GET)
public String writeGET() {
logger.info("write GET...");
return "/article/write";
}
#RequestMapping(value = "/write", method = RequestMethod.POST)
public String writePOST(ArticleVO articleVO, RedirectAttributes redirectAttributes) throws Exception {
logger.info("writePOST...");
logger.info(articleVO.toString());
articleService.create(articleVO);
;
redirectAttributes.addFlashAttribute("msg", "regSuccess");
return "redirect:/article/list";
}
#RequestMapping(value = "/list", method = RequestMethod.GET)
public String list(Model model) throws Exception {
logger.info("list ...");
model.addAttribute("articles", articleService.listAll());
return "/article/list";
}
#RequestMapping(value = "/read", method = RequestMethod.GET)
public String read(#RequestParam("article_no") int article_no, Model model) throws Exception {
logger.info("read ...");
model.addAttribute("article", articleService.read(article_no));
return "/article/read";
}
#RequestMapping(value = "/modify", method = RequestMethod.GET)
public String modifyGET(#RequestParam("article_no") int article_no, Model model) throws Exception {
logger.info("modifyGet ...");
model.addAttribute("article", articleService.read(article_no));
return "/article/modify";
}
#RequestMapping(value = "/modify", method = RequestMethod.POST)
public String modifyPOST(ArticleVO articleVO, RedirectAttributes redirectAttributes) throws Exception {
logger.info("modifyPOST ...");
articleService.update(articleVO);
redirectAttributes.addFlashAttribute("msg", "modSuccess");
return "redirect:/article/list";
}
#RequestMapping(value = "/remove", method = RequestMethod.POST)
public String remove(#RequestParam("article_no") int article_no, RedirectAttributes redirectAttributes)
throws Exception {
logger.info("remove ...");
articleService.delete(article_no);
redirectAttributes.addFlashAttribute("msg", "delSuccess");
return "redirect:/article/list";
}
}
DAO
#Controller
#RequestMapping("/article")
public class ArticleController {
private static final Logger logger = LoggerFactory.getLogger(ArticleController.class);
private final ArticleService articleService;
#Inject
public ArticleController(ArticleService articleService) {
this.articleService = articleService;
#RequestMapping(value = "/write", method = RequestMethod.GET)
public String writeGET() {
logger.info("write GET...");
return "/article/write";
}
#RequestMapping(value = "/write", method = RequestMethod.POST)
public String writePOST(ArticleVO articleVO, RedirectAttributes redirectAttributes) throws Exception {
logger.info("writePOST...");
logger.info(articleVO.toString());
articleService.create(articleVO);
;
redirectAttributes.addFlashAttribute("msg", "regSuccess");
return "redirect:/article/list";
}
#RequestMapping(value = "/list", method = RequestMethod.GET)
public String list(Model model) throws Exception {
logger.info("list ...");
model.addAttribute("articles", articleService.listAll());
return "/article/list";
}
#RequestMapping(value = "/read", method = RequestMethod.GET)
public String read(#RequestParam("article_no") int article_no, Model model) throws Exception {
logger.info("read ...");
model.addAttribute("article", articleService.read(article_no));
return "/article/read";
}
#RequestMapping(value = "/modify", method = RequestMethod.GET)
public String modifyGET(#RequestParam("article_no") int article_no, Model model) throws Exception {
logger.info("modifyGet ...");
model.addAttribute("article", articleService.read(article_no));
return "/article/modify";
}
#RequestMapping(value = "/modify", method = RequestMethod.POST)
public String modifyPOST(ArticleVO articleVO, RedirectAttributes redirectAttributes) throws Exception {
logger.info("modifyPOST ...");
articleService.update(articleVO);
redirectAttributes.addFlashAttribute("msg", "modSuccess");
return "redirect:/article/list";
}
#RequestMapping(value = "/remove", method = RequestMethod.POST)
public String remove(#RequestParam("article_no") int article_no, RedirectAttributes redirectAttributes)
throws Exception {
logger.info("remove ...");
articleService.delete(article_no);
redirectAttributes.addFlashAttribute("msg", "delSuccess");
return "redirect:/article/list";
}
}
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure --> <!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven /> <!-- Handles HTTP GET requests for /resources/** by efficiently serving up
static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<resources mapping="/plugins/**"
location="/resources/plugins/" />
<resources mapping="/dist/**" location="/resources/dist/" /> <!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan
base-package="com.cameldev.httpsession" />
</beans:beans>
root-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="net.sf.log4jdbc.sql.jdbcapi.DriverSpy" />
<property name="url"
value="jdbc:log4jdbc:mysql://127.0.0.1:3306/injo?serverTimezone=UTC&useSSL=false" />
<property name="username" value="root" />
<property name="password" value="howang12" />
</bean>
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation"
value="classpath:/mybatis-config.xml" />
<property name="mapperLocations"
value="classpath:mappers/**/*Mapper.xml" />
</bean>
<bean id="sqlSession"
class="org.mybatis.spring.SqlSessionTemplate"
destroy-method="clearCache">
<constructor-arg name="sqlSessionFactory"
ref="sqlSessionFactory" />
</bean>
<context:component-scan base-package="com.cameldev.httpsession" />
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param> <!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

Spring data ldap configuration

I'm having trouble configuring spring-data-ldap in a web app.
I summarize what I have done:
I created a maven (called ldap-model) project, with the spring-data-ldap dependency, I created the User.java (Entry) class and the corresponding Repository: UserRepository.
Then I created a new spring mvc web project, with the liberation dependency created before (ldap-model).
I wanted to use the xml configuration, so:
root-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:ldap="http://www.springframework.org/schema/ldap"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/ldap http://www.springframework.org/schema/ldap/spring-ldap.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<context:property-placeholder location="classpath:ldap.properties" />
<context:annotation-config />
<ldap:context-source id="contextSource"
password="${ldap.contextSource.password}" url="${ldap.contextSource.url}"
username="${ldap.contextSource.userDn}" base="${ldap.contextSource.base}"></ldap:context-source>
<ldap:repositories base-package="eu.test.ldap.repository">
</ldap:repositories>
<ldap:ldap-template id="ldapTemplate"
context-source-ref="contextSource"></ldap:ldap-template>
<bean class="eu.test.webapp.UserService">
</bean>
Here I have the first problem with tag ldap:repositories , with Ctrl + Space it's suggested to me, but it does not compile giving this error :
Multiple annotations found at this line:
- Configuration problem: Cannot locate BeanDefinitionParser for element [repositories] Offending resource: file [C:/Progetti/
Workspace di test/ldap-webapp/src/main/webapp/WEB-INF/spring/root-context.xml]
- Cannot locate BeanDefinitionParser for element [repositories]
Following the rest of the code :
UserService.java
public class UserService implements BaseLdapNameAware {
private final UserRepository userRepo;
private LdapName baseLdapPath;
#Autowired
public UserService(UserRepository userRepo) {
this.userRepo = userRepo;
}
public void find()
{
User u = userRepo.findByUid("test.test");
System.out.println(u.getUid());
}
#Override
public void setBaseLdapPath(LdapName baseLdapPath) {
this.baseLdapPath = baseLdapPath;
}}
ldap.properties
ldap.contextSource.url=*********
ldap.contextSource.userDn=cn=*********
ldap.contextSource.password=*********
ldap.contextSource.base=*********
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="eu.test.webapp" />
HomeController.java
#Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
#Autowired
private UserService userService;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
userService.find();
return "home";
}
}
Is there something wrong besides the error given?
I also tried to create a java configuration, not xml
I created a new spring mvc web project, with the liberation dependency created before (ldap-model).
#Configuration
#PropertySource("classpath:ldap.properties")
#ComponentScan(basePackages = {"eu.test.*"})
#Profile("default")
#EnableLdapRepositories(basePackages = "eu.test.ldap.repository.**")
public class AppConfig {
#Autowired
private Environment env;
#Bean
public LdapContextSource contextSource() {
LdapContextSource contextSource = new LdapContextSource();
contextSource.setUrl(env.getRequiredProperty("ldap.contextSource.url"));
contextSource.setBase(env.getRequiredProperty("ldap.contextSource.base"));
contextSource.setUserDn(env.getRequiredProperty("ldap.contextSource.userDn"));
contextSource.setPassword(env.getRequiredProperty("ldap.contextSource.password"));
return contextSource;
}
#Bean
public LdapTemplate ldapTemplate() {
return new LdapTemplate(contextSource());
}
}
ldap.properties like above
UserService.java
#Service
public class UserService {
#Autowired
private UserRepository userRepository;
public String getUsernameByUid(String uid)
{
return userRepository.findByUid(uid).getUsername();
}
}
HomeController.java
#Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
#Autowired
private UserService userService;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
String username = userService.getUsernameByUid("nome.cognome");
return "home";
}
}
I'm sure something is missing, userService is null
Does anyone have an example web project with these features?
Sorry for the english, thank you.
there seems to be a difference in parsing xml configuration since spring-ldap-core 2.3.
If you take a look at LdapNamespaceHandler class, you can see that no handler is defined for tag "repositories".
It sounds strange because there is no equivalent change in spring-ldap.xsd.
Anyway, if you want to use xml configuration approach, you can solve using spring-ldap-core 2.2 instead of spring-ldap-core 2.3, simply modifying your pom.xml.
Ciao.

spring cannot find my bean

I am new to spring, in my application I need to connect to Mysql, all my database's configuration are in a bean, when I try to get it,the server gives me this error:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'dataSource' is defined
this is my servlet-context where I define my bean:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.metmi.mmasgis" />
<beans:bean id="dataSource" name="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
autowire-candidate="true">
<beans:property name="driverClassName"
value="com.mysql.jdbc.Driver">
</beans:property>
<beans:property name="username" value="root"></beans:property>
<beans:property name="password" value="password"></beans:property>
<beans:property name="url"
value="jdbc:mysql://localhost:3306/springschema">
</beans:property>
</beans:bean>
</beans:beans>
this is my controller:
package com.metmi.mmasgis;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import javax.inject.Inject;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.ContextLoader;
import com.metmi.mmasgis.dao.DbImpl;
import com.metmi.mmasgis.model.Db;
/**
* Handles requests for the application home page.
*/
#Controller
public class HomeController {
#Inject
DbImpl dbs;
private static final Logger logger = LoggerFactory
.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG,
DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate);
return "home";
}
/**
* get the database list in Mysql
*/
#RequestMapping(value = "/db", method = RequestMethod.GET)
public String dbs(Locale locale, Model model) {
ApplicationContext ctx = ContextLoader
.getCurrentWebApplicationContext();
DataSource ds = (DataSource) ctx.getBean("dataSource");
dbs = new DbImpl();
dbs.setDataSource(ds);
ArrayList<Db> dbList = dbs.getDatabases();
model.addAttribute("dbList", dbList);
return "dbs";
}
/**
* Simply shows ciao.
*/
#RequestMapping(value = "/ciao", method = RequestMethod.GET)
public String ciao(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG,
DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate);
return "ciao";
}
}
Move your bean declaration to your main application context, not the one where you have DispatcherServlet.

How to send a JSON response in Spring?

I want to return a JSON response from the server in a spring application.
Following is my code snippet.
#RequestMapping(value="getCustomer.action", method = RequestMethod.GET)
public #ResponseBody Customer getValidCustomer(Model model) {
System.out.println("comes");
Customer customer2 = (Customer) customerService
.getCustomer("vvmnbv#jgfj.ghfjg");
System.out.println(customer2.getEmail());
return customer2;
}
But I'm getting an error client-side.
You need to:
Add Jackson JSON Mapper to the classpath
Add <mvc:annotation-driven> to your config
Return Map<Integer, String>
Read: http://blog.safaribooksonline.com/2012/03/28/spring-mvc-tip-returning-json-from-a-spring-controller/
Since you already have an answer with some specifics in it I thought I would just contribute with an example. Here you go:
#RequestMapping(value = "/getfees", method = RequestMethod.POST)
public #ResponseBody
DomainFeesResponse getFees(
#RequestHeader(value = "userName") String userName,
#RequestHeader(value = "password") String password,
#RequestHeader(value = "lastSyncDate", defaultValue = "") String syncDate) {
return domainFeesHelper.executeRetreiveFees(userName, password, syncDate);
}
Just a little summary: As you know you will need the Jackson library in the class path so that Objects can be converted to JSON.
#ResponseBody tells spring to convert its return value and write it to the HTTP Response automatically. There is no other configuration required.
The sample *-servlet.xml configuration is given below.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="org.smarttechies.controller" />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="html" value="text/html"></entry>
<entry key="json" value="application/json"></entry>
<entry key="xml" value="application/xml"></entry>
</map>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</list>
</property>
</bean>
</beans>
Then deploy the application into server and send the request by setting the “Accept” header to “application/json” to get the response in JSON format or “application/xml” to get the response in XML format.
The detailed post explaining about the spring REST is available at http://smarttechie.org/2013/08/11/creating-restful-services-using-spring/
//I have created a class for converting simple string into json convertable format
and returned it to the JSP page where it parsed into json and used like
public class Json {
public static String Convert(Object a,Object b){
return " \""+a.toString()+"\" : \""+b.toString()+"\",";
}
public static String ConvertLast(Object a,Object b){
return " \""+a.toString()+"\" : \""+b.toString()+"\" }";
}
public static String ConvertFirst(Object a,Object b){
return "{ \""+a.toString()+"\" : \""+b.toString()+"\",";
} }
//Controller code ignore the data that i put into the conver(),convertLast() and convertFirst() methods
String json = Json.ConvertFirst("apId", appointment.getId())
+ Json.Convert("appDate",
format.format(appointment.getAppointmentdate()))
+ Json.Convert("appStart", formathourse.format(appointment
.getAppointmentstarttime()))
+ Json.Convert("appEnd", formathourse.format(appointment
.getAppointmentendtime()))
+ Json.Convert("PatientId", appointment.getPatientId()
.getId())
+ Json.Convert("PatientName", appointment.getPatientId()
.getFname()
+ " "
+ appointment.getPatientId().getLname())
+ Json.Convert("Age", appointment.getPatientId().getAge())
+ Json.Convert("Contact", appointment.getPatientId()
.getMobile())
+ Json.Convert("Gender", appointment.getPatientId()
.getSex())
+ Json.ConvertLast("Country", appointment.getPatientId()
.getCountry());
return json;}
/JSP JQuery Code
var app=jQuery.parseJSON(response);
$("#pid").html(app.PatientId);
$("#pname").html(app.PatientName);
$("#pcontact").html(app.Contact);

How can I map my Spring URL to a JSP file in /WEB-INF/views?

I'm having trouble doing a Spring (using 3.0.5.RELEASE) mapping. I want to map the URL http://mydomain/context-path/user/registrationform.jsp to my JSP page at
/WEB-INF/views/user/registrationform.jsp
but I'm getting a 404. I have my controller setup like so …
#Controller
#RequestMapping("registrationform.jsp")
public class RegistrationController {
private static Logger LOG = Logger.getLogger(RegistrationController.class);
…
public void setRegistrationValidation(
RegistrationValidation registrationValidation) {
this.registrationValidation = registrationValidation;
}
// Display the form on the get request
#RequestMapping(method = RequestMethod.GET)
public String showRegistration(Map model) {
final Registration registration = new Registration();
model.put("registration", registration);
return "user/registrationform";
}
here is my dispatcher-servlet.xml …
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- Enable annotation driven controllers, validation etc... -->
<mvc:annotation-driven />
<context:component-scan base-package="com.burrobuie.eventmaven" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/messages" />
</bean>
</beans>
and here is my web.xml …
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
What else do I need to configure (or configure differently) to make this mapping work? This is harder than - Dave
#Controller
#RequestMapping("registrationform.jsp")
public class RegistrationController {
The RequestMapping annotation at class level should be use for a common url pattern like "item/*" and all the links that contains "/item" followed by other pattern would be mapped it to the controller. "user/" in your case
The RequestMapping annotation at method level is used for mapping the sub URL like "item/add" or "item/delete", "registrationform.jsp' in your case
So try this:
#Controller
#RequestMapping("/user")
public class RegistrationController {
private static Logger LOG = Logger.getLogger(RegistrationController.class);
…
public void setRegistrationValidation(
RegistrationValidation registrationValidation) {
this.registrationValidation = registrationValidation;
}
// Display the form on the get request
#RequestMapping(value="/registrationform.jsp",method = RequestMethod.GET)
public String showRegistration(Map model) {
final Registration registration = new Registration();
model.put("registration", registration);
return "user/registrationform";
}
This will map /user/registrationform.jsp
Change the RequestMapping to:
#RequestMapping("/user/registrationform.jsp")

Categories