SpringMVC入门项目 注解版

来源:互联网 发布:淘宝发货地址在哪里填 编辑:程序博客网 时间:2024/06/03 16:48

1.创建一个maven项目 目录结构是这样的
这里写图片描述
2.需要加入的jar

<dependencies>    <dependency>      <groupId>org.springframework</groupId>      <artifactId>spring-webmvc</artifactId>      <version>4.3.6.RELEASE</version>    </dependency>    <dependency>      <groupId>jstl</groupId>      <artifactId>jstl</artifactId>      <version>1.2</version>    </dependency>    <dependency>      <groupId>javax.servlet</groupId>      <artifactId>javax.servlet-api</artifactId>      <version>3.1.0</version>    </dependency>  </dependencies>

3.web.xml

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">  <listener>    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  </listener>  <context-param>    <param-name>contextConfigLocation</param-name>    <param-value>classpath:spring.xml</param-value>  </context-param>  <!-- POST中文乱码过滤器 -->  <filter>    <filter-name>CharacterEncodingFilter</filter-name>    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>    <init-param>      <param-name>encoding</param-name>      <param-value>utf-8</param-value>    </init-param>  </filter>  <filter-mapping>    <filter-name>CharacterEncodingFilter</filter-name>    <url-pattern>/*</url-pattern>  </filter-mapping>  <servlet>    <servlet-name>SpringMVC</servlet-name>    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    <init-param>      <param-name>contextConfigLocation</param-name>      <param-value>classpath:spring-mvc.xml</param-value>    </init-param>    <!--load-on-startup:表示启动容器时初始化该Servlet;-->    <load-on-startup>1</load-on-startup>  </servlet>  <servlet-mapping>    <servlet-name>SpringMVC</servlet-name>    <!--url-pattern:表示哪些请求交给Spring Web MVC处理, “/” 是用来定义默认    servlet映射的。也可以如“*.html”表示拦截所有以html为扩展名的请求。-->    <url-pattern>/</url-pattern>  </servlet-mapping></web-app>

4.spring-mvc.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"       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">    <!-- HandlerMapping 映射处理器-->    <!--<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>-->    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>    <!-- HandlerAdapter:处理类中的核心方法的 -->    <!--<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>-->    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">        <!--线程安全的访问session-->        <property name="synchronizeOnSession" value="true"/>    </bean>    <!-- ViewResolver -->    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>        <property name="prefix" value="/WEB-INF/jsp/"/>        <property name="suffix" value=".jsp"/>    </bean>    <bean class="com.lyf.controller.BaseController"/>    <bean class="com.lyf.controller.UserController"/></beans>

5.spring.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: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-4.0.xsd        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd        http://www.springframework.org/schema/mvc        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">    <mvc:default-servlet-handler/><!-- 只针对静态页,jsp可不用  --></beans>

servlet在找页面时,走的是dispatcherServlet路线。找不到的时候会报404
加上这个默认的servlet时候,servlet在找不到的时候会去找静态的内容。

6.User

package com.lyf.po;/** * Created by fangjiejie on 2017/6/4. */public class User  {    private String username;    private String password;    public String getUsername() {        return username;    }    public void setUsername(String username) {        this.username = username;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }    public User() {    }}

7.BaseController

package com.lyf.controller;import com.lyf.po.User;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.util.HashMap;import java.util.Map;/** * Created by fangjiejie on 2017/6/4. */@Controller//用于标识是处理器类@RequestMapping(value = "/base")//请求到处理器功能方法的映射规则public class BaseController {    @RequestMapping(value="/hello1")    public ModelAndView handleRequest1(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse){        ModelAndView modelAndView=new ModelAndView();        String name=httpServletRequest.getParameter("name");        modelAndView.setViewName("show1");        System.out.println("this is hello1"+name);        return modelAndView;    }    @RequestMapping(value="/hello2/{username}/{password}")    public ModelAndView handleRequest2(@PathVariable String username, @PathVariable String password){        ModelAndView modelAndView=new ModelAndView();        modelAndView.addObject("un",username);        modelAndView.addObject("pw",password);        modelAndView.setViewName("show1");        return modelAndView;    }    @RequestMapping(value = "/hello3/{min:\\d+}-{max:\\d+}")    public ModelAndView handleRequest3(@PathVariable int min,@PathVariable int max){        ModelAndView modelAndView=new ModelAndView();        Map<String,Object> map=new HashMap<String, Object>();        map.put("min",min);        map.put("max",max);        System.out.println(min+"-"+max);        modelAndView.addAllObjects(map);        modelAndView.setViewName("show1");        return modelAndView;    }    @RequestMapping(value = "/hello4")    public ModelAndView handleRequest4(User user){        ModelAndView modelAndView=new ModelAndView();        modelAndView.setViewName("show1");        modelAndView.addObject("up",user.getUsername()+":"+user.getPassword());        return modelAndView;    }}

