项目环境要求:
windows7
jdk1.8
apache-tomcat-8.0.53
eclipse
apache-maven-3.3.9
mysql
框架技术要求:
spring
springjdbc
springMVC
redis
下载和安装链接
maven安装包和maven安装步骤
https://download.csdn.net/download/qq_29914837/10672813
apache-tomcat-8.0.53下载和安装步骤
https://download.csdn.net/download/qq_29914837/10672823
jdk1.8下载和安装步骤
https://download.csdn.net/download/qq_29914837/10672804
redis-64.3.0.503下载和安装
新建一个工作区间,配置工作区间环境(window-preferences)
全部改为UTF-8,如图
配置安装maven,我这里是settings-person.xml,这是我自己重命名了的,安装包中的一般都是settings.xml
配置validation验证,解决每次保存项目时会长时间验证等待的问题,注意Manual不变,Build值勾选Classpath Dependency Validator项
前期准备工作完成,就可以开始创建maven项目了。
项目建立完成后需要调整项目的目录结构
Src/main/java 为正式环境的java代码
Src/main/resources 为正式环境的资源文件
Src/test/java 为测试环境的java代码
Src/rest/resources 为测试环境的资源文件
注意:此处新建选择source folder
source folder 设计出来就是用来放待编译的java文件
folder 就是最普通的文件
配置maven项目的参数和环境(右击项目–>properties)
Depoyment Assembly :配置源目录文件相对应的部署路径,我这里配置正式环境的部署路径为WEB-INF/classes,配置测试环境的部署路径为WEB-INF/test-classes
配置java Bulid Path (重要)
java build path面板的功能梳理
Source标签页,指定本工程的源码目录和输出目录。
Projects标签页,指定本工程所依赖的其他工程。
Libraries标签页,指定本工程所需的jar包和class目录等。
add external jars = 增加工程外部的包
add jars = 增加工程内包
add library = 增加一个库
add class folder = 增加一个类文件夹
Order And Export标签页,指定本工程的编译引用顺序和导出内容等。
设置“Dynamic Web Module”为3.0,java版本为1.8(注意:先设置java为1.8,保存后,再设置 Dynamic Web Module”为3.0)
如果项目出现:Cannot change version of project facet Dynamic web module to 3.0的提示信息,则参考下面解决方案,否则跳过此步骤。
原因:该开始选择会报错会提示选择不了这是因为新建项目的时候用了maven-artchetype-webapp由于这个catalog比较老,用的servlet还是2.3的
解决方案:
打开web.xml文件,修改头部为
然后 点击window --> show view --> Navigator 打开org.eclipse.wst.common.project.facet.core.xml文件,或者在项目的工作区间中搜索org.eclipse.wst.common.project.facet.core.xml文件
返回查看,Dynamic Web Module已变为3.0
Eclipse Maven 编译错误 Dynamic Web Module 3.0 requires Java 1.6 or newer 解决方案
但是 Eclipse 明明已经将编译级别设置为 1.8:
这是由于你的 Maven 编译级别是 jdk1.5 或以下,而你导入了 jdk1.6 以上的依赖包:查看 Eclipse 的 Navigator 视图下该项目的 .classpath 文件:
解决办法:
使用 maven-compiler-plugin 将 maven 编译级别改为 jdk1.6 以上:
spring-weixin
org.apache.maven.plugins
maven-compiler-plugin
3.1
1.8
UTF8
右击项目-maven - update 即可
最后新建server-将web项目部署到服务器上,启动tomcat
(备注:如果项目的jsp页面出错,是因为没有servlet的相关jar包,需要在
Pom.xml中配置)
javax.servlet
javax.servlet-api
3.1.0
provided
打开浏览器:http://127.0.0.1:8080/maven-springmvc-spring-springjdbc/
如果没有成功打开页面,则查看配置参数和环境
User.java 用户实体类
package com.entity.test.user;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name="user")
public class User implements Serializable {
private Integer id;//主键id
private String username;//用户名
private String password;//密码
public User() {
}
public User(Integer id, String username, String password) {
super();
this.id = id;
this.username = username;
this.password = password;
}
@Column(name="username",length = 10, nullable = true)
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Column(name="password",length = 10, nullable = true)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Column(name="id",length = 10, nullable = true)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
UserController.java 用户控制层类
package com.controller.test.user;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
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 org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.entity.test.user.User;
import com.service.test.user.UserService;
import com.util.exception.ExceptionUtil;
/**
* 所属类别:控制层方法类(用户)测试
* 用途:用户功能方法
* version:1.0
*/
@Controller
@RequestMapping(value="/user")
public class UserController {
@Autowired
private UserService userService;
public UserController() {
}
//用户登录方法
@RequestMapping(value="/login", method=RequestMethod.POST)
public String login(String username, String password, HttpSession session){
if (null == username || "".equals(username.trim())) {
throw new ExceptionUtil("用户名不能为空");
}
User user = userService.getUserByUsername(username);
if (null == user) {
throw new ExceptionUtil("用户名不存在");
}
if (!user.getPassword().equals(password)) {
throw new ExceptionUtil("密码不正确");
}
session.setAttribute("loginUser", user);
return "redirect:/user/users";
}
//用户列表
@RequestMapping(value="users", method=RequestMethod.GET)
public String list(Model model){
Map users = new HashMap();
for (User user : userService.getAllUsers()) {
users.put(user.getUsername(), user);
}
model.addAttribute("users", users);
return "test/list";
}
//进入添加界面
@RequestMapping(value="add", method=RequestMethod.GET)
public String add(@ModelAttribute("user") User user){
return "test/add";
}
//添加
@RequestMapping(value="add", method=RequestMethod.POST)
public String add(@Validated User user, BindingResult br, @RequestParam(value="attach") MultipartFile[] attachs, HttpServletRequest req) throws IOException{
if (br.hasErrors()) {
return "test/add";
}
String realPath = req.getSession().getServletContext().getRealPath("/resources/upload");
for (int i = 0; i < attachs.length; i++) {
MultipartFile attach = attachs[i];
if (attach.isEmpty()) {
continue;
}
File attachFile = new File(realPath + "/" + attach.getOriginalFilename());
FileUtils.copyInputStreamToFile(attach.getInputStream(), attachFile);
System.out.println(realPath + "/" + attach.getOriginalFilename());
System.out.println(attach.getName());
System.out.println(attach.getOriginalFilename());
System.out.println(attach.getContentType());
}
userService.register(user);
return "redirect:/user/users";
}
//展示用户
@RequestMapping(value="/{username}/show", method=RequestMethod.GET)
public String show(@PathVariable String username, Model model){
model.addAttribute(userService.getUserByUsername(username));
return "test/show";
}
//展示用户
@RequestMapping(value="/{username}/show", method=RequestMethod.GET, params="json")
@ResponseBody
public User show(@PathVariable String username){
return userService.getUserByUsername(username);
}
//进入编辑页面
@RequestMapping(value="/{username}/update", method=RequestMethod.GET)
public String update(@PathVariable String username, Model model){
model.addAttribute(userService.getUserByUsername(username));
return "test/update";
}
//编辑
@RequestMapping(value="/{username}/update", method=RequestMethod.POST)
public String update(@PathVariable String username, @Validated User user, BindingResult br){
if(br.hasErrors()){
return "test/update";
}
userService.update(user);
return "redirect:/user/users";
}
//删除
@RequestMapping(value="/{username}/delete", method=RequestMethod.GET)
public String delete(@PathVariable String username){
userService.removeUser(username);
return "redirect:/user/users";
}
//注销
@RequestMapping(value="/logout", method=RequestMethod.GET)
public String logout(HttpSession session){
session.removeAttribute("loginUser");
return "index";
}
/* //异常处理
@ExceptionHandler(value={ExceptionUtil.class})
public String handleLocalException(ExceptionUtil e, HttpServletRequest req){
req.setAttribute("error", e);
return "test/error";
}
*/
}
web.xml 配置文件
Archetype Created Web Application
/WEB-INF/views/index.jsp
org.springframework.web.util.IntrospectorCleanupListener
org.springframework.web.context.ContextLoaderListener
contextConfigLocation
classpath*:spring/applicationContext*.xml
spring
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:springMVC/spring-servlet.xml
1
spring
/
setcharacter
org.springframework.web.filter.CharacterEncodingFilter
encoding
utf-8
setcharacter
/
HiddenHttpMethodFilter
org.springframework.web.filter.HiddenHttpMethodFilter
HiddenHttpMethodFilter
springMVC3
java.lang.NullPointerException
/WEB-INF/views/commons/error/error_web_null.jsp
404
/WEB-INF/views/commons/error/error_web_404.jsp
405
/WEB-INF/views/commons/error/error405.jsp
500
/WEB-INF/views/commons/error/error500.jsp
UserDao.java 用户的Dao层接口
package com.dao.test.user;
import java.util.List;
import com.entity.test.user.User;
public interface UserDao {
//用户注册
public void register(User user);
//根据用户名查找用户
public User findUserByUserName(final String userName);
//查询用户集合
public List findAllUser();
//删除用户(通过用户名)
public boolean deleteByUsername(String username);
//编辑更新用户
public boolean update(User user);
}
UserDaoImpl.java 用户Dao层实现类
package com.dao.test.user;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import com.dao.test.user.UserDao;
import com.entity.test.user.User;
@Repository("userDao")
public class UserDaoImpl implements UserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public UserDaoImpl(){
}
public void register(User user) {
String sqlStr = "insert into user(userName,password) values(?,?)";
Object[] params = new Object[]{user.getUsername(),user.getPassword()};
jdbcTemplate.update(sqlStr, params);
}
public User findUserByUserName(String userName) {
String sqlStr = "select * from user where userName = ?" ;
List users = jdbcTemplate.query(sqlStr,new Object[]{userName} , new UserRowMapper());
if (null != users && !users.isEmpty()) {
return users.get(0);
}
return null;
}
@Override
public boolean deleteByUsername(String username){
int updateNum = jdbcTemplate.update("delete from user where username = '" + username + "'");
if (updateNum != 1) {
return false;
}
return true;
}
@Override
public List findAllUser() {
return jdbcTemplate.query("select * from user", new UserRowMapper());
}
private static class UserRowMapper implements RowMapper {
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
int i = 1;
User user = new User();
user.setId(rs.getInt(i++));
user.setUsername(rs.getString(i++));
user.setPassword(rs.getString(i++));
return user;
}
}
@Override
public boolean update(User user) {
return jdbcTemplate.update("update user set password = " + user.getPassword() + " where username = '" + user.getUsername() + "'") == 1 ? true : false;
}
}
UserService.java 用户service层接口
package com.service.test.user;
import java.util.List;
import com.entity.test.user.User;
public interface UserService {
public boolean register(User user);
public User loginCheck(User user);
public List getAllUsers();
public boolean removeUser(String username);
public User getUserByUsername(String username);
public boolean update(User user);
}
UserServiceImpl.java 用户service层实现类
package com.service.test.user;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dao.test.user.UserDao;
import com.entity.test.user.User;
@Service("userService")
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
public UserServiceImpl() {
}
@Override
public List getAllUsers() {
return userDao.findAllUser();
}
@Override
public boolean register(User user) {
User u = userDao.findUserByUserName(user.getUsername());
if (u == null || u.getId() == null || u.getId() == 0) {
userDao.register(user);
return true;
} else {
System.out.println("id=" + u.getId() + ", userName=" + u.getUsername() + ", password=" + u.getPassword());
return false;
}
}
@Override
public User loginCheck(User user) {
User u = userDao.findUserByUserName(user.getUsername());
System.out.println("id=" + u.getId() + ", userName=" + u.getUsername() + ", password=" + u.getPassword());
if (user.getPassword().equals(u.getPassword())) {
return u;
} else {
return null;
}
}
@Override
public boolean removeUser(String username) {
if (userDao.deleteByUsername(username)) {
return true;
}
return false;
}
@Override
public User getUserByUsername(String username) {
return userDao.findUserByUserName(username);
}
@Override
public boolean update(User user) {
return userDao.update(user);
}
}
jdbc.properties (连接数据库的配置资源文件信息)
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/framework
jdbc.username=root
jdbc.password=123456
log4j.properties (日志输出资源文件)
log4j.rootLogger=DEBUG,A1
# \u8f93\u51fa\u5230\u63a7\u5236\u53f0
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss} [\u65E5\u5FD7\u4FE1\u606F] %m%n
applicationContext_spring.xml (spring的资源配置文件)
${jdbc.driverClassName}
${jdbc.url}
${jdbc.username}
${jdbc.password}
5
30
10
60
5
0
60
30
true
false
applicationContext.xml (把多个配置文件集成在一个配置文件中,方便操作)其中redis的配置文件可以先跳过,后续会讲解
ExceptionUtil.java 自定义异常类
package com.util.exception;
/**
* 所属类别:工具类
* 用途:自定义的异常类
* @author yilei
* version:1.0
*/
public class ExceptionUtil extends RuntimeException {
public ExceptionUtil(String string) {
super(string);
}
}
TestException.java 异常测试类
package com.controller.test.exception;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
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.ResponseBody;
import com.util.exception.ExceptionUtil;
@Controller
@RequestMapping(value = "/exception")
public class TestException {
@RequestMapping("/exception/{id}")
@ResponseBody
public Object hello(@PathVariable String id) {
if(id.equals("0")){
throw new ExceptionUtil("自定义有异常");
}else if (id.equals("1")) {// NullPointerException控制值异常
throw new NullPointerException("空指针异常");
} else if (id.equals("2")) {// 数学运算异常
int value = 1 / 0;
return "java.lang.ArithmeticException";
} else {
return "ok";
}
}
//异常处理,基于注解的方式,但是需要进行自定义异常的类中都写一个相同的方法才可生效。如果使用这种方式。
/* @ExceptionHandler(value={ExceptionUtil.class})
public String handleLocalException(ExceptionUtil e, HttpServletRequest req){
req.setAttribute("error", e);
return "error/error";
}*/
}
spring-servlet.xml (springmvc的配置资源文件)
commons/error/error_spring_ExceptionUtil
commons/error/error_spring_null
commons/error/error_spring_math
备注:如果对springMVC中的异常处理过程不太清楚的话,可以参考本人的另一篇博文,有详细结合了本项目讲解了异常处理过程和几种方式特点
springMVC的几种异常处理方式
https://blog.csdn.net/qq_29914837/article/details/82697089
接下来是jsp页面的建立,如图所示,其中error文件下的jsp文件,为异常处理页面,可以帮助大家更好的理解集中异常处理方式的区别和特点,实际项目运用中,保留一到两个页面即可。
error_spring_ExceptionUtil.jsp (用于springmvc中配置的自定义异常时输出)
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
Insert title here
error_spring_ExceptionUtil.jsp
spirngmvc配置异常-自定义异常
error.jsp (用于springmvc中配置的自定义异常(基于注解方式)时输出)
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="sf" %>
异常抛出处理
${error.message}
error_spring_math.jsp (用于springmvc中配置的数学算术运行异常时输出)
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
Insert title here
error_spring_math.jsp
spirngmvc配置异常-数学算术运算异常
error_spring_null.jsp (用于springmvc中配置的空指针异常时输出)
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
页面发生错误
error_spring_null.jsp
springmvc异常处理-空指针异常
error_web_404.jsp (用于web.xml中配置的404异常时输出)
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
Insert title here
error_web_404.jsp
web.xml配置的404异常
error_web_null.jsp (用于web.xml中配置的空指针异常时输出)
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
页面发生错误
error_web_null.jsp
web.xml配置的空指针异常
add.jsp ( 添加用户)
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="sf" %>
添加用户
编号:
姓名:
密码:
文件:
文件:
list.jsp(用户列表)
<%@page import="com.entity.test.user.User"%>
<%@page import="org.eclipse.jdt.internal.compiler.batch.Main"%>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
User user = (User) session.getAttribute("loginUser");
boolean isLogin = null == user ? false : true;
%>
用户列表展示
添加用户
欢迎${loginUser.username}的到来!
注销
用户编号
用户姓名
用户密码
操作
${uentry.value.id}
${uentry.value.username}
${uentry.value.password}
编辑 删除
show.jsp(查看用户)
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="sf" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
用户展示页面
编号: ${user.id}
姓名: ${user.username}
密码: ${user.password}
返回用户列表展示界面
update.jsp(编辑用户)
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="sf" %>
用户编辑界面
编号:
姓名:
密码:
index.jsp (首页,用户登录界面)
<%@ page language="java" contentType="text/html; utf-8"
pageEncoding="utf-8"%>
用户登录界面
登录界面
pom.xml maven依赖配置
4.0.0
com.yi
maven-springmvc-spring-springjdbc
war
0.0.1-SNAPSHOT
maven-springmvc-spring-springjdbc Maven Webapp
http://maven.apache.org
4.3.10.RELEASE
javax.servlet
javax.servlet-api
3.1.0
provided
junit
junit
4.11
test
org.springframework
spring-test
${spring.version}
test
org.springframework
spring-context
${spring.version}
org.springframework
spring-jdbc
${spring.version}
org.springframework
spring-web
${spring.version}
org.springframework
spring-core
${spring.version}
org.springframework
spring-webmvc
${spring.version}
org.aspectj
aspectjweaver
1.8.5
mysql
mysql-connector-java
5.1.35
com.mchange
c3p0
0.9.5
jstl
jstl
1.2
org.hibernate
hibernate-validator
5.1.2.Final
commons-fileupload
commons-fileupload
1.3.1
com.fasterxml.jackson.core
jackson-databind
2.5.2
org.codehaus.jackson
jackson-core-asl
1.9.13
org.codehaus.jackson
jackson-mapper-asl
1.9.13
com.thoughtworks.xstream
xstream
1.4.7
commons-lang
commons-lang
2.6
provided
org.eclipse.persistence
javax.persistence
2.1.1
redis.clients
jedis
2.9.0
org.springframework.data
spring-data-redis
1.7.2.RELEASE
maven-springmvc-spring-springjdbc
引用方法
运行sql,建立用户表(已插入一条数据,admin,123456)
SET FOREIGN_KEY_CHECKS=0;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(50) NOT NULL AUTO_INCREMENT,
`userName` varchar(30) DEFAULT NULL,
`password` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
INSERT INTO `user` VALUES ('1', 'admin', '123456');
按照要求建立以上全部文件即可
启动项目,打开浏览器
http://127.0.0.1:8080/maven-springmvc-spring-springjdbc
项目搭建基本完成,如果需要集成redis请参考本人另一篇博文
https://blog.csdn.net/qq_29914837/article/details/82686359