복붙노트

[SPRING] 봄 MVC : 인덱스 페이지에 대한 기본 컨트롤러를 만드는 방법?

SPRING

봄 MVC : 인덱스 페이지에 대한 기본 컨트롤러를 만드는 방법?

내가 그 표준 봄 MVC 안녕하세요 세계 응용 프로그램 중 하나를하려고하지만 컨트롤을 루트에 매핑하고 싶습니다 트위스트와 함께. (예 : http://numberformat.wordpress.com/2009/09/02/hello-world-spring-mvc-with-annotations/) 그래서 유일한 차이점은 호스트를 \ appname \ something에 매핑하고 host \ appname에 매핑하고 싶습니다.

내 index.jsp를 src \ main \ webapp \ jsp에두고 welcome.xml로 web.xml에 매핑했습니다. 나는 시도했다 :

@Controller("loginController")
public class LoginController{

  @RequestMapping("/")
  public String homepage2(ModelMap model, HttpServletRequest request, HttpServletResponse response){
    System.out.println("blablabla2");
    model.addAttribute("sigh", "lesigh");
    return "index";
  }

내 컨트롤러지만 내 바람둥이의 콘솔에는 아무것도 표시되지 않습니다. 내가 엉망이 된 곳을 아는 사람 있니?

내 web.xml :

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_2_5.xsd"
    version="2.5">

    <!-- Index -->
    <welcome-file-list>
        <welcome-file>/jsp/index.jsp</welcome-file>
    </welcome-file-list>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
    </context-param>

    <servlet>
        <servlet-name>springweb</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springweb</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

mvc-dispatcher-servlet.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:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        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">

    <context:annotation-config />
    <context:component-scan base-package="de.claude.test.*" />

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

스프링 3.0.5를 사용하고 있습니다.

또는 이것이 가능하지 않으며 index-jsp를 web-inf의 루트에 다시 넣고 컨트롤러가 내 jsp 내 어딘가에 리다이렉션을 할 필요가 있습니까?

해결법

  1. ==============================

    1.나는 Sinhue의 설정에 따라 같은 문제가 있었지만 해결했다.

    나는 Sinhue의 설정에 따라 같은 문제가 있었지만 해결했다.

    문제는 WebContent 디렉토리에 index.jsp 파일이있을 때 뭔가 (Tomcat?)가 "/"에서 "/index.jsp"로 전달된다는 것입니다. 제거했을 때 요청이 더 이상 전달되지 않았습니다.

    내가 문제를 진단하기 위해 수행 한 것은 포괄적 인 요청 처리기를 작성하고 서블릿 경로를 콘솔에 인쇄하는 것이 었습니다. 이것은 내가 만들고있는 요청이 http : // localhost / myapp /에 대한 것이었지만 서블릿 경로가 "/index.html"로 변경되었다는 것을 보여주었습니다. 나는 그것이 "/"이길 기대하고 있었다.

    @RequestMapping("*")
    public String hello(HttpServletRequest request) {
        System.out.println(request.getServletPath());
        return "hello";
    }
    

    요약하면, 따라야 할 단계는 다음과 같습니다.

    희망이 도움이됩니다.

  2. ==============================

    2.리디렉션은 하나의 옵션입니다. 한 가지 시도해 볼 수있는 것은 매우 단순한 인덱스 페이지를 만드는 것입니다.이 페이지는 WAR의 루트에 놓습니다.이 페이지는 다른 것을하지 않고 컨트롤러로 리디렉션됩니다.

    리디렉션은 하나의 옵션입니다. 한 가지 시도해 볼 수있는 것은 매우 단순한 인덱스 페이지를 만드는 것입니다.이 페이지는 WAR의 루트에 놓습니다.이 페이지는 다른 것을하지 않고 컨트롤러로 리디렉션됩니다.

    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <c:redirect url="/welcome.html"/>
    

    그런 다음 해당 URL로 컨트롤러를 매핑합니다.

    @Controller("loginController")
    @RequestMapping(value = "/welcome.html")
    public class LoginController{
    ...
    }
    

    마지막으로 web.xml에서 (새) 색인 JSP에 액세스 할 수있게하려면

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    
  3. ==============================

    3.기본 뷰에 Controller 메서드를 매핑하면됩니다. 예를 들어, 우리는 index.html을 기본 페이지로 가지고 있습니다.

    기본 뷰에 Controller 메서드를 매핑하면됩니다. 예를 들어, 우리는 index.html을 기본 페이지로 가지고 있습니다.

    @RequestMapping(value = "/", method = GET)
    public String index() {
        return "index";
    }
    

    일단 완료되면 기본 응용 프로그램 컨텍스트로 페이지에 액세스 할 수 있습니다.

    E.g http://localhost:8080/myapp
    
  4. ==============================

    4.그것은 나를 위해 작동하지만 몇 가지 차이점이 있습니다.

    그것은 나를 위해 작동하지만 몇 가지 차이점이 있습니다.

    나는 이것들이 큰 차이가 없다는 것을 안다. 그러나 나는 꽤 확신한다. (나는 지금 일하고 있지 않다.) 이것이 나의 구성이고 스프링 MVC 3.0.5와 함께 작동한다.

    하나 더. dispatcher 구성을 web.xml에 표시하지는 않지만 어쩌면 일부 접두어가있을 수 있습니다. 그것은 다음과 같이되어야합니다 :

    <servlet-mapping>
        <servlet-name>myServletName</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    

    그렇지 않은 경우 url-rewrite 필터가 필요하거나 리디렉션 솔루션을 사용해보십시오.

    편집 : 귀하의 질문에 대답, 내보기 resolver 구성도 조금 다릅니다 :

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
    </bean>
    
  5. ==============================

    5.보다 간단한 방법으로 해결할 수 있습니다. in web.xml

    보다 간단한 방법으로 해결할 수 있습니다. in web.xml

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.htm</welcome-file>
    </welcome-file-list>
    

    그런 다음 @RequestMapping ( "index.htm")을 사용하여 index.htm을 처리하려는 컨트롤러를 사용하십시오. 또는 색인 컨트롤러 만 사용하십시오.

    <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="index.htm">indexController</prop>
            </props>
        </property>
    <bean name="indexController" class="org.springframework.web.servlet.mvc.ParameterizableViewController"
          p:viewName="index" />
    </bean>
    
  6. ==============================

    6.spring.xml 파일에 한 항목 더 추가합니다. 즉.mvc-dispatcher-servlet.xml

    spring.xml 파일에 한 항목 더 추가합니다. 즉.mvc-dispatcher-servlet.xml

    <mvc:view-controller path="/" view-name="index"/>
    

    이것을 xml에 넣은 후 mvc-dispatcher-servlet.xml 파일에서 언급 한 것처럼 사용자 정의 JSP 폴더에 기본보기 또는 JSP 파일을 넣으십시오.

    jsp 이름으로 색인을 변경하십시오.

  7. ==============================

    7.이를 달성하는 한 가지 방법은 web.xml 파일의 컨트롤러 요청 경로에 환영 파일을 매핑하는 것입니다.

    이를 달성하는 한 가지 방법은 web.xml 파일의 컨트롤러 요청 경로에 환영 파일을 매핑하는 것입니다.

    швеб.хмлщ

    <web-app ...
    
    <!-- Index -->
    <welcome-file-list>
        <welcome-file>home</welcome-file>
    </welcome-file-list>
    
    </web-app>
    

    [LoginController.java]

    @Controller("loginController")
    public class LoginController{
    
    @RequestMapping("/home")
    public String homepage2(ModelMap model, HttpServletRequest request, HttpServletResponse response){
        System.out.println("blablabla2");
        model.addAttribute("sigh", "lesigh");
        return "index";
    }
    
  8. ==============================

    8.스프링 MVC 웹 API에서 사용하는 솔루션은 다음과 같은 간단한 기본 컨트롤러 클래스를 만드는 것입니다.

    스프링 MVC 웹 API에서 사용하는 솔루션은 다음과 같은 간단한 기본 컨트롤러 클래스를 만드는 것입니다.

    @Controller
    public class DefaultController {
    
        private final String redirect;
    
        public DefaultController(String redirect) {
            this.redirect = redirect;
        }
    
        @RequestMapping(value = "/")
        public ModelAndView redirectToMainPage() {
            return new ModelAndView("redirect:/" + redirect);
        }
    
    }
    

    리디렉션은 다음과 같은 스프링 구성을 사용하여 주입 할 수 있습니다.

    <bean class="com.adoreboard.farfisa.controller.DefaultController">
        <constructor-arg name="redirect" value="${default.redirect:loginController}"/>
    </bean>
    

    $ {default.redirect : loginController}는 기본적으로 loginController가 될 것이지만 default.redirect = something_else를 스프링 속성 파일에 삽입하거나 환경 변수를 설정하여 변경할 수 있습니다.

    @Mike가 위에 언급 한 것처럼 나는 또한 다음과 같은 것을 가지고있다.

    이 솔루션을 사용하면 Spring이 원하는 것과 그렇지 않을 수있는 리디렉션에 대해 걱정할 필요가 없습니다.

  9. from https://stackoverflow.com/questions/5252065/spring-mvc-how-to-create-a-default-controller-for-index-page by cc-by-sa and MIT license