spring mvc简单上手

来源:互联网 发布:js限制ip访问代码 编辑:程序博客网 时间:2024/04/28 15:37
 //2016.10.28更新

用spring mvc构建web项目

一.配置环境:
所需jar包 spring-framwork,commons-logging,jars-in-tomcat 可选 hibernate,junit

二.配置web.xml,使spring dispatcher管理所有请求:
(1)WEB-INF/web.xml如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <servlet>
        <servlet-name>springMvc</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

<load-on-startup>启动优先级设置为最大
<url-pattern>设置为/ 管理所有请求

(2)配置好之后我们需要在WEB-INF下创建一个springMvc-servlet.xml管理spring dispatcherServlet
由于使用注解配置,我们需要添加<context:component-scan base-package="controller"/>到下文
<?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: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="controller"/>
 
    <!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/page/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

视图解析器:对控制器返回的路径进行解析,最简单的就是上文中的InternalResourceViewResolver,通过增加前缀和后缀进行工作
如果controller返回一个"/hello"字符串,会被试图解析器解释为“/WEB-INF/page/hello.jsp

三.创建controller类,需用controller注解声明:
@Controller
public class HomeController {

spring distpatcher运作时会根据请求路径自动扫描控制器并通过@RequestMapping注解(下面会提到)匹配相应的处理方法

四.@RequestMapping在方法或者类级别上声明处理请求路径:
@RequestMapping("/home")
public String registerHandle(
            HttpServletRequest request){
        UserService.saveUser();
        return "redirect:/hello?name="+request.getParameter("name");
}
方法的可接受参数有好几种,具体可以百度
路径跳转用以下语句(浏览器跳转)
return "redirect:/hello?name=abc";

1 0
原创粉丝点击