SpringMVC 01

基于servlet!!!

需求:客⼾端发起请求,服务器端接收请求,执⾏逻辑并进⾏视图跳转。
开发步骤

  1. 导⼊相关Jar包;
  2. 创建Controller类和视图⻚⾯;
    1,
@Controller
public class HelloContriller {
    //给方法一个地址
    @RequestMapping("/test")
    public String test(){
        return "/jsp/success.jsp";
    }
}

2,新页面 web/jsp/success.jsp

<p>
    success
</p>

3,主页

<body>
<a href="${pageContext.request.contextPath}/test">test</a>
</body>
  1. 使⽤注解配置Controller类中业务⽅法的映射地址;

  2. 配置SpringMVC核⼼⽂件spring-mvc.xml;

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
        <!--包扫描-->
    <context:component-scan base-package="com.hpe">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
</beans>
  1. 配置SpringMVC核⼼控制器DispatcherServlet;在web.xml中
<!-- 配置SpringMVC核心控制器,其本质上就是一个Servlet -->
<servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 配置SpringMVC配置文件使SpringMVC核心控制器能够加载 -->
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <!--tomcat启动就加载-->
    <load-on-startup>1</load-on-startup>
</servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
  1. 浏览器发起请求测试
    运行就行了

组件
value:⽤于指请求的URL,它和path属性的作⽤是⼀样的;
method:⽤于指定请求的⽅式;

HelloContriller.java中

@Controller
@RequestMapping(value = "/hello")
public class HelloContriller {
    //给方法一个地址
    @RequestMapping(value = "/test",method = RequestMethod.GET,params = {"username"})
    public String test(){
        return "/jsp/success.jsp";
    }
}

主页中也就要拼接上username

<a href="${pageContext.request.contextPath}/hello/test?username=tom">test</a>

改前缀和后缀,省事 return “success”;

默认为转发 用return “forword:/jsp/success.jsp”; forword
可以改为重定向 用return “redirect:/jsp/success.jsp”; redirect

你可能感兴趣的:(java,Spring,springmvc)