---
title: "spring mvc 稍微深入的例子"
author: "jt120"
date: "2013-08-09T17:21:53Z"
tags: ["MVC", "Spring"]
categories: ["企业架构"]
slug: "spring-mvc"
draft: false
lastmod: "2013-08-09T17:21:53Z"
id: 1922685
url: "https://jt120.iteye.com/blog/1922685"
---

1、配置web.xml文件 \[code="xml"] hello org.springframework.web.servlet.DispatcherServlet 1 hello / CharacterFilter org.springframework.web.filter.CharacterEncodingFilter encoding UTF-8 CharacterFilter /* \[/code] 2、根据servlet-name配置的名字，新建一个hello-servlet.xml，和web.xml放到同一路径 \[code="xml"] \[/code] 3、创建一个entity，例如User \[code="java"]package zttc.itat.model; import org.hibernate.validator.constraints.NotEmpty; public class User { private String username; private String password; private String nickname; private String email; public User() { } @NotEmpty(message="用户名不能为空") public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } //@Size(min=1,max=10,message="密码的长度应该在1和10之间") public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } //@Email(message="邮箱的格式不正确") public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public User(String username, String password, String nickname, String email) { super(); this.username = username; this.password = password; this.nickname = nickname; this.email = email; } public User(String username) { super(); this.username = username; } }\[/code] 4、创建controller \[code="java"]package zttc.itat.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import zttc.itat.model.User; @Controller public class HelloController { //RequestMapping表示用那个url来对应，这里表示用写hello或直接空，访问这个方法 @RequestMapping({"/hello","/"}) public String hello(String username,Model model) { System.out.println("hello"); //使用这个url来访问此链接：http://localhost:8080/springmvc\_hello/?username=ddd model.addAttribute("username", username); System.out.println(username); //此时用那个作为key?它默认是使用对象的类型作为key--&gt;model.addAttribute("string",username) model.addAttribute(new User("fff"));//就相当于addAttribute("user",new User("fff")); model.addAttribute(username); return "hello"; } @RequestMapping("/welcome") public String welcome() { return "welcome"; } }\[/code] 5、写对应的jsp页面 hello.jsp \[code="html"]&lt;%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%&gt; Insert title here

# hello ${username }!!

string:${string } user.username:${user.username } \[/code] welcom.jsp \[code="html"]&lt;%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%&gt; Insert title here

# Welcome!!

\[/code]