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. LeetCode关于数组中求和的题型

    15. 3Sum:三数之和为0的组合 Given an array S of n integers, are there elements a, b, c in S such that a + b + ...

  2. mysql 列转行

    第一种方法:使用序列化表的方法实现列转行 第一种方法:使用UNION的方法实现列转行 第二种方法:使用序列化表的方法实现列转行

  3. CentOS 下安装 OpenOffice4.0

    一.更新服务器 yum源 [root@APP2 /]# yum clean all [root@APP2 /]# yum makecache [root@APP2 /]# yum update 1.首 ...

  4. Spring @Qualifier

    先说明下场景,代码如下: 有如下接口: public interface EmployeeService { public EmployeeDto getEmployeeById(Long id); ...

  5. django创建工程,用命令

    django创建工程的命令 >>python C:\Python33\Lib\site-packages\django\bin\django-admin.py startproject p ...

  6. Finding Hotels

    Finding Hotels http://acm.hdu.edu.cn/showproblem.php?pid=5992 Time Limit: 2000/1000 MS (Java/Others) ...

  7. iOS下JS与OC互相调用(七)--Cordova 环境搭建

    Cordova大家可能比较陌生,但肯定听过 PhoneGap ,Cordova 就是 PhoneGap 被 Adobe 收购后所改的名字.它是一个可以让 JS 与原生代码互相通信的一个库,并且提供了一 ...

  8. python之面向对象之反射运用

    先看下hasattr和getattr在反射中的用法 import sys class apache(object): def __init__(self,tcp): self.tcp = tcp de ...

  9. 88. Merge Sorted Array 后插

    合并两个排序的整数数组A和B变成一个新的数组.给出A=[1,2,3,4],B=[2,4,5,6],返回 [1,2,2,3,4,4,5,6] 假设A具有足够的空间(A数组的大小大于或等于m+n)去添加B ...

  10. 粘性Service

    粘性Service就是一种服务 把他删去他又会马上创建 原理是在这个服务中去开启线程不断检测此服务是否存在如果不存在,咋就会重新创建 import android.app.Activity; impo ...