modelAttribute属性指定该form绑定的是哪个Model,当指定了对应的Model后就可以在form标签内部其
它表单标签上通过为path指定Model属性的名称来绑定Model中的数据了

重新整理

设定编码方式:放在web.xml中,设定为utf-8

<filter>
<filter-name>CharacterFilter</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>CharacterFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

实现功能一:能正确返回welcome.html的页面,用<bean>

1、在eclipse中创建dynamic web project,注意第三个next中选择generate web.xml

2、导入dist下地包,导入commons-logging-1.1.3

3、web.xml

<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>

4、spring-servlet.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean name="/welcome.html" class="zttc.itat.controller.WelcomeController"></bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>

注意:bean name 不要写成/welcome/html; property prefix 不要写成/WEB-INF/jsp

5、WelcomeController.java

public class WelcomeController extends AbstractController {

	@Override
protected ModelAndView handleRequestInternal(HttpServletRequest req,
HttpServletResponse resp) throws Exception {
// TODO Auto-generated method stub
return new ModelAndView("welcome");
} }

注意:继承AbstractController;放在zttc.itat.controller package下面

6、welcome.jsp

//简单地jsp页面
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
welcome!
</body>
</html>

实现功能二:开启注解,给controller传值,给view传值,rest风格

1、springmvc-servlet.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
     //增加了这句
<context:component-scan base-package="zttc.itat.controller" />
<mvc:annotation-driven />
//删除了bean[name="/welcome.html"]
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>

2、HelloController.java

package zttc.itat.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView; @Controller
public class HelloController { @RequestMapping({"/hello","/"})
public ModelAndView hello(@RequestParam("username") String username){
ModelAndView mv = new ModelAndView();
mv.addObject("username", username);
mv.setViewName("hello");
return mv;
} }

3、hello.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
//显示传来的值
${username}
</body>
</html>

实现功能三:用户管理系统,CRUD

展示用户信息

1、user.java

package zttc.itat.model;

public class User {
private String username;
private String nickname;
private String password;
private String email; //构造函数没有返回类型
public User(){ } public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getNickname() {
return nickname;
} public void setNickname(String nickname) {
this.nickname = nickname;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} public String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email;
} public User(String username, String nickname, String password, String email){
super();
this.username = username;
this.nickname = nickname;
this.password = password;
this.email = email;
}
}

2、UserController.java

package zttc.itat.controller;

import java.util.HashMap;
import java.util.Map; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView; import zttc.itat.model.User; @Controller
//路径会加上/user
@RequestMapping("/user")
public class UserController {
private Map<String, User> users = new HashMap<String, User>(); public UserController(){
users.put("a", new User("a","aa","1","s"));
users.put("b", new User("b","bb","2","f"));
} @RequestMapping(value="/users", method=RequestMethod.GET)
public ModelAndView list(){
ModelAndView mv = new ModelAndView();
mv.addObject("users", users);
mv.setViewName("user/list");
return mv;
}
}

3、springmvc-servlet.xml,导入jsf-api,jsf-impl,jstl-1.2 

使用jstl标签
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>

4、list.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
//使用jstl需要添加的标示
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<c:forEach items="${users}" var="um">
${um.value.username }
--${um.value.nickname }
--${um.value.password }
--${um.value.email }<br />
</c:forEach>
</body>
</html>

添加用户

1、UserController.java

//首先,需要访问add.jsp页面,get方法。该页面使用了springmvc的form标签,所以需要加@ModelAttribute("user") User user,这样 可以通过form中的path对应到user得username属性
@RequestMapping(value="/add", method=RequestMethod.GET)
public String add(@ModelAttribute("user") User user){
return "user/add";
}
//其次,表单提交到当前页面,post方法。验证提交的数据,加入bean-validator,加入@Valid User user, BindingResult br,br一定要紧跟user;jsp页面也需要加入一定的error标签
@RequestMapping(value="/add", method=RequestMethod.POST)
public String add(@Valid User user, BindingResult br){
//如果出错
if(br.hasErrors()){
return "user/add";
}
users.put(user.getUsername(), user);
return "redirect:/user/users";
}

2、User.java

