Spring MVC - Mapping to .htm doesn't work - spring-mvc

I want to crate a simple hello world following a tutorial step by step, but I think that missing something, because my code returns just a 404
Please, can you help me with what is wrong?
This is the Controller class
package com.companyname.springapp;
import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
/**
* Created by cota on 22/12/15.
*/
#Controller
public class HelloController{
protected final Log logger = LogFactory.getLog(getClass());
#RequestMapping(value="/hello.htm",method = RequestMethod.GET)
public ModelAndView handleRequest(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
String now = (new Date()).toString();
logger.info("Returning hello view with " + now);
return new ModelAndView("views/hello.jsp", "now", now);
}
}
This is the 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"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>Springapp</display-name>
<servlet>
<servlet-name>springapp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/app-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springapp</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
This is the app-config.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: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">
<!-- Configures the #Controller programming model -->
<mvc:annotation-driven/>
<!-- Scans the classpath of this application for #Components to deploy as beans -->
<context:component-scan base-package="com.companyname.springapp.web" />
</beans>
This is a header file to include all the JSP files
<%# page session="false"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
And the index.jsp and hello.jsp have the next line
<%# include file="views/include.jsp" %>
It's my first question here and really admire all of you, sorry for my poor english!

I don`t think so you have not properly configured view resolver. so, please try the below links. It may be work for you.
Open your app-config.xml and add the below lines.
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/views/" p:suffix=".jsp" />
and modify the your controller as below.
#RequestMapping(value="/hello.htm",method = RequestMethod.GET)
public ModelAndView handleRequest(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
String now = (new Date()).toString();
logger.info("Returning hello view with " + now);
return new ModelAndView("hello", "now", now);
}
I hope this will work for you..

Related

creating graph-Spring mvc framework error did not find current representation

while creating graphs in spring MVC on tomcat apache server it is shoving the error: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists
My controller class:
package in.webtuts.google.chart.spring.controllers;
import java.util.List;
import in.webtuts.google.chart.data.PieChartData.KeyValue;
import in.webtuts.google.chart.spring.services.PieChartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping("/piechart")
public class PieChartController {
#Autowired
private PieChartService pieChartService;
#RequestMapping(method = RequestMethod.GET)
public String springMVC(ModelMap modelMap) {
List<KeyValue> pieDataList = pieChartService.getPieChartData();
modelMap.addAttribute("pieDataList", pieDataList);
return "spring";
}
}
This is web.xml file:
<?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>Springgraphs</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-
class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<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>
<welcome-file-list>
<welcome-file>piechart.html</welcome-file>
</welcome-file-list>
<!-- spring end -->
</web-app>
This is the dispatcher servlet code:
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:component-scan
base-package="in.webtuts.google.chart.spring.controllers, in.webtuts.google.chart.spring.daos, in.webtuts.google.chart.spring.services"></context:component-scan>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/" >
</property>
<property name="suffix" value=".jsp">
</property>
</bean>
This is the service interface:
package in.webtuts.google.chart.spring.services;
import in.webtuts.google.chart.data.PieChartData.KeyValue;
import java.util.List;
public interface PieChartService {
List<KeyValue> getPieChartData();
}
service interface implement class:
package in.webtuts.google.chart.spring.services;
import in.webtuts.google.chart.data.PieChartData.KeyValue;
import in.webtuts.google.chart.spring.daos.PieChartDao;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
public class PieChartServiceImpl implements PieChartService{
#Autowired
private PieChartDao pieChartDao;
public void setPieChartDao(PieChartDao pieChartDao) {
this.pieChartDao = pieChartDao;
}
#Override
public List<KeyValue> getPieChartData() {
return pieChartDao.getPieChartData();
}
}
DAO interface:
package in.webtuts.google.chart.spring.daos;
import in.webtuts.google.chart.data.PieChartData.KeyValue;
import java.util.List;
public interface PieChartDao {
List<KeyValue> getPieChartData();
}
Dao implementation class:
package in.webtuts.google.chart.spring.daos;
import in.webtuts.google.chart.data.PieChartData;
import in.webtuts.google.chart.data.PieChartData.KeyValue;
import java.util.List;
public class PieChartDaoImpl implements PieChartDao{
#Override
public List<KeyValue> getPieChartData() {
return PieChartData.getPieDataList();
}
}
This is the applicationContext.xml file:
<?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: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.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<context:annotation-config></context:annotation-config>
<bean id="pieChartDao"
class="in.webtuts.google.chart.spring.daos.PieChartDaoImpl"></bean>
<bean id="pieChartService"
class="in.webtuts.google.chart.spring.services.PieChartServiceImpl">
<property name="pieChartDao" ref="pieChartDao"></property>
</bean>
</beans>
This is the DATA class:
package in.webtuts.google.chart.data;
import java.util.ArrayList;
import java.util.List;
public class PieChartData {
private static final List<KeyValue> pieDataList;
static {
pieDataList = new ArrayList<PieChartData.KeyValue>();
pieDataList.add(new KeyValue("Russia", "17098242"));
pieDataList.add(new KeyValue("Canada", "9984670"));
pieDataList.add(new KeyValue("USA", "9826675"));
pieDataList.add(new KeyValue("China", "9596961"));
pieDataList.add(new KeyValue("Brazil", "8514877"));
pieDataList.add(new KeyValue("Australia", "7741220"));
pieDataList.add(new KeyValue("India", "3287263"));
}
public static List<KeyValue> getPieDataList() {
return pieDataList;
}
public static class KeyValue {
String key;
String value;
public KeyValue(String key, String value) {
super();
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
}
This is the JSP file:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Google Chart - Servlet 3</title>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1.0', {
'packages' : [ 'corechart' ]
});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Country',
'Area(square km)'],
<c:forEach items="${pieDataList}" var="entry">
[ '${entry.key}', '${entry.value}' ],
</c:forEach>
]);
var options = {
'title' : 'Area-wise Top Seven Countries in the World',
is3D : true,
pieSliceText: 'label',
tooltip : {showColorCode: true},
'width' : 900,
'height' : 500
};
var chart = new
google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div style="width: 600px;">
<div id="chart_div"></div>
</div>
</body>
</html>

Issues configuring web.xml mapping

I have just picked up web development and I cannot for the life of me figure out what I'm doing wrong when mapping the SimpleServlet in web.xml
these are my files:
My web.xml is:
<?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"
version="3.0">
<display-name>JavaHelloWorldApp</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>SimpleServlet</servlet-name>
<servlet-class>wasdev.sample.servlet.SimpleServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SimpleServlet</servlet-name>
<url-pattern>/SimpleServlet</url-pattern>
</servlet-mapping>
</web-app>
Simple Servlet
package wasdev.sample.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class SimpleServlet
*/
#WebServlet("/SimpleServlet")
public class SimpleServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
response.getWriter().print("Hello World!");
}
}
I am simply trying to get a local host running and access the JavaHelloWorldApp/SimpleServlet

Spring MVC weblogic 10.3.6 Error 403-Forbidden

I work with Spring MVC 3.2.6.RELEASE and weblogic 10.3.6 and Eclipse Juno
When I execute the application I want to go a controller and get a jsp.
This is my web.xml
<?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" xmlns:jsp="http://java.sun.com/xml/ns/javaee/jsp" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi: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>eusurveyadmin</display-name>
<servlet>
<servlet-name>eusurveyadmin</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/eusurveyadmin-servlet.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>eusurveyadmin</servlet-name>
<url-pattern>/eusurveyadmin/*</url-pattern>
</servlet-mapping>
<jsp-config>
<taglib>
<taglib-uri>http://www.owasp.org/index.php/Category:OWASP_Enterprise_Security_API</taglib-uri>
<taglib-location>/WEB-INF/Content/esapi.tld</taglib-location>
</taglib>
</jsp-config>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>file:ecalcpAdminlog4j.xml</param-value>
</context-param>
<listener>
<listener-class>
eusurvey.listener.Log4jConfigListener</listener-class>
</listener>
<context-param>
<param-name>propertiesConfigLocation</param-name>
<param-value>file://C://OEPEJUNO//user_projects//domains//test38//configuracion.properties</param-value>
</context-param>
<listener>
<listener-class>
eusurvey.listener.CustomContextLoaderListener
</listener-class>
</listener>
<error-page>
<error-code>500</error-code>
<location>/500</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/404</location>
</error-page>
</web-app>
Controller is WelcomeController.java
package eusurvey.controller;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
import java.util.Locale;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;
import eusurvey.modelA.daos.Preferencia;
import eusurvey.services.PreferencesService;
#Controller
#RequestMapping("/welcome")
public class WelcomeController extends ExceptionsController {
private static final Logger logger = Logger
.getLogger(WelcomeController.class);
#Resource(name = "preferencesService")
private PreferencesService preferencesService;
private int a = 0;
private Preferencia results = null;
#ModelAttribute("Preferencia")
public Preferencia fechaUltimaEncuesta() {
results = preferencesService.consultaPreferencia();
return results;
}
#RequestMapping(value = "/*")
public String welcome(HttpServletRequest request, ModelMap model) {
logger.info("WelcomeController welcome");
results = fechaUltimaEncuesta();
model.addAttribute("fechaUltimaEncuesta", results.getValor());
request.getSession().setAttribute("fechaUltimaEncuesta",
results.getValor());
String fechaUltimaEncuesta = (String) request.getSession()
.getAttribute("fechaUltimaEncuesta");
//return "welcome1";
return "/menu/pantallaInicio";
}
#ExceptionHandler(Exception.class)
public ModelAndView handleException(Exception e, Locale locale, HttpServletRequest request) {
logger.error("WelcomeController handleException "+e.getLocalizedMessage()+" exception "+ e);
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
String mensajeException = sw.toString();
logger.error("WelcomeController handleException exception "+e.getClass().getSimpleName()+" mensaje "+mensajeException );
ModelAndView mav = new ModelAndView();
mav.addObject("exception", e);
mav.addObject("url", request.getRequestURL());
mav.setViewName("errores/errorGeneral");
return mav;
}
}
When I run the applicacion I get the error
This is my weblogic.xml
<?xml version="1.0" encoding="UTF-8"?>
<wls:weblogic-web-app
xmlns:wls="http://xmlns.oracle.com/weblogic/weblogic-web-app"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd http://xmlns.oracle.com/weblogic/weblogic-web-app http://xmlns.oracle.com/weblogic/weblogic-web-app/1.3/weblogic-web-app.xsd">
<wls:weblogic-version>10.3.6</wls:weblogic-version>
<wls:context-root>EcalpAdmin</wls:context-root>
<wls:container-descriptor>
<wls:prefer-web-inf-classes>true</wls:prefer-web-inf-classes>
</wls:container-descriptor>
</wls:weblogic-web-app>
How do I have to write my web.xml to go the controller?
It appears that your RequestMapping at the class level is /welcome. Any method level RequestMapping will be relative to that. So your URL should be http://localhost/EcalpAdmin/welcome.

org.springframework.web.servlet.DispatcherServlet noHandlerFound when testing through MockMvc

I have defined a rest service using Spring Mvc 4 and then testing the same through MockMvc. Correct response is returned when I run the service using Tomcat 7 through following URL:
http://localhost:8080/SpringServiceSample/service/greeting/Niharika
But when I run the Junit Test, I get 404 error with following in my logs:
INFO: FrameworkServlet '': initialization completed in 159 ms
May 18, 2015 12:36:02 PM org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping found for HTTP request with URI [/service/greeting] in DispatcherServlet with name ''
Following is the code:
SpringServiceController.java
package com.test.springservice.controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping("/service/greeting")
public class SpringServiceController {
#RequestMapping(value = "/{firstName}", method = RequestMethod.GET)
#ResponseBody
public String getGreeting(
#PathVariable String firstName) {
String result = "Hello " + firstName;
return result;
}
}
test-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="com.test.springservice.controller" />
<mvc:annotation-driven />
</beans>
web.xml
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>SpringServiceSample</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>test</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>test</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
SpringServiceControllerTest.java
package com.test.springservice.controller;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.web.context.WebApplicationContext;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration
#WebAppConfiguration
public class SpringServiceControllerTest {
#Autowired
private WebApplicationContext ctx;
private MockMvc mockMvc;
#Before
public void setup() {
this.mockMvc = webAppContextSetup(ctx).build();
}
#Test
public void testGetGreeting() throws Exception {
String firstName = "Niharika";
mockMvc.perform(
MockMvcRequestBuilders.get("/service/greeting").param(
"firstName", firstName))
.andDo(print())
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(
MockMvcResultMatchers.content().string(
"Hello " + firstName));
}
#Configuration
public static class TestConfiguration {
#Bean
public SpringServiceController springServiceController() {
return new SpringServiceController();
}
}
}
Please suggest what I may be doing wrong here.
try add the test-servlet.xml to the #ContextConfiguration annotation, that is
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations={"classpath*:test-servlet.xml"})
#WebAppConfiguration
public class SpringServiceControllerTest {
#Autowired
private WebApplicationContext ctx;
private MockMvc mockMvc;
By the way, add <mvc:default-servlet-handler /> in test-servlet.xml

Servlet Mappings

My problem is i mapped my servlets on web.xml. When i submit info to servlet it gives me "resuorces is not found" error. How can i solve this problem. Thanks your answers.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login Page</title>
</head>
<body>
<form action="Login" method="POST">
UserName:<input type="text" name="user_name">
<BR>
Password:<input type="password" name="password">
<BR>
<input type="submit" value="Gonder">
<BR>
<input type="reset" value="Reset">
</form>
</body>
</html>
SERVLET CODES are like this
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
private String usr_name;
private String pass;
static Logger log=Logger.getLogger(Login.class);
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PropertyConfigurator.configure("C:\\Users\\AliArdaOrhan\\workspace2\\QuizProject\\WebContent\\WEB-INF\\log4j.properties");
usr_name=request.getParameter("user_name");
pass=request.getParameter("Password");
try {
if(Validation.validate(usr_name,pass)){
RequestDispatcher rs=request.getRequestDispatcher("Welcome");
rs.forward(request, response);
}
else{
RequestDispatcher rs=request.getRequestDispatcher("login");
rs.forward(request, response);
}
} catch (ClassNotFoundException | SQLException e) {
log.error("Cannot Validate User Information", e);
}
}
}
WEB XML CODES are like this
<?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_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>QuizProject</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description>Login Page</description>
<display-name>Login</display-name>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>Welcome</display-name>
<servlet-name>Welcome</servlet-name>
<servlet-class>Welcome</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Welcome</servlet-name>
<url-pattern>/Welcome</url-pattern>
</servlet-mapping>
</web-app>
You need to add a servlet mapping for Login action in your web.xml:
<servlet>
<description></description>
<display-name>Login</display-name>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
And make sure you restart your server after you make those changes in web.xml.
And if you are using Servlet 3.0 then you can use annotations like below in your servlet which are equivalent to above code:
#WebServlet("/Login")
public class Login extends HttpServlet {
Please change on this line
<form action="Login" method="POST">
replace "Login" with "/GuestBook"
You are sending your form to Login (relative URL), but your servlet awaits at /GuestBook. Change the servlet mapping or form's action attribute.

Resources