springmvc 孔浩

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/**/" />
 
原文地址:https://www.cnblogs.com/wang-jing/p/4557150.html