//验证的注解
@NotEmpty(message="用户名不能为空")
public String getUsername() {
return username;
} @Size(min=1, max=10, message="长度1-10")
public String getPassword() {
return password;
} @Email(message="格式不正确")
public String getEmail() {
return email;
}

3、add.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
//使用springmvc form标签
<%@taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<sf:form method="post" modelAttribute="user">
     //添加的出错提示
username:<sf:input path="username" /><sf:errors path="username" /><br />
nickname:<sf:input path="nickname" /><sf:errors path="nickname" /><br />
password:<sf:input path="password" /><sf:errors path="password" /><br />
email:<sf:input path="email" /><sf:errors path="email" /><br />
<input type="submit" value="add user" /><br />
</sf:form>
</body>
</html>

展示单个用户

1、UserController.java

//展示单个用户,show.jsp有form,需要传一个model,add是用过@ModelAttribute来指定;show使用ModelAndView来指定。@PathVariable来接收路径中得变量
@RequestMapping(value="/{username}", method=RequestMethod.GET)
public ModelAndView show(@PathVariable String username){
ModelAndView mv = new ModelAndView();
mv.addObject(users.get(username));
mv.setViewName("user/show");
return mv;
}
//返回json对象,添加jackson-all-1.9.4,只需return user就行,需要添加@ResponseBody
@RequestMapping(value="/{username}", method=RequestMethod.GET, params="json")
@ResponseBody
public User show(@PathVariable String username, String abc){
return users.get(username);
}

2、show.jsp

//跟add.jsp类似
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<sf:form method="post" modelAttribute="user">
username:${user.username }<br />
password:${user.password }<br />
nickname:${user.nickname }<br />
email:${user.email }<br />
</sf:form>
</body>
</html>

更新用户信息

1、UserController.java

@RequestMapping(value="/{username}/update", method=RequestMethod.GET)
public ModelAndView update(@PathVariable String username, @ModelAttribute("user") User user){
ModelAndView mv = new ModelAndView();
mv.addObject(users.get(username));
mv.setViewName("user/update");
return mv;
} @RequestMapping(value="/{username}/update", method=RequestMethod.POST)
public String update(@PathVariable String username, @Valid User user, BindingResult br){
if(br.hasErrors()){
return "user/update";
}
users.put(username, user);
return "redirect:/user/users";
}

2、update.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
//给表单元素赋初值
<sf:form method="post" modelAttribute="user">
username:<sf:input path="username" value="${user.username}"/><sf:errors path="username" /><br />
nickname:<sf:input path="nickname" value="${user.nickname}"/><sf:errors path="nickname" /><br />
password:<sf:input path="password" value="${user.password}"/><sf:errors path="password" /><br />
email:<sf:input path="email" value="${user.email}"/><sf:errors path="email" /><br />
<input type="submit" value="update user" /><br />
</sf:form>
</body>
</html>

3、

--<a href="${um.value.username}/delete">delete</a>

删除用户

1、UserController.java

//ModelAndView setViewName 时可以增加 redirect 记得user前加/
@RequestMapping(value="/{username}/delete", method=RequestMethod.GET)
public ModelAndView delete(@PathVariable String username){
ModelAndView mv = new ModelAndView();
users.remove(username);
mv.setViewName("redirect:/user/users");
return mv;
}

2、list.jsp

--<a href="${um.value.username}/delete">delete</a>

登陆

1、UserException.java

//serial选第一个;右键 source generate constructor form superclass
package zttc.itat.model; public class UserException extends RuntimeException { /**
*
*/
private static final long serialVersionUID = 1L; public UserException() {
super();
// TODO Auto-generated constructor stub
} public UserException(String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
// TODO Auto-generated constructor stub
} public UserException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
} public UserException(String message) {
super(message);
// TODO Auto-generated constructor stub
} public UserException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
} }

2、UserController.java

@RequestMapping(value="/login", method=RequestMethod.POST)
public String login(String username, String password, HttpSession session){
if(!users.containsKey(username)){
throw new UserException("用户名不存在");
}
User u = users.get(username);
if(!u.getPassword().equals(password)){
throw new UserException("用户密码不正确");
}
//把登陆成功地用户存入session
session.setAttribute("loginUser", u);
return "redirect:/user/users";
} //局部异常处理函数,只处理当前controller的异常
// @ExceptionHandler(value={UserException.class})
// public String handlerException(UserException e, HttpServletRequest req){
// req.setAttribute("e", e);
// return "error";
// }

3、springmvc-servlet.xml:全局异常处理

<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<!-- 配置这个属性 -->
<property name="exceptionMappings">
<props>
<!-- 如果发现的是UserException,就到error页面 -->
<prop key="zttc.itat.model.UserException">error</prop>
</props>
</property>
</bean>

4、error.jsp 放在jsp下面

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
//当前是全局异常处理,如果为局部异常处理的话是e
${exception.message }
</body>
</html>

5、login.jsp 放在webContent下面

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="user/login" method="POST">
Username:<input type="text" name="username"><br />
Password:<input type="text" name="password"><br />
<input type="submit" value="login" />
</body>
</html>

上传文件

1、add.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
//form一定要加enctype
<sf:form method="post" modelAttribute="user" enctype="multipart/form-data">
username:<sf:input path="username" /><sf:errors path="username" /><br />
nickname:<sf:input path="nickname" /><sf:errors path="nickname" /><br />
password:<sf:input path="password" /><sf:errors path="password" /><br />
email:<sf:input path="email" /><sf:errors path="email" /><br />
     //增加了这个
file:<input type="file" name="attach" /><br />
<input type="submit" value="add user" /><br />
</sf:form>
</body>
</html>

2、springmvc-servlet.xml

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5000000"></property>
</bean>

3、UserController.java 在webContent下面建resources文件夹,导入commons-fileupload-1.2.2,commons-io-2.1

//修改了add方法
@RequestMapping(value="/add", method=RequestMethod.POST)
public String add(@Valid User user, BindingResult br, @RequestParam MultipartFile attach, HttpServletRequest req) throws IOException{
if(br.hasErrors()){
return "user/add";
}
     //不知道每个方法是做什么用的
String realpath = req.getSession().getServletContext().getRealPath("/resources/upload");
System.out.println(realpath);
File f = new File(realpath+"/"+attach.getOriginalFilename());
FileUtils.copyInputStreamToFile(attach.getInputStream(), f);
users.put(user.getUsername(), user);
return "redirect:/user/users";
}
//上传多个文件
@RequestMapping(value="/add",method=RequestMethod.POST)
public String add(@Valid User user, BindingResult br, @RequestParam MultipartFile[] attachs, HttpServletRequest req) throws IOException{ //一定要紧跟validate之后写验证结果类
if(br.hasErrors()){
return "user/add";
}
String realpath = req.getSession().getServletContext().getRealPath("/resources/upload");
System.out.println(realpath);
for(MultipartFile attach:attachs){
if(attach.isEmpty()) continue;
File f = new File(realpath+"/"+attach.getOriginalFilename());
FileUtils.copyInputStreamToFile(attach.getInputStream(), f);
}
users.put(user.getUsername(), user);
return "redirect:/user/users";
}

静态文件 可以直接访问

1、list.jsp  在resources中新建css文件夹

<link href="<%=request.getContextPath()%>/resources/css/style.css" rel="stylesheet" type="text/css"/>

2、springmvc-serlvet.xml

<mvc:resources location="/resources/" mapping="/resources/**/" />
 

springmvc 孔浩的更多相关文章

  1. springmvc 孔浩 hibernate

    以上为项目文件 用到的jar包:http://pan.baidu.com/s/1kT1Rsqj 1. model-User 2. beans.xml-去哪些包中找annotation:查找相应的实体类 ...

  2. springmvc 孔浩 hibernate code

    model--User package model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; ...

  3. 孔浩老师的 Struts2 教程听课笔记(思维导图)

    最近有空重头学习了一遍孔浩老师的 Struts2 教程,重新写了一份听课笔记.后面常用 form 标签.服务器端验证.异常处理因为时间问题,没有来得及整理.后续我会抽空补上.最近忙着准备笔试.面试. ...

  4. cms完整视频教程+源码 孔浩老师 全131讲

    话不多说,请看如下链接,  项目在此文件夹目录下:  JAVA专区>3.深入Java Web>3.1.cms项目 很多反馈说无效 本次 2016.09.12 发布最新链接 链接:https ...

  5. 《Maven_孔浩》依赖传递

    间接依赖的包中有同级相同的依赖,那么按照写在前面的依赖:如果不同级有相同的依赖,那么按照级别最高的为准. 依赖的范围scope(test/compile/provided/runtime) test: ...

  6. 《Maven_孔浩》Maven依赖

    项目目录结构如下: pom.xml src          main\java\zttc\itat\maven\ch02 target   pom.xml文件说明 groupId:项目id(如:zt ...

  7. 《Maven_孔浩》Maven命令

    maven命令: mvn compile:maven编译 mvn test:测试 mvn clean:删除编译生成的target文件 mvn package:运行编译.测试.package,把项目打包 ...

  8. 《Maven_孔浩》Maven介绍及安装

    maven是apache基金会下的一个项目管理工具. 安装步骤 1.下载并解压 2.配置环境变量M2_HOME(解压后的目录):将M2_HOME\bin加入到PATH环境变量中 3.测试:在命令行输入 ...

  9. SpringMVC(一) HelloWorld

    学习新东西的的第一个程序--HelloWorld,以下是SpringMVC的HelloWorld 第一步: 用MAVEN 创建webapp,并添加依赖.(强烈建议使用MAVEN,MAVEN学习书籍和视 ...

随机推荐

  1. linux 常用find

    磁盘查找文件内容: find .|xargs grep x find . -exec grep x{} \; 磁盘查找文件名称: find / -name "httpd.conf" ...

  2. dubbo hessian+dubbo协议

    Dubbo缺省协议采用单一长连接和NIO异步通讯,适合于小数据量大并发的服务调用,以及服务消费者机器数远大于服务提供者机器数的情况 Hessian协议用于集成Hessian的服务,Hessian底层采 ...

  3. ubuntu安装谷歌拼音输入法

    在这篇教程中,我将告诉你如何在ubuntu系统上安装谷歌拼音输入法.谷歌拼音输入法有基于ibus框架的,也有基于fcitx框架的.我只演示fcitx框架下谷歌拼音输入法的安装,因为ibus框架的谷歌拼 ...

  4. 【英宝通Unity4.0公开课学习 】(六)76讲到90讲

    还是关于Mecanim动画的内容. 这些讲的每讲长度明显比前面的长,而且很多都涉及到脚本编写. 不过我还是2倍速给略览过去了,主要目的就是学个框架嘛 :) 1. Blend Tree 可嵌套. 可理解 ...

  5. The Doors(几何+最短路,好题)

    The Doors http://poj.org/problem?id=1556 Time Limit: 1000MS   Memory Limit: 10000K Total Submissions ...

  6. MongoDB的数据类型(四)

    JSON JSON是一种简单的数据表示方式,它易于理解.易于解析.易于记忆.但从另一方面来说,因为只有null.布尔.数字.字符串.数组和对象这几种数据类型,所以JSON有一定局限性.例如,JSON没 ...

  7. Java中 Random

    Java中的Random()函数 (2013-01-24 21:01:04) 转载▼ 标签: java random 随机函数 杂谈 分类: Java 今天在做Java练习的时候注意到了Java里面的 ...

  8. Zookeeper 系列(二)安装配制

    Zookeeper 系列(二)安装配制 一.Zookeeper 的搭建方式 Zookeeper 安装方式有三种,单机模式和集群模式以及伪集群模式. 单机模式 :Zookeeper 只运行在一台服务器上 ...

  9. OSGi 系列(六)之服务的使用

    OSGi 系列(六)之服务的使用 1. 为什么使用服务 降低服务提供者和服务使用者直接的耦合,这样更容易重用组件 隐藏了服务的实现细节 支持多个服务的实现.这样你可以互换这实现 2. 服务的使用 2. ...

  10. 旅游类APP原型模板分享——爱彼迎

    这是一款专为游客提供全球范围内短租服务的APP,可以让你不论出门在外或在家附近都能开展探索之旅,并且还可以获取世界各地独特房源.当地体验及好去处等相关信息. 这款APP层级清晰简明,此原型模板所用到的 ...