I have a problem with the following code.
When I run mobile/menu it works, but when I run mobile/Home, with a
jsp in WEB-INF/views/Menu.jsp, it doesn't work.
Can anyone help me to find the mistake?
Thanks in advance.
My Controller
#RestController
#RequestMapping(value="/mobile")
public class UsersController {
#Autowired
UsersService userServices;
#RequestMapping(value="/menu", method=RequestMethod.POST, headers="Accept=application/json")
public #ResponseBody Map<String,Object> getMenu(mng_menu menu){
Map<String,Object> map = new HashMap<String,Object>();
List<mng_menu> list = userServices.listaMenu();
if (list != null){
map.put("status","200");
map.put("message","Data found");
map.put("data", list);
}else{
map.put("status","404");
map.put("message","Data not found");
}
return map;
}
#RequestMapping(value="/Home", method = RequestMethod.GET, headers="Accept=application/json")
public ModelAndView Home(){
ModelAndView view =new ModelAndView("Menu");
return view;
}
My SpringMVC-servlet
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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">
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
Web.xml
<web-app id="WebApp_ID" 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>SpringMVC</display-name>
<servlet>
<servlet-name>SpringMVC</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>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/mobile/Home</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/mobile/menu</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Related
This is the web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app id = "WebApp_ID" version = "3.0"
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_3_0.xsd">
<display-name>First spring project</display-name>
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
This is spring-dispatcher-servlet.xml
<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="com.wasik.controller"></context:component-scan>
<mvc:annotation-driven/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
This the controller I am using annotations in that
package com.wasik.controller;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class mycontroller {
#RequestMapping(value="/admissionForm.html" , method=RequestMethod.GET)
public ModelAndView display(){
ModelAndView view=new ModelAndView("AdmissionForm");
return view;
}
#RequestMapping(value="/submitAdmissionForm", method=RequestMethod.POST)
public ModelAndView Success(#PathVariable Map<String, String>map) {
ModelAndView view =new ModelAndView ("AdmissionSuccess");
String name=map.get("name");
String password=map.get("password");
view.addObject("msg","hi "+name+ password);
return view;
}
}
After that I am taking the two values like username and password
addmissionForm.jsp
<form action="/springWithFormValidation/submitAdmissionForm" method="POST">
Name<input type="text" name="name">
password<input type="test" name="password">
<input type="submit" value="submit">
</form>
and finally population on the browser
admissionSuccess.jsp
<p> successfully registered with following details</p>
<h2> ${msg}</h2>
I am working on setting up swagger2 documentation for my Spring REST Project. But when I try to execute http://localhost:8085/swagger-ui.html returns empty page.The problem is my bean class is not loaded by my spring MVC application and it is NOT a spring boot application.
The below is my swagger2 config class
#Configuration
#EnableSwagger2
#EnableWebMvc
public class SwaggerConfig extends WebMvcConfigurerAdapter{
#Bean
public Docket newsApi() {
System.out.println("!#################################################22");
return new Docket(DocumentationType.SWAGGER_2)
.groupName("Dialr")
.apiInfo(apiInfo())
.select()
.paths(regex("/*.*"))
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring REST Sample with Swagger")
.description("Spring REST Sample with Swagger")
.termsOfServiceUrl("http://www-03.ibm.com/software/sla/sladb.nsf/sla/bm?Open")
.contact("Niklas Heidloff")
.license("Apache License Version 2.0")
.licenseUrl("https://github.com/IBM-Bluemix/news-aggregator/blob/master/LICENSE")
.version("2.0")
.build();
}
}
The below is my rest-servlet.xml under WEB-INF
<?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.xx.yy.zz" />
<mvc:annotation-driven />
<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>
<context:annotation-config/>
<bean name="swaggerConfig" class="com.xx.yy.SwaggerConfig"/>
</beans>
Please find the web.xml entry as well
<?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>Retail_SVC</display-name>
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/rest-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
Please let me know if anything is missing ? Any help is highly appreciated.
Since the base url mapping in your servlet mapping is /rest/* the swagger-ui.html will not load to http://localhost:8085/swagger-ui.html so
try with http://localhost:8085/rest/swagger-ui.html it may work
I used the WebMvcConfigurer instead of the WebMvcConfigurerAdapter because that class is already deprecated.
#Configuration
#EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer {
#Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.illary.controller"))
.paths(PathSelectors.any())
.build()
.apiInfo(metaData());
}
private ApiInfo metaData() {
return new ApiInfoBuilder()
.title("Spring Boot Swagger App")
.description("\"Spring Boot Swagger Server App\"")
.version("1.0.0")
.license("Apache License Version 2.0")
.licenseUrl("https://www.apache.org/licenses/LICENSE-2.0\"")
.build();
}
public ApiInfo apiInfo() {
final ApiInfoBuilder builder = new ApiInfoBuilder();
builder.title("Swagger Test App").version("1.0").license("(C) Copyright Test")
.description("The API provides a platform to query build test swagger api");
return builder.build();
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
I am trying to implement an embedded jetty server using spring mvc for dispatching. I tried several tutorials but monstyl they are out of date or don't use embedded jetty.
So far I created a new spring mvc project from scratch in intellij idea.
src/
main/
java/
com.springapp.mvc/
HelloController.java
Launcher.java
webapp/
WEB-INF/
mvc-dispatcher-servlet.xml
web.xml
pom.xml
HelloController.java
#Controller
#RequestMapping("/")
public class HelloController {
#RequestMapping(method = RequestMethod.GET)
public String printWelcome(ModelMap model) {
model.addAttribute("message", "Hello world!");
return "hello";
}
}
Launcher.java
public class Launcher {
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
//todo: implementation to use dispatcher-servlet...
server.start();
server.join();
}
}
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"
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">
<context:component-scan base-package="com.springapp.mvc"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
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>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
How do I tell the server correctly to use the dispatcher servlet?
I tried a few things out but nothing really worked yet.
The solution for everyone who is also interested... (in scala not in java)
val server: Server = new Server(8080)
private val root: WebAppContext = new WebAppContext
root.setContextPath("/")
root.setDescriptor("src/main/webapp/web.xml")
root.setResourceBase("src/main/webapp/"))
root.setParentLoaderPriority(true)
server.setHandler(root)
server.start()
server.join()
Given the following web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<filter>
<filter-name>Guice Filter</filter-name>
<filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Guice Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>com.foo.JerseyContextListener</listener-class>
</listener>
<context-param>
<param-name>module</param-name>
<param-value>com.foo.MainModule</param-value>
</context-param>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
How do I tell DropWizard to set "module" servlet context parameter to "com.foo.MainModule"?
Configuration.getHttpConfiguration().getContextParameters() always returns an empty list. Are we supposed to extend this class?
You can set it in your configuration file:
- http:
- contextParameters:
- module: com.foo.MainModule
It seems you need override Configuration.http:
public class MyConfiguration extends Configuration
{
public MyConfiguration()
{
this.http = new HttpConfiguration()
{
#Override
public ImmutableMap<String, String> getContextParameters()
{
return ImmutableMap.<String, String>builder().put("module", MainModule.class.getName()).
build();
}
};
}
}
Error info: No mapping found for HTTP request with URI [/TestSpringWebApp/hello.htm]
Any help would be greatly appreciated!
I am using annotation to map request to controller.
controller code :
#Controller
#RequestMapping("/hello.htm")
public class HelloController {
protected final Log logger = LogFactory.getLog(getClass());
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);
}
}
Dispatcher-servlet.xml as follows:
<?xml version="1.0" encoding="UTF-8"?>
<beans ...>
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<!--
Most controllers will use the ControllerClassNameHandlerMapping above, but
for the index controller we are using ParameterizableViewController, so we must
define an explicit mapping for it.
-->
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index.htm">indexController</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<!--
The index controller.
-->
<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
<!-- <bean name="/hello.htm" class="com.kibboko.poprocks.web.HelloController"/>-->
</beans>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans ...>
<!--bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}" /-->
<!-- ADD PERSISTENCE SUPPORT HERE (jpa, hibernate, etc) -->
</beans>
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans ...>
<!--bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}" /-->
<!-- ADD PERSISTENCE SUPPORT HERE (jpa, hibernate, etc) -->
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app ...>
<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>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>redirect.jsp</welcome-file>
</welcome-file-list>
</web-app>
You also need to add
<mvc:annotation-driven />
to your Dispatcher-servlet.xml file.
You have to add #RequestMapping to the method, not to the class. If you add it to the class it will be applied as a prefix to all the methods mapping of this class, but you also have to map the methods of the class.
You can have #RequestMapping for class also, but every method also should have its own " #RequestMapping" please see below example.
#Controller
#RequestMapping("/appointments")
public class AppointmentsController {
private final AppointmentBook appointmentBook;
#Autowired
public AppointmentsController(AppointmentBook appointmentBook) {
this.appointmentBook = appointmentBook;
}
#RequestMapping(method = RequestMethod.GET)
public Map<String, Appointment> get() {
return appointmentBook.getAppointmentsForToday();
}
#RequestMapping(value="/{day}", method = RequestMethod.GET)
public Map<String, Appointment> getForDay(#PathVariable #DateTimeFormat(iso=ISO.DATE) Date day, Model model) {
return appointmentBook.getAppointmentsForDay(day);
}
#RequestMapping(value="/new", method = RequestMethod.GET)
public AppointmentForm getNewForm() {
return new AppointmentForm();
}
#RequestMapping(method = RequestMethod.POST)
public String add(#Valid AppointmentForm appointment, BindingResult result) {
if (result.hasErrors()) {
return "appointments/new";
}
appointmentBook.addAppointment(appointment);
return "redirect:/appointments";
}
}