8.UserController

package com.lyf.controller;import com.lyf.po.User;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.CookieValue;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.SessionAttributes;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServletResponse;import java.util.Map;/** * Created by fangjiejie on 2017/6/4. */@Controller@RequestMapping(value="/user")@SessionAttributes(value = {"user"})public class UserController {    /**     * 1. 使用RequestMapping注解来映射请求的URL     * 2. 返回值会通过视图解析器解析为实际的物理视图, 对于InternalResourceViewResolver视图解析器,会做如下解析     * 通过prefix+returnVal+suffix 这样的方式得到实际的物理视图,然后会转发操作     * "/WEB-INF/views/success.jsp"     */     @RequestMapping(value = "/pass1")     public String pass1(Model model){        model.addAttribute("hellomodel","hello model");        model.addAttribute("hellomm","hello mm");        return "show2";     }    @RequestMapping(value = "/pass2")     public String pass2(@RequestParam String action, Map map){        System.out.println(action);        map.put("hellomap",action);        return "show2";     }    @RequestMapping(value = "/pass3")    public String pass3(@RequestParam("name") String []n,Map map){        map.put("names",n);        return "show2";    }    @RequestMapping(value = "/pass4")    public String pass4(@CookieValue(value = "count",defaultValue = "0") long count, HttpServletResponse response){        Cookie cookie=new Cookie("count",String.valueOf(++count));        response.addCookie(cookie);        return "show3";    }    @RequestMapping(value = "/pass5")    public String pass5(User u,Map map){        map.put("user",u);        return "show4";    }}

9.index.jsp

<%@page contentType="text/html; charset=utf-8" pageEncoding="UTF-8" %><html><body><h2>Hello World!</h2><a href="/base/hello1?name=lyf">hello1,request传参</a><br><a href="/base/hello2/lyf/110">ant 风格传值</a><a href="/base/hello3/100-200">正则表达式传值</a><form action="/base/hello4">    username: <input type="text" name="username"><br>    password: <input type="text" name="password"><br>    <input type="submit" value="提交"></form></body></html>

index1.jsp

<%--  Created by IntelliJ IDEA.  User: fangjiejie  Date: 2017/6/4  Time: 18:20  To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head>    <title>Title</title></head><body><a href="/user/pass1">后端向前端传值</a><br><a href="/user/pass2?action=requestParam">@RequestParam传值 无键</a><br><a href="/user/pass3?name=li&name=wang&name=hh">@RequestParam传值 有键</a><br><a href="/user/pass4">@CookieValue传值</a><br>@SessionAttributes传值 <br><form action="/user/pass5">    username: <input type="text" name="username"><br>    password: <input type="text" name="password"><br>    <input type="submit" value="提交"></form></body></html>

10.show1.jsp

<%--  Created by IntelliJ IDEA.  User: fangjiejie  Date: 2017/6/4  Time: 15:29  To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head>    <title>Title</title></head><body><h1>hello world</h1><br>username:${un}<br>password:${pw}<br>min-max: <br>${min}-${max} <br>username:${username}<br>password:${password}<br>${up}</body></html>

show2.jsp

<%--  Created by IntelliJ IDEA.  User: fangjiejie  Date: 2017/6/4  Time: 15:29  To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %><%@taglib prefix="f" uri="http://java.sun.com/jsp/jstl/core" %><%@ taglib prefix="l" uri="http://java.sun.com/jsp/jstl/core" %><html><head>    <title>Title</title></head><body>${hellomodel}<br>${hellomm}<br>${hellomap} <br><l:forEach items="${names}" var="n">    ${n} <br></l:forEach></body></html>

show3.jsp

<%--  Created by IntelliJ IDEA.  User: fangjiejie  Date: 2017/6/4  Time: 18:47  To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head>    <title>Title</title><%    Cookie []cookies=request.getCookies();    for(Cookie c:cookies){        if(c.getName().equals("count")){            out.println(c.getValue());        }    }%></head><body></body></html>

show4.jsp

<%--  Created by IntelliJ IDEA.  User: fangjiejie  Date: 2017/6/4  Time: 18:59  To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head>    <title>Title</title></head><body>username:${user.username} <br>password:${user.password}</body></html>

补充@ModelAttribute:
index1.jsp

<%--  Created by IntelliJ IDEA.  User: fangjiejie  Date: 2017/6/5  Time: 20:58  To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head>    <title>Title</title></head><body><form action="/reg/ok1" commandName="user1">    <input type="text" name="username">    <input type="text" name="pwd">    <input type="submit" value="submit"></form><hr><form action="/reg/ok2" commandName="user2">    <input type="text" name="username">    <input type="text" name="pwd">    <input type="submit" value="submit"></form><hr><form action="/reg/ok3">    <input type="text" name="username">    <input type="text" name="pwd">    <input type="submit" value="submit"></form><a href="/reg/ok4">@ModelAttribute无参数List传值</a><br><a href="/reg/ok5">@ModelAttribute无参数Map传值</a></body></html>

RegController

package com.lyf.controller;import com.lyf.po.User;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.bind.annotation.RequestMapping;import java.util.Arrays;import java.util.HashMap;import java.util.List;import java.util.Map;/** * Created by fangjiejie on 2017/6/5. */@Controller@RequestMapping(value = "/reg")public class RegController {    @RequestMapping(value = "/ok1")    public String ok1(@ModelAttribute("user1") User user, Map map){        //map.put("user",user);        return "show5";    }    @RequestMapping(value = "/ok2")//返回值未标明页时,路径为jsp/reg/ok2.jsp    public  @ModelAttribute("user2") User ok2(@ModelAttribute("user2") User user,Map map){        //map.put()        return user;    }    @RequestMapping("/ok3")//无键时,名称默认为类名的小写    public @ModelAttribute User ok3(@ModelAttribute User u,Map map){        return u;    }    @RequestMapping("/ok4")//名称为 (stringList)泛型小写+List    public @ModelAttribute List<String> ok4(){        return Arrays.asList("AAA","BBB","CCC");    }    @RequestMapping("/ok5")    public @ModelAttribute Map<String,User> ok5( ){        Map<String,User> map=new HashMap<String,User>();        map.put("A",new User("MIKE","999"));        map.put("B",new User("ROSE","888"));        map.put("C",new User("NIKE","222"));        return map;    }}

这里写图片描述
show5.jsp

<%--  Created by IntelliJ IDEA.  User: fangjiejie  Date: 2017/6/5  Time: 21:08  To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head>    <title>Title</title></head><body>user:${user.username}:${user.pwd} <br>user1:${user1.username}:${user1.pwd}<br><hr></body></html>

ok2.jsp

<%--  Created by IntelliJ IDEA.  User: fangjiejie  Date: 2017/6/5  Time: 21:23  To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head>    <title>Title</title></head><body>user2:${user2.username}:${user2.pwd}<br></body></html>

ok3.jsp

<%--  Created by IntelliJ IDEA.  User: fangjiejie  Date: 2017/6/5  Time: 21:31  To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head>    <title>Title</title></head><body>ok3 <br>user:${user.username}:${user.pwd} <br></body></html>

ok4.jsp

<%--  Created by IntelliJ IDEA.  User: fangjiejie  Date: 2017/6/5  Time: 21:39  To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %><%@ taglib prefix="f" uri="http://java.sun.com/jsp/jstl/core" %><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><html><head>    <title>Title</title><c:forEach items="${stringList}" var="s">    ${s}</c:forEach></head><body></body></html>

ok5.jsp

<%--  Created by IntelliJ IDEA.  User: fangjiejie  Date: 2017/6/5  Time: 21:50  To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %><%@ taglib prefix="f" uri="http://java.sun.com/jsp/jstl/core" %><html><head>    <title>Title</title></head><body><f:forEach items="${map}" var="k">    ${k.key}:${k.value.username}:${k.value.pwd} <br></f:forEach></body></html>