搜索
您的当前位置:首页正文

Spring MVC框架简单使用

来源:二三娱乐

首先需要安装xampp和Tomcat,SpringMvc项目中需要在Tomcat上面运行

使用IDEA,直接新建一个Spring MVC项目,如果lib已经有的话,就选择lib路径,如果没有,就选择download!

Paste_Image.png

勾选Create project form template后选择Spring MVC,就可以创建一个Spring MVC项目了!

目录结构

SpringMVC项目的文件目录:包括Controller和webapp,其中Controller负责操作,webapp负责配置文件(包括网页文件)
项目创建成功后会有两个配置文件:首先是mvc-dispatcher-servlet的内容

其中base-package是包名,第二个代表控制的页面的路径在哪里,prefix是前缀,jsp文件后缀
<pre>
<context:component-scan base-package="com.springapp.mvc"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
</pre>
至于web.xml的配置内容,会在另外一篇文章详细介绍、、、
控制器的写法:首先必须声明这个类是控制类即类开头标志@Controller,如果没有在value声明的话,就是默认地址localhost/端口号
value代表网页地址
return 返回的是的JSP的文件名

hello.jsp

<pre>
/**

  • 传输数据
  • @param map
  • @return
    */
    @RequestMapping(value = "addUsers", method = RequestMethod.GET)
    public String addUsers(ModelMap map) {
    User user = new User();
    user.setName("test");
    user.setAge(0);
    map.addAttribute("user",user);
    return "addUsers";
    }

/**

  • 显示结果数据
  • @param map
  • @param name
  • @param age
  • @return
    */
    @RequestMapping(value = "result", method = RequestMethod.GET)
    public String result(ModelMap map, @RequestParam String name, @RequestParam int age) {
    try {
    name = new String(name.getBytes("iso-8859-1"), "utf-8");
    } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    }
    map.addAttribute("name", name);
    map.addAttribute("age", age);
    return "result";
    }

/**

  • 接收路径参数localhost:8080/page/name/age
  • @param map
  • @param name
  • @param age
  • @return
    */
    @RequestMapping(value = "/page/{name}/{age}", method = RequestMethod.GET)
    public String getName(ModelMap map, @PathVariable("name") String name, @PathVariable("age") int age) {
    try {
    name = new String(name.getBytes("iso-8859-1"), "utf-8");
    } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    }
    map.addAttribute("name", name);
    map.addAttribute("age", age + "");
    return "result";
    }

</pre>

Top