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>
Related
So, I am pretty new to Spring MVC, and I think I'm having problems with configuration and I'm going crazy.
I've tried the solution here but either I'm unable to make it work or my mistake is something different
The error I'm getting is:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'servicioPersonalUrgenciasImplementacion': Unsatisfied dependency expressed through field 'dao'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.modelo.dao.PersonalUrgenciasDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
My components are:
Controller. in com.controladores package
#Controller
public class LoginController {
private ServicioPersonalUrgenciasLogin service;
#Autowired
public void setServicioPersonalUrgenciasLogin( ServicioPersonalUrgenciasLogin service) {
this.service = service;
}
#GetMapping("login")
public String login(Model model) {
PersonalUrgenciasLogin login = new PersonalUrgenciasLogin();
//Add customers to the model
model.addAttribute("login", login);
return "login";
}
...
}
Service interface and Service implementation, both in com.modelo.servicios
#Service
public interface ServicioPersonalUrgenciasLogin {
public boolean login(String username, String pwd) throws NoSuchAlgorithmException, UnsupportedEncodingException;
public void cambiarContrasenia(String username, String newpwd);
}
#Service
public class ServicioPersonalUrgenciasLoginImplementacion implements ServicioPersonalUrgenciasLogin {
#Autowired
private PersonalUrgenciasLoginDAO dao;
#Override
#Transactional
public boolean login(String username, String pwd) throws NoSuchAlgorithmException, UnsupportedEncodingException {
return dao.login(username, pwd);
}
#Override
#Transactional
public void cambiarContrasenia(String username, String newpwd) {
// I have to implement this,
}
}
DAO Interface and Implementation, both in com.modelo.dao package
I know this is not the way to implement a login, but I wanted something fast
public interface PersonalUrgenciasLoginDAO {
public boolean login(String username, String pwd) throws NoSuchAlgorithmException, UnsupportedEncodingException;
public void cambiarContrasenia(String username, String newpwd);
}
#Repository
public class PersonalUrgenciasLoginDAOImplementacion implements PersonalUrgenciasLoginDAO{
#Autowired
private SessionFactory factoria;
#Override
public boolean login(String username, String pwd) throws NoSuchAlgorithmException, UnsupportedEncodingException {
Session sesion = factoria.getCurrentSession();
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] hashInOne = md5.digest(pwd.getBytes("UTF-8"));
String hashMD5String = getString(hashInOne);
Query<String> query2 = sesion.createQuery(
"SELECT usuario FROM PersonalUrgencias WHERE contrasenia=: pwd AND usuario =:user", String.class);
query2.setParameter("user", username);
query2.setParameter("pwd", hashMD5String);
List<String> haLogueado = query2.getResultList();
return !haLogueado.isEmpty();
}
#Override
public void cambiarContrasenia(String username, String newpwd) {
// TODO Auto-generated method stub
}
private static String getString( byte[] bytes )
{
StringBuffer sb = new StringBuffer();
for( int i=0; i<bytes.length; i++ )
{
byte b = bytes[ i ];
String hex = Integer.toHexString((int) 0x00FF & b);
if (hex.length() == 1)
{
sb.append("0");
}
sb.append( hex );
}
return sb.toString();
}
My Entity. I know it is not wired, but I don't want it to be
And then, my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>triaje</display-name>
<absolute-ordering />
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
And this is my applicationContext.xml
I've tried just writting com in <context:component-scan...> too
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Add support for component scanning -->
<context:component-scan base-package="com, com.controladores, com.modelo.dao, com.modelo.entidades, com.modelo.servicios" />
<!-- Add support for conversion, formatting and validation support -->
<mvc:annotation-driven/>
<!-- Define Spring MVC view resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Step 1: Define Database DataSource / connection pool -->
<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.cj.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3316/trj?useSSL=false&serverTimezone=UTC" />
<property name="user" value="root" />
<property name="password" value="root" />
<!-- these are connection pool properties for C3P0 -->
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="maxIdleTime" value="30000" />
</bean>
<!-- Step 2: Setup Hibernate session factory -->
<bean id="factoria"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="com.modelo.entidades" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- Step 3: Setup Hibernate transaction manager -->
<bean id="myTransactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="factoria"/>
</bean>
<!-- Step 4: Enable configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="myTransactionManager" />
<!-- Add support for reading web resources: css, images, js... -->
<mvc:resources location="/resources/" mapping="/resources/**"></mvc:resources>
</beans>
I'm both grateful and sorry for anybody who has read through all of this
I'm making a simple project for school but I'm stuck.
I have a bean FavoriteService that I need to address. However when autowiring the bean in my servlet I keep getting a Null Pointer Exception and I can't figure out why.
FavoriteService
public class FavoriteService {
#Autowired
private Users users;
public boolean checkLogin(String username, String password) {
return users.login(username, password);
}
public void addUser(String rootUsername, String rootPassword, String username, String password)
{
if(rootUsername.equals("root") && rootPassword.equals("rootpasswd")) users.addUser(username, password);
}
public List<String> getFavorites(String username, String password)
{
List<String> favorites;
if(checkLogin(username, password))
{
favorites = users.getFavorites(username);
} else {
favorites = new ArrayList<String>();
}
return favorites;
}
public void addFavorite(String username, String password, String favorite)
{
if(checkLogin(username, password))
{
users.addFavorite(username, favorite);
}
}
public void removeFavorite(String username, String password, String favorite)
{
if(checkLogin(username, password))
{
users.removeFavorite(username, favorite);
}
}
}
Servlet
public class LoginServlet extends HttpServlet {
#Autowired
private FavoriteService favoriteService;
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println(favoriteService);
if(favoriteService.checkLogin(username, password))
{
resp.sendRedirect("root.jsp");
} else {
resp.sendRedirect("index.jsp");
}
}
}
springservlet-servlet
<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:mvc="http://www.springframework.org/schema/mvc"
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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="be.kdg.prog4.tdd"/>
<bean name="userDao" class="be.kdg.prog4.tdd.UserDaoWithMap" scope="singleton" />
<bean name="users" class="be.kdg.prog4.tdd.Users" scope="singleton" />
<bean name="favoriteService" class="be.kdg.prog4.tdd.FavoriteService" scope="singleton" />
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".*"/>
</bean>
</beans>
Web.xml
<web-app schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>TDD oefening</display-name>
<servlet>
<servlet-name>springservlet</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springservlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>be.kdg.prog4.tdd.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
If you need any more info feel free to ask.
Thanks.
EDIT:
I solved it by doing this in the servlet init
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext());
}
If you are calling LoginServlet you are not going through Spring. You mapped it directly in your web.xml and your set let container is initializing your class without going through Spring and the autowired does not work. You need the access the server through a mapping of springservlet.
The Servlet is not initialized by Spring and therefore the #Autowired fields are not getting initialized by Spring.
Instead of using #Autowired you can override the Servlet init() method and get the Spring web context and use its getBean method to get your bean.
This is how you can get the Spring context in your init method:
ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
I am trying to do a restful service in spring mvc. This is my controller code,
#Controller
#RequestMapping("/manageuser")
public class ManageUserController {
#RequestMapping(value = "/deleteuser/{user}", method = RequestMethod.GET)
#ResponseStatus(value = HttpStatus.OK)
protected void deleteUser(#PathVariable String user, ModelMap model) {
System.out.println(user);
}
#RequestMapping(value = "/adduser/{user}", method = RequestMethod.GET)
#ResponseStatus(value = HttpStatus.OK)
protected void addUser(#PathVariable String user, ModelMap model) {
System.out.println(user);
}
}
My manageuser-servelt.xml
<context:component-scan base-package="com.example.web" use-default-filters="false"
>
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".jsp" />
</bean>
My web.xml content,
<servlet>
<servlet-name>manageuser</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:manageuser-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>manageuser</servlet-name>
<url-pattern>/manageuser</url-pattern>
</servlet-mapping>
I am getting a 404 if I navigate to localhost/manageuser/adduser/Barney. What am I doing wrong here? Is this the right approach for RESTful services using spring-mvc?
Does "the System.out.println(user)" display the user ? If not, you have a problem in your mapping.
Check another Blog here : http://www.breathejava.com/restful-web-service-tutorial-spring-xml/.
I'm trying to start up Jetty with Spring MVC that contains jsp and #Controller. After start jetty I've got every time WARN if I try to call any pages. For example
ttp://localhost:8080/getMessageStats/
No mapping found for HTTP request with URI [/resources/css/bootstrap.min.css] in DispatcherServlet with name 'org.springframework.web.servlet.DispatcherServlet-57ad85ed' No mapping found for HTTP request with URI [/resources/js/bootstrap.min.js] in DispatcherServlet with name 'org.springframework.web.servlet.DispatcherServlet-57ad85ed'
web.xml
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring MVC Application</display-name>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/cloud/*</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
mvc-dispatcher-servlet.xml
<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:mvc="http://www.springframework.org/schema/mvc"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="net.cloud.web.statistics"/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:annotation-driven />
WebServer.class
public class WebServer {
private static final Logger log = LoggerFactory.getLogger(WebServer.class);
private static final String CONTEXT_PATH = "/";
private Server httpServer;
#Value("${http_statistics_port}")
private Integer port;
#Value("${start_page_path}")
private String startPagePath;
public void init() {
try {
httpServer = new Server(port);
httpServer.setHandler(getServletContextHandler());
httpServer.setStopAtShutdown(true);
httpServer.start();
log.info("WebServer start ...");
httpServer.join();
} catch (Exception ex) {
log.error("Exception in http server. Exception: {}", ex.getMessage());
}
}
private static ServletContextHandler getServletContextHandler() throws IOException {
WebAppContext contextHandler = new WebAppContext();
contextHandler.setErrorHandler(null);
contextHandler.setContextPath(CONTEXT_PATH);
WebApplicationContext context = getContext();
contextHandler.addServlet(new ServletHolder(new DispatcherServlet(context)), CONTEXT_PATH);
contextHandler.addEventListener(new ContextLoaderListener(context));
contextHandler.setResourceBase(new ClassPathResource("webapp").getURI().toString());
contextHandler.setDescriptor("/webapp/WEB-INF/web.xml");
return contextHandler;
}
private static WebApplicationContext getContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setConfigLocation("webapp/WEB-INF/");
log.info("CONTEXT name {} locations {}", context.getDisplayName(), context.getConfigLocations());
return context;
}
}
GetMessagesStatsController.class
#Controller
#RequestMapping("/getMessageStats")
public class GetMessageStatsController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String printWelcome(ModelMap model) {
GetMessageStatsRPC rpc = new GetMessageStatsRPC();
model.addAttribute("result", rpc.getResult());
return "getMessageStats";
}
#RequestMapping(value = "/json", method = RequestMethod.GET)
public #ResponseBody
String generateJsonResponse() {
GetMessageStatsRPC rpc = new GetMessageStatsRPC();
return rpc.getResult().toString();
}
}
Project tree (Sorry, no rating to upload picture). Classes:
src/java/main/net/.../WebServer.class;src/java/main/net/.../GetMessagesStatsController.class
src/main/webapp/WEB-INF/web.xml; src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml; src/main/webapp/WEB-INF/pages/*.jsp; src/main/webapp/resources/css and src/main/webapp/resources/js
Guys, any idea?
First when the application is deployed it checks the web.xml and gets
<url-pattern>/*</url-pattern>
Then it initializes the DispatcherServlet and initializes the initialization paramerters using
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
(WEB-INF must start with /)
then in mvc-dispatcher-servlet.xml the view resolver resolves the rendering pages.
Change <property name="prefix" value="WEB-INF/pages/"/>
to
<property name="prefix" value="/WEB-INF/pages/"/>
Finally in your controller #RequestMapping("/getMessageStats")
so finally launching the application as
http://localhost:8080/ProjectName/getMessageStats/
invokes printWelcome() of GetMessagesStatsController and
http://localhost:8080/ProjectName/getMessageStats/json
invokes generateJsonResponse()
Looks like the viewResolver has problem. change the prefix to /WEB-INF/pages/, as follow:
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
Without the slash it means a relative path, so it will find the page at relativePath(getMessageStats/) + prefix(WEB-INF/pages/) + request(getMessageStats) +suffix(.jsp).
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")