上一篇文章简单介绍了一下springmvc的使用情况,这里对mvc做进一步的改进
1, recourses
上一篇中 home方法直接返回了 "WEB-INF/views/home.jsp";
这里可以看到WEB-INF/views和jsp这些都是很多余只有home是真正可变量
所以我们希望能找到方法可以配置 这些即可,不用在多写
spring中有视图处理 是该接口 ViewResolver,而默认的生成的处理类是:InternalResourceViewResolver ,仅仅生成了一个JSTLView, 而这个Resolver是可以定制的
我们可以这样:
package xyz.sample.baremvc; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration public class AppConfig { // Resolve logical view names to .jsp resources in the /WEB-INF/views directory @Bean ViewResolver viewResolver() { InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix("WEB-INF/views/"); resolver.setSuffix(".jsp"); return resolver; } }
也可以这样:
<!-- Resolve logical view names to .jsp resources in the /WEB-INF/views directory --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean>
是不是简单些了,下面再复杂一点
2, 方法拦截和参数注入
我们可以指定 action 只可以被 get访问, 也可以直接注入要接收的参数
如下:
package xyz.sample.baremvc; import java.util.Comparator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; /** * Handles requests for the application home page. */ @Controller public class HomeController { @Autowired Comparator<String> comparator; @RequestMapping(value = "/") public String home() { System.out.println("HomeController: Passing through..."); return "home"; } @RequestMapping(value = "/compare", method = RequestMethod.GET) public String compare(@RequestParam("input1") String input1, @RequestParam("input2") String input2, Model model) { int result = comparator.compare(input1, input2); String inEnglish = (result < 0) ? "less than" : (result > 0 ? "greater than" : "equal to"); String output = "According to our Comparator, '" + input1 + "' is " + inEnglish + "'" + input2 + "'"; model.addAttribute("output", output); return "compareResult"; } }
WEB-INF/views/compareResult.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ page session="false" %> <html> <head> <title>Result</title> </head> <body> <h1><c:out value="${output}"></c:out></h1> </body> </html>
要注入的service代码
package xyz.sample.baremvc; import java.util.Comparator; import org.springframework.stereotype.Component; @Service public class CaseInsensitiveComparator implements Comparator<String> { public int compare(String s1, String s2) { assert s1 != null && s2 != null; return String.CASE_INSENSITIVE_ORDER.compare(s1, s2); } }
至此,一个大致的mvc框架是就完工了, 基本零配置,比spring+struts简单多了吧