上一篇介绍了SpringMVC的入门,接下来编写用SpringMVC实现用户管理功能,
首先装备环境:贴出导包的目录结构:(可以从下面贴出的源码下载链接中下载源码,项目的jar包链接中下载)
1、在官网下载Spring的包,解压之后把dist下的所有包导入工程,同时导入日志包
2、导入jstl包
3、导入beanValidator.jar包实现服务器端的验证
第二部在WEB-INF/jsp/user下创建list.jsp,add.jsp
目录结构:
第三步写Web.xml文件,配置spring中的字符编码过滤器解决编码问题,配置SpringMVC的前置控制器DispatcherServlet,
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name></display-name>
<filter>
<filter-name>filter</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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>web</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>web</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
接着写实体类User:
package com.springmvc.pojo;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
public class User {
public User() {
}
private String username;
private String nickName;
private String password;
private String email;
@NotEmpty(message="用户名不能为空")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@NotEmpty(message="昵称不能为空")
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
@Size(min=1,max=10,message="密码的长度在1-10位左右")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Email(message="邮箱的格式不正确")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public User(String username, String nickName, String password, String email) {
this.username = username;
this.nickName = nickName;
this.password = password;
this.email = email;
}
}
接着是编写UserController控制器:
package com.springmvc.controller;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.springmvc.exception.UserException;
import com.springmvc.pojo.User;
@Controller
@RequestMapping("/user")
public class UserController{
private Map<String,User> users=new HashMap<String, User>();
/**
* 为了简化开发,下面是初始化数据,模拟数据库
*/
public UserController(){
users.put("zs", new User("张三","zs","123","123@qq.com"));
users.put("ls", new User("李四","ls","456","456@qq.com"));
users.put("ww", new User("王五","ww","789","789@qq.com"));
}
@RequestMapping(value="/users",method=RequestMethod.GET)
public String list(Model model){
model.addAttribute("users", users);
return "user/list";
}
@RequestMapping(value="/saveUI",method=RequestMethod.GET)
public String saveUI(@RequestParam(value="nickName",required=false) String nickName,@ModelAttribute(value="user") User user,Model model) {
// TODO Auto-generated method stub
//model.addAttribute(new User());//默认的key是该对象的类型的首个字母大写
if(nickName!=null){
model.addAttribute( users.get(nickName));
}
System.out.println("------"+nickName);
return "user/add";
}
@RequestMapping(value="/save",method=RequestMethod.POST)
public String save(@Valid User user,BindingResult br){//一定要紧跟Validate之后写验证结果类
//model.addAttribute("user", user);
if(br.hasErrors()){
return "user/add";//如果有错误直接跳转到add视图
}
System.out.println("保存用户。。。。"+user.getUsername());
users.put(user.getNickName(), user);
return "redirect:/user/users";
}
/**
* REST风格
* @param nickName
* @return
*/
@RequestMapping(value="/delete/{nickName}",method=RequestMethod.GET)
public String delete(@PathVariable(value="nickName") String nickName){
users.remove(nickName);
return "redirect:/user/users";
}
@RequestMapping(value="/login",method=RequestMethod.POST)
public String login(String username,String password,HttpSession session){
if(!users.containsKey(username)){
throw new UserException("用户名不存在");
}
User user= users.get(username);
if(!user.getPassword().equals(password)){
throw new UserException("密码不存在");
}
session.setAttribute("user", user);
return "redirect:/user/users";
}
/**
* 局部异常处理,只能处理这个控制器中的异常
* @param e
* @param request
* @return
*/
// @ExceptionHandler(value=UserException.class)
// public String handlerException(UserException e,HttpServletRequest request){
// request.setAttribute("error", e);
// return "/login.jsp";
// }
}
接着在web-inf下创建web-servlet.xml:(记住这里的web和上面的
servlet-name>web</servlet-name>
相对应)
<?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:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
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
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
">
<!-- 添加注解扫描器 -->
<context:component-scan base-package="com.springmvc.controller"></context:component-scan>
<!-- 会自动注册DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter 两个bean,是spring MVC为@Controllers分发请求所必须的。
默认的注解映射的支持
-->
<mvc:annotation-driven/>
<!-- 包含WEB程序的css等静态文件 -->
<mvc:resources location="/css/" mapping="/css/**"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp" />
</bean>
<!-- 配置全局异常 -->
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<!-- 定义默认的异常处理页面,当该异常类型的注册时使用
<property name="defaultErrorView" value="error"></property>-->
<!-- 定义需要特殊处理的异常,用类名或完全路径名作为key,异常也页名作为值 -->
<property name="exceptionMappings">
<props>
<prop key="com.springmvc.exception.UserException">error</prop>
</props>
</property>
</bean>
</beans>
下面是自定义的异常UserException:
package com.springmvc.exception;
public class UserException extends RuntimeException {
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
}
}
页面效果: