【问题标题】:setting fullpath in controller在控制器中设置完整路径
【发布时间】:2011-08-17 06:41:22
【问题描述】:

我开发了一个弹簧应用程序。所有请求都发送到控制器(我的应用中有 2 个控制器),所以 web.xml 如下所示

在 web.xml 中

<servlet-mapping>
   <url-pattern>/*</url-pattern>

aaa 控制器

@Controller
@RequestMapping("/aaa")

bbb 控制器

@Controller
@RequestMapping("/bbb")

但是现在我需要在我的项目中添加一些 jsp 页面,因为 web.xml 中的“/*”我的 jsp 页面没有找到。所以我改变了如下的servlet映射;

在 web.xml 中

<servlet-mapping>
   <url-pattern>/aaa/*</url-pattern>
   <url-pattern>/bbb/*</url-pattern>

aaa 控制器

@Controller
@RequestMapping("/")

bbb 控制器

@Controller
@RequestMapping("/")

但我不想使用这种方法,因为我可以访问像 /bbb/xxx 这样的 aaa 控制器中的 xxx servlet。

那么有没有其他解决方案,例如我可以在控制器或任何东西中设置完整路径吗?

提前谢谢...

【问题讨论】:

    标签: spring spring-mvc annotations


    【解决方案1】:

    您还需要通过服务器传递 jsp。 您可以将其映射为 html 扩展名

    <servlet>
        <servlet-name>example</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>example</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
    

    在 example-servlet.xml 中只需添加以下 jsp 解析器

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

    然后在控制器中使用 ModelAndView 对象:

    @Controller
    @RequestMapping(value="/aaa")
    public class aaaController{
    
        @RequestMapping(value="/aaa.html", method=RequestMethod.GET)
        public ModelAndView index(){
            ModelAndView mv = new ModelAndView("aaa");
            return mv;
        }
    }
    
    
    @Controller
    @RequestMapping(value="/bbb")
    public class aaaController{
    
        @RequestMapping(value="/bbb.html", method=RequestMethod.GET)
        public ModelAndView index(){
            ModelAndView mv = new ModelAndView("bbb");
            return mv;
        }
    }
    

    在这种情况下,当你点击 /aaa/aaa.html 时,第一个控制器将返回 /aaa.jsp 作为你的模型和视图

    当你点击 /bbb/bbb.html 时,第二个控制器将返回 /bbb.jsp 作为你的模型和视图

    希望对你有帮助。

    【讨论】:

    • @Controller @RequestMapping("/aaa") @RequestMapping(method=RequestMethod.GET,value="/login") public String getLogin(HttpServletRequest request, HttpServletResponse response, Model model) { model. addAttribute("用户名", "测试");返回“登录”; } } 错误--- [PageNotFound] No mapping found for HTTP request with URI [/TestServer/WEB-INF/views/login.jsp] 我想我被误解了,我的问题是在我的应用程序中没有更改任何 url 添加一些jsp页面。 bwt 我无法更改 uri,因为它已被使用。 uri 必须是 .../TestServer/aaa/login
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-14
    • 1970-01-01
    相关资源
    最近更新 更多