1、工程结构:
spring mvc的访问地址是使用REST风格
2、web.xml的配置
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/web-main.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
3、书写spring配置文件 /WebRoot/web-main.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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.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">
<mvc:annotation-driven/>
<mvc:resources location="/resources/" mapping="/resources/**"/>
<context:component-scan base-package="cn.edu.hj.controller"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5000000"></property>
</bean>
</beans>
4、操作中涉及到的一个User javabean
详细的注解验证可看这个
package cn.edu.hj.bean;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
public class User {
private String username;
private String password;
private String email;
public User(){
}
public User(String username, String password, String email) {
this.username = username;
this.password = password;
this.email = email;
}
@NotEmpty(message = "用户名不能为空")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@NotEmpty(message = "密码不能为空")
@Size(min = 4, max = 8, message = "密码在4~8位之间")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@NotEmpty(message = "email不能为空")
@Email(message = "email格式不正确")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString(){
return username+"#"+password+"#"+email;
}
}
5、模拟用户增删改查以及登录和上传文件的action处理类
package cn.edu.hj.controller;
import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.apache.commons.io.FileUtils;
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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import cn.edu.hj.bean.User;
@Controller
@RequestMapping(value = "/user")
@SessionAttributes(value = "loginUser")
public class UserController {
Map<String,User> users = new LinkedHashMap<String,User>();
public UserController(){
System.out.println("初始化....");
users.put("ldh",new User("ldh", "123", "ldh@qq.com"));
users.put("gfc",new User("gfc", "123", "gfc@qq.com"));
users.put("zxy",new User("zxy", "123", "zxy@qq.com"));
users.put("lm ",new User("lm ", "123", " lm@qq.com"));
}
public void init(Model model,User user){
if(user != null){
users.put(user.getUsername(), user);
}
model.addAttribute("users", users);
}
@RequestMapping(value = "/list.htm")
public String list(Model model){
init(model, null);
return "user/userlist";
}
@RequestMapping(value = "/add.htm", method = RequestMethod.GET)
public String add(Model model){
model.addAttribute(new User());
return "user/adduser";
}
@RequestMapping(value = "/add.htm", method = RequestMethod.POST)
public String add(@Valid User user,BindingResult binding,Model model){
if(binding.hasErrors()){
return "user/adduser";
}
init(model, user);
return "redirect:/user/list.htm";
}
@RequestMapping(value = "/{username}.htm",method = RequestMethod.GET)
public String show(@PathVariable String username,Model model){
User user = users.get(username);
model.addAttribute("user", user);
return "user/show";
}
@RequestMapping(value = "/delete/{username}.htm",method = RequestMethod.GET)
public String delete(@PathVariable String username){
users.remove(username);
return "redirect:/user/list.htm";
}
@RequestMapping(value = "/update/{username}.htm",method = RequestMethod.GET)
public String update(@PathVariable String username,Model model){
User user = users.get(username);
model.addAttribute("user", user);
return "user/adduser";
}
@RequestMapping(value = "/update/{username}.htm",method = RequestMethod.POST)
public String update(@PathVariable String username,@Valid User user,BindingResult br){
if(br.hasErrors()){
return "/user/adduser";
}
users.put(user.getUsername(), user);
return "redirect:/user/list.htm";
}
@ResponseBody
@RequestMapping(value = "/{username}.htm",params = "json")
public User showJson(@PathVariable String username,Model model){
System.out.println("username:"+username);
return users.get(username);
}
@RequestMapping(value = "/login.htm",method = RequestMethod.GET)
public String login(){
return "/user/login";
}
@RequestMapping(value = "/login.htm",method = RequestMethod.POST)
public String login(String username,String password,Model model){
if(!users.containsKey(username)){
throw new RuntimeException("用户名不存在!");
}
if(!password.equals(users.get(username).getPassword())){
throw new RuntimeException("密码不正确");
}
model.addAttribute("loginUser", users.get(username));
return "redirect:/user/list.htm";
}
@ExceptionHandler(value = {RuntimeException.class})
public String handlerException(Exception ex,HttpServletRequest req){
req.setAttribute("ex", ex);
return "error";
}
@RequestMapping(value = "/redir.htm")
public String redir(Model model,RedirectAttributes ra){
ra.addFlashAttribute("movie", "海贼王");
return "redirect:/user/list.htm";
}
@RequestMapping(value = "upload.htm",method = RequestMethod.GET)
public String uploadPhoto(){
return "user/upload";
}
@RequestMapping(value = "upload.htm",method = RequestMethod.POST)
public String uploadPhoto(MultipartFile photo,Model model,HttpServletRequest req){
System.out.println(photo.getContentType());
System.out.println(photo.getName());
System.out.println(photo.getOriginalFilename());
String realpath = req.getSession().getServletContext().getRealPath("/upload/");
System.out.println(realpath);
try {
FileUtils.copyInputStreamToFile(photo.getInputStream(), new File(realpath + "/" +photo.getOriginalFilename()));
} catch (IOException e) {e.printStackTrace();}
model.addAttribute("message", "上传成功");
return "user/upload";
}
@RequestMapping(value = "uploads.htm",method = RequestMethod.POST)
public String uploadPhoto(@RequestParam(required = false)MultipartFile[] photos,Model model,HttpServletRequest req){
String realpath = req.getSession().getServletContext().getRealPath("/upload/");
try {
for(MultipartFile photo : photos){
if(photo.isEmpty())continue;
FileUtils.copyInputStreamToFile(photo.getInputStream(), new File(realpath + "/" +photo.getOriginalFilename()));
}
} catch (IOException e) {e.printStackTrace();}
model.addAttribute("message", "上传成功");
return "user/upload";
}
}
6,相关的jsp页面
【1】/WebRoot/index.jsp页面
<body>
This is my JSP page. <br>
</body>
【2】/WebRoot/WEB-INF/jsp/error.jsp页面 用于显示错误信息的,action中抛出的异常被在此处显示
<body>
${ex.message}
</body>
【3】/WebRoot/WEB-INF/jsp/user/userlist.jsp页面 用于显示用户列表的
<body>
<a href="add.htm">Add</a> ${loginUser.username } ${movie }<br/>
<%Map<String,User> users = (Map<String,User>)request.getAttribute("users");
if(users != null){
for(User user : users.values()){
%>
<%=user%>
<a href="<%=user.getUsername()%>.htm">详细</a>
<a href="update/<%=user.getUsername()%>.htm">修改</a>
<a href="delete/<%=user.getUsername()%>.htm">删除</a><br/>
<% }
}
%>
<a href="login.htm">Login</a><br/>
</body>
【4】/WebRoot/WEB-INF/jsp/user/adduser.jsp页面 用于添加修改用户的
<body>
<%@taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<sf:form method="post" modelAttribute="user">
username:<sf:input path="username"/><sf:errors path="username"/><br/>
password:<sf:password path="password"/><sf:errors path="password"/><br/>
email:<sf:input path="email"/><sf:errors path="email"/><br/>
<input type="submit" />
</sf:form>
</body>
【5】/WebRoot/WEB-INF/jsp/user/show.jsp页面 用于显示某个用户信息的
<body>
<a href="javascript:history.go(-1);">返回</a><br/>
${user}
</body>
【6】/WebRoot/WEB-INF/jsp/user/login.jsp页面 用户登录的
<body>
<form method="post" action="login.htm">
username:<input type="text" name="username"/><sf:errors path="username"/><br/>
password:<input type="password" name="password"/><sf:errors path="password"/><br/>
<input type="submit" />
</form>
</body>
【7】/WebRoot/WEB-INF/jsp/user/upload.jsp页面 用户登录的
<body>
<form method="post" action="uploads.htm" enctype="multipart/form-data">
<input type="file" name="photos"><br/>
<input type="file" name="photos"><br/>
<input type="file" name="photos"><br/>
<input type="submit" />${message }
</form>
</body>
整个工程的下载地址为: http://download.csdn.net/detail/wxwzy738/5224307
相关知识
基于JSP+Servlet+Mysql的宠物管理系统(简单增删改查)
基于Springboot+vue的宠物之家领养救助管理系统的设计与实现
SSM+宠物领养系统毕业设计
基于Spring Boot的宠物医院管理系统设计与实现
宠物商店项目,增删改查
基于Spring Boot的宠物医院管理系统的设计
基于spring boot+vue的流浪宠物领养救助管理系统
springboot宠物领养管理系统论文
springboot信息管理毕业设计简单的任务书分享
基于Spring Boot框架的宠物猫售卖商城交易管理系统java源码分享
网址: 二、spring mvc模拟用户增删改查以及登录和上传文件的相关流程 https://m.mcbbbk.com/newsview473494.html
上一篇: 宠物医院门店 |
下一篇: 「安阳宠诺宠物诊所招聘信息」 |