Старый диспетчерский сервлет не работает при загрузке после загрузки - PullRequest
0 голосов
/ 05 июня 2019

У меня есть существующее приложение, построенное на Spring 4.3.20 и Hibernate 3.6, мы использовали SimpleUrlHandlerMapping в конфигурации XML для отображения контроллера, и оно работает нормально.

Я начал с более мелких шагов и без каких-либо изменений я просто переместил свой проект maven только в зависимости от весенней загрузки (без аннотированного файла @SpringBootApplication), и все заработало нормально. Теперь я начал перемещать свой web.xml контент в SpringBootApplication файл, но он не работал, не уверен, что мне не хватает.

Контроллер

public class AuthController extends MultiActionController {
public ModelAndView test(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        return new ModelAndView("jsonView","model",<data in string>,);
    }
}

диспетчер-servlet.xml

<beans>
    <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>                
                <prop key="AuthController/*.do">AuthController</prop>
</props>
        </property>
        <property name="interceptors">
            <list>
                <ref bean="openSessionInViewInterceptor" />
            </list>
        </property>    
            </bean>

</beans>

views.xml

<bean name="jsonView" class="com.mycompany.views.JsonView">
        <property name="contentType">
            <value>text/html; charset=ISO-8859-1</value>
        </property>
    </bean>

JsonView.java

public class JsonView extends AbstractView {
    boolean validSession = true;

    public void setValidSession(boolean validSession) {
        this.validSession = validSession;
    }

    protected void renderMergedOutputModel(Map map,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        String model = (String) map.get("model");

        try {
            JSONObject jobj = new JSONObject(model);
            if (jobj.has("msg")) {
                if (jobj.getString("msg").toLowerCase().contains("system failure:")) {
                    jobj.remove("msg");
                    jobj.put("msg", "Some problem occurred while performing the operation. Please try again later.");
                    model = jobj.toString();
                }
            }
        } catch (JSONException je) {
            model = (String) map.get("model");
        }
        model = "{\"valid\":" + this.validSession + ",\"data\":" + model + ",\"success\":true}";
        response.getOutputStream().write(model.getBytes());
        response.setContentType("text/html; charset=UTF-8");
    }

web.xml контент, который мы удалили для SpringBootApplication

<listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:config/applicationContextList.xml</param-value>
    </context-param>
<servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:config/dispatcher-servlet.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

SpringBootApplication

@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class })
@ImportResource("classpath*:config/applicationContextList.xml")
public class MainSpringBootApplication extends SpringBootServletInitializer{

    public static void main(String[] args) {
        SpringApplication.run(MainSpringBootApplication.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(MainSpringBootApplication.class);
    }
@Bean
    public DispatcherServlet dispatcherServlet() {
        return new DispatcherServlet();
    }

    @Bean
    public ServletRegistrationBean dispatcherServletRegistration() {
        ServletRegistrationBean registration = new ServletRegistrationBean(dispatcherServlet());
        Map<String,String> params = new HashMap<String,String>();
        params.put("contextClass","org.springframework.web.context.support.AnnotationConfigWebApplicationContext");
        params.put("contextConfigLocation","classpath:config/dispatcher-servlet.xml");
                registration.setInitParameters(params);
        registration.addUrlMappings("*.do");
        registration.addUrlMappings("/props/*");
        return registration;
    }

ApplicationContext-view.xml

<bean id="xmlViewResolver" class="org.springframework.web.servlet.view.XmlViewResolver">
        <property name="order" value="1" /> 
        <property name = "location">
         <value>/WEB-INF/views.xml</value>
      </property>
    </bean>

applicationContextList.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
    <import resource="applicationContext.xml" />
    <import resource="applicationContext-view.xml" />   
</beans>

Когда js вызывает AuthController.test.do, тогда он выдает ошибку 404, тогда как нормально работал без SpringBootApplication и только web.xml

Я получаю журнал ниже, когда выполняю необходимую услугу:

2019-06-05 16:48:35.893 DEBUG 26901 --- [nio-8084-exec-3] o.s.web.servlet.DispatcherServlet        : DispatcherServlet with name 'dispatcherServlet' processing POST request for [/Accounting/AuthController/test.do]
2019-06-05 16:48:35.893 DEBUG 26901 --- [nio-8084-exec-3] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /AuthController/test.do
2019-06-05 16:48:35.894 DEBUG 26901 --- [nio-8084-exec-3] s.w.s.m.m.a.RequestMappingHandlerMapping : Did not find handler method for [/AuthController/test.do]
2019-06-05 16:48:35.894 DEBUG 26901 --- [nio-8084-exec-3] o.s.w.s.handler.SimpleUrlHandlerMapping  : Matching patterns for request [/AuthController/test.do] are [/**]
2019-06-05 16:48:35.894 DEBUG 26901 --- [nio-8084-exec-3] o.s.w.s.handler.SimpleUrlHandlerMapping  : URI Template variables for request [/AuthController/test.do] are {}
2019-06-05 16:48:35.894 DEBUG 26901 --- [nio-8084-exec-3] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapping [/AuthController/test.do] to HandlerExecutionChain with handler [ResourceHttpRequestHandler [locations=[ServletContext resource [/], class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@4351bc9]]] and 1 interceptor
2019-06-05 16:48:35.894 DEBUG 26901 --- [nio-8084-exec-3] o.s.web.cors.DefaultCorsProcessor        : Skip CORS processing: request is from same origin
2019-06-05 16:48:35.896 DEBUG 26901 --- [nio-8084-exec-3] o.s.web.servlet.DispatcherServlet        : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2019-06-05 16:48:35.896 DEBUG 26901 --- [nio-8084-exec-3] o.s.web.servlet.DispatcherServlet        : Successfully completed request
2019-06-05 16:48:35.896 ERROR 26901 --- [nio-8084-exec-3] o.s.boot.web.support.ErrorPageFilter     : Cannot forward to error page for request [/a/gst25/AuthController/test.do] as the response has already been committed. As a result, the response may have the wrong status code. If your application is running on WebSphere Application Server you may be able to resolve this problem by setting com.ibm.ws.webcontainer.invokeFlushAfterService to false
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...