百瑞网站建设,html教程电子书,广州天极科技,360来店通自助营销平台目录
一、Spring练习环境搭建。
#xff08;1#xff09;设置服务器启动的展示页面。
#xff08;2#xff09;创建工程步骤。
#xff08;3#xff09;applicationContext.xml配置文件。
#xff08;4#xff09;spring-mvc.xml配置文件。
#xff08;5#x…目录
一、Spring练习环境搭建。
1设置服务器启动的展示页面。
2创建工程步骤。
3applicationContext.xml配置文件。
4spring-mvc.xml配置文件。
5web.xml配置文件。
6jdbc.properties配置文件。
7log4j.properties配置文件。
二、SSM项目结构。
1conctroller层。
1.1RoleController类。
1.2UserController类。
1.3jsp文件的部分截取参考。
2service层。
2.1RoleService接口与RoleServiceImpl类。
2.2UserService接口与UserService类。
3dao层。
3.1RoleDao接口与RoleDaoImpl类。
3.2UserDao接口与UserDaoImpl类。
4domain存放POJO类。
4.1Role类。
4.2 User类。
5utils存放工具类。
6interceptor拦截器。
三、SpringMVC的视图解析器的前缀后缀添加规则
四、业务功能实现步骤。 一、Spring练习环境搭建。 1设置服务器启动的展示页面。
% page languagejava contentTypetext/html; charsetUTF-8pageEncodingUTF-8%
!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd
html
head
meta http-equivContent-Type contenttext/html; charsetUTF-8
title主页/title
/head
body%response.sendRedirect(request.getContextPath()/pages/main.jsp);%
/body
/html
2创建工程步骤。
IDEA项目右键-新建-新模块 -选择Maven-选择骨架或不选-next-命名-把项目缺少的文件添加上去。
3applicationContext.xml配置文件。
?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexmlns:contexthttp://www.springframework.org/schema/contextxsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd!--1、加载jdbc.properties文件--context:property-placeholder locationclasspath:jdbc.properties/!--2、配置数据源对象--bean iddataSource classcom.mchange.v2.c3p0.ComboPooledDataSourceproperty namedriverClass value${jdbc.Driver}/property namejdbcUrl value${jdbc.url}/property nameuser value${jdbc.user}/property namepassword value${jdbc.password}//bean!--3、配置JdbcTemplate对象--bean idjdbcTemplate classorg.springframework.jdbc.core.JdbcTemplateproperty namedataSource refdataSource//bean!--配置RoleService--bean idroleService classservice.impl.RoleServiceImplproperty nameroleDao refroleDao//bean!--配置RoleDao--bean idroleDao classdao.impl.RoleDaoImplproperty namejdbcTemplate refjdbcTemplate//bean!--配置UserService--bean iduserService classservice.impl.UserServiceImplproperty nameuserDao refuserDao/property nameroleDao refroleDao//bean!--配置UserDao--bean iduserDao classdao.impl.UserDaoImplproperty namejdbcTemplate refjdbcTemplate//bean/beans
4spring-mvc.xml配置文件。
?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexmlns:mvchttp://www.springframework.org/schema/mvcxmlns:contexthttp://www.springframework.org/schema/contextxsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd!--1、mvc的注解驱动--mvc:annotation-driven/!--2、配置视图解析器--bean classorg.springframework.web.servlet.view.InternalResourceViewResolverproperty nameprefix value/pages//property namesuffix value.jsp//bean!--3、静态资源权限开放--mvc:default-servlet-handler/!--4、组件扫描--context:component-scan base-packagecontroller/!--5、拦截器配置--mvc:interceptorsmvc:interceptor!--配置对哪些资源执行操作--mvc:mapping path/**/!--配置哪些资源排除拦截操作--mvc:exclude-mapping path/user/login/bean classinterceptor.PrivilegeInterceptor//mvc:interceptor/mvc:interceptors
/beans
5web.xml配置文件。
?xml version1.0 encodingUTF-8?
web-app xmlnshttp://xmlns.jcp.org/xml/ns/javaeexmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsdversion4.0!--Spring监听器--listenerlistener-classorg.springframework.web.context.ContextLoaderListener/listener-class/listener!--Spring监听器的全局的初始化参数--context-paramparam-namecontextConfigLocation/param-nameparam-valueclasspath:applicationContext.xml/param-value/context-param!--SpringMVC的前端控制器--servletservlet-nameDispatcherServlet/servlet-nameservlet-classorg.springframework.web.servlet.DispatcherServlet/servlet-classinit-paramparam-namecontextConfigLocation/param-nameparam-valueclasspath:spring-mvc.xml/param-value/init-paramload-on-startup1/load-on-startup!--表示服务器启动就创建--/servletservlet-mappingservlet-nameDispatcherServlet/servlet-nameurl-pattern//url-pattern/servlet-mappingfilterfilter-nameCharacterEncodingFilter/filter-namefilter-classorg.springframework.web.filter.CharacterEncodingFilter/filter-classinit-paramparam-nameencoding/param-nameparam-valueUTF-8/param-value/init-param/filterfilter-mappingfilter-nameCharacterEncodingFilter/filter-nameurl-pattern/*/url-pattern/filter-mapping
/web-app
6jdbc.properties配置文件。
jdbc.Drivercom.mysql.cj.jdbc.Driver
jdbc.urljdbc:mysql://localhost:3306/test?useUnicodetruecharacterEncodingUTF-8
jdbc.userroot
jdbc.passwordroot 注意url中的 后面是防止乱码的方法之一。
7log4j.properties配置文件。
### direct log messages to stdout ###
log4j.appender.stdoutorg.apache.log4j.ConsoleAppender
log4j.appender.stdout.TargetSystem.out
log4j.appender.stdout.layoutorg.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern%d{ABSOLUTE} %5p %c{1}:%L - %m%n### direct messages to file mylog.log ###
log4j.appender.fileorg.apache.log4j.FileAppender
log4j.appender.file.Filec:/mylog.log
log4j.appender.file.layoutorg.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern%d{ABSOLUTE} %5p %c{1}:%L - %m%n### set log levels - for more verbose logging change info to debug ###log4j.rootLoggerinfo, stdout
二、SSM项目结构。
1conctroller层。
1.1RoleController类。
package controller;
Controller
RequestMapping(/role)
public class RoleController {Resource(name roleService)private RoleService roleService;RequestMapping(/list)public ModelAndView list(){ModelAndView modelAndView new ModelAndView();ListRole roleList roleService.list();//设置模型modelAndView.addObject(roleList,roleList);//设置视图modelAndView.setViewName(role-list);return modelAndView;}RequestMapping(/save)//参数是用来接收表单数据public String save(Role role){roleService.save(role);return redirect:/role/list;}
}1.2UserController类。
package controller;
Controller
RequestMapping(/user)
public class UserController {Resource(name userService)private UserService userService;Autowiredprivate RoleService roleService;RequestMapping(/list)public ModelAndView list(){ModelAndView modelAndView new ModelAndView();ListUser userList userService.list();modelAndView.addObject(userList,userList);modelAndView.setViewName(user-list);return modelAndView;}RequestMapping(/saveUI)public ModelAndView saveUI(){ModelAndView modelAndView new ModelAndView();ListRole roleList roleService.list();modelAndView.addObject(roleService,roleList);modelAndView.setViewName(user-add);return modelAndView;}RequestMapping(/save)public String save(User user,Long[] roleIds){userService.save(user,roleIds);return redirect:/user/list;}RequestMapping(/del/{userId})//Restful风格public String del(PathVariable(name userId) Long userId){userService.del(userId);return redirect:/user/list;}RequestMapping(/login)public String login(String username, String password, HttpSession session){User user userService.login(username,password);if (user ! null){//登录成功将user存储到sessionsession.setAttribute(user,user);return redirect:/index.jsp;}return redirect:/login.jsp;}
}
1.3jsp文件的部分截取参考。
% taglib prefixc urihttp://java.sun.com/jsp/jstl/core %
tbodyc:forEach items${roleList} varroletrtdinput nameids typecheckbox/tdtd${role.id}/tdtd${role.roleName}/tdtd${role.roleDesc}/tdtd classtext-centera href# classbtn bg-olive btn-xs删除/a/td/tr/c:forEach
/tbody
% taglib prefixc urihttp://java.sun.com/jsp/jstl/core %
div classcol-md-10 datac:forEach items${roleService} varroleinput typecheckbox nameroleIds value${role.id}${role.roleName}/c:forEach
/div
% taglib prefixc urihttp://java.sun.com/jsp/jstl/core %
scriptfunction delUser(userId) {if (confirm(您确认要删除吗?)){location.href${pageContext.request.contextPath}/user/del/userId;}}
/script
tbodyc:forEach items${userList} varusertrtdinput nameids typecheckbox/tdtd${user.id}/tdtd${user.username}/tdtd${user.email}/tdtd${user.phoneNum}/tdtd classtext-centerc:forEach items${user.roles} varrolenbsp;${role.roleDesc}/c:forEach/tdtd classtext-centera hrefjavascript:void(0); onclickdelUser(${user.id}) classbtn bg-olive btn-xs删除/a/td/tr/c:forEach
/tbody
2service层。
2.1RoleService接口与RoleServiceImpl类。
package service;
import domain.Role;
import java.util.List;
public interface RoleService {public void save(Role role);public ListRole list();
}package service.impl;
public class RoleServiceImpl implements RoleService {private RoleDao roleDao;public void setRoleDao(RoleDao roleDao) {this.roleDao roleDao;}Overridepublic ListRole list() {ListRole roleList roleDao.findAll();return roleList;}Overridepublic void save(Role role) {roleDao.save(role);}
}2.2UserService接口与UserService类。
package service;
public interface UserService {public ListUser list();void save(User user, Long[] roleIds);void del(Long userId);User login(String username, String password);
}package service.impl;
public class UserServiceImpl implements UserService {private UserDao userDao;public void setUserDao(UserDao userDao) {this.userDao userDao;}private RoleDao roleDao;public void setRoleDao(RoleDao roleDao) {this.roleDao roleDao;}Overridepublic ListUser list() {ListUser userList userDao.findAll();//封装userList中的每一个User的roles数据for (User user : userList) {//获得user的idLong id user.getId();//将id作为参数查询当前userId对应的Role集合数据ListRole roles roleDao.findRoleById(id);user.setRoles(roles);}return userList;}Overridepublic void save(User user, Long[] roleIds) {//第一步向sys_user表中存储数据Long userId userDao.save(user);//第二步向sys_user_role关系表中存储数据userDao.saveUserRoleRel(userId,roleIds);}Overridepublic void del(Long userId) {//1、删除sys_user_role关系表userId数据userDao.delUserRoleRel(userId);//2、删除sys_user表userId数据userDao.del(userId);}Overridepublic User login(String username, String password) {try {User user userDao.findByUsernameAndPassword(username,password);return user;}catch (EmptyResultDataAccessException e){//如果有这个异常说明搜索后的结果为空return null;}}
}3dao层。
3.1RoleDao接口与RoleDaoImpl类。
package dao;
public interface RoleDao {public void save(Role role);public ListRole findAll();ListRole findRoleById(Long id);
}package dao.impl;
public class RoleDaoImpl implements RoleDao {private JdbcTemplate jdbcTemplate;public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {this.jdbcTemplate jdbcTemplate;}Overridepublic ListRole findAll() {ListRole roleList jdbcTemplate.query(select * from sys_role, new BeanPropertyRowMapperRole(Role.class));return roleList;}Overridepublic void save(Role role) {jdbcTemplate.update(insert into sys_role values(?,?,?),null,role.getRoleName(),role.getRoleDesc());}Overridepublic ListRole findRoleById(Long id) {//其实就是ur表的每一个roleId把r表全部查找一遍把ur.roleId r.id并且ur.userId ?的结果就是满足条件的ListRole roles jdbcTemplate.query(select * from sys_user_role ur,sys_role r where ur.roleId r.id and ur.userId ?, new BeanPropertyRowMapper(Role.class), id);return roles;}
}3.2UserDao接口与UserDaoImpl类。
package dao;
public interface UserDao {ListUser findAll();Long save(User user);void saveUserRoleRel(Long id, Long[] roleIds);void delUserRoleRel(Long userId);void del(Long userId);User findByUsernameAndPassword(String username, String password);
}package dao.impl;
public class UserDaoImpl implements UserDao {private JdbcTemplate jdbcTemplate;public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {this.jdbcTemplate jdbcTemplate;}Overridepublic ListUser findAll() {ListUser userList jdbcTemplate.query(select * from sys_user,new BeanPropertyRowMapper(User.class));return userList;}Override//里面有获取数据表的主键id的方式public Long save(User user) {//创建PreparedStatementCreatorPreparedStatementCreator creator new PreparedStatementCreator() {Overridepublic PreparedStatement createPreparedStatement(Connection connection) throws SQLException {//使用原始jdbc完成有个PreparedStatement的组件PreparedStatement preparedStatement connection.prepareStatement(insert into sys_user values(?,?,?,?,?), PreparedStatement.RETURN_GENERATED_KEYS);//PreparedStatement.RETURN_GENERATED_KEYS,就是1的意思也可以写1preparedStatement.setObject(1,null);preparedStatement.setString(2,user.getUsername());preparedStatement.setString(3,user.getEmail());preparedStatement.setString(4,user.getPassword());preparedStatement.setString(5,user.getPhoneNum());return preparedStatement;}};//创建keyHolder获取自增主键idGeneratedKeyHolder keyHolder new GeneratedKeyHolder();jdbcTemplate.update(creator, keyHolder);//获取生成的主键long userId keyHolder.getKey().longValue();//不能获取主键的方式//jdbcTemplate.update(insert into sys_user values(?,?,?,?,?),null,user.getUsername(),user.getEmail(),user.getPassword(),user.getPhoneNum());return userId; //返回当前保存用户的id该id是数据库自动生成的}Overridepublic void saveUserRoleRel(Long userId, Long[] roleIds) {for (Long roleId : roleIds) {jdbcTemplate.update(insert into sys_user_role values(?,?),userId,roleId);}}Overridepublic void delUserRoleRel(Long userId) {jdbcTemplate.update(delete from sys_user_role where userId ?,userId);}Overridepublic void del(Long userId) {jdbcTemplate.update(delete from sys_user where id ?,userId);}Overridepublic User findByUsernameAndPassword(String username, String password) throws EmptyResultDataAccessException {User user jdbcTemplate.queryForObject(select * from sys_user where username ? and password ?, new BeanPropertyRowMapper(User.class), username, password);return user;}
}4domain存放POJO类。
4.1Role类。
package domain;
public class Role {private Long id;private String roleName;private String roleDesc;public Long getId() {return id; }public void setId(Long id) {this.id id; }public String getRoleName() { return roleName;}public void setRoleName(String roleName) { this.roleName roleName;}public String getRoleDesc() { return roleDesc;}public void setRoleDesc(String roleDesc) { this.roleDesc roleDesc;}Overridepublic String toString() {return Role{ id id , roleName roleName \ , roleDesc roleDesc \ };}
}4.2 User类。
package domain;
import java.util.List;
public class User {private Long id;private String username;private String email;private String password;private String phoneNum;//当前用户具备哪些角色private ListRole roles;public ListRole getRoles() { return roles; }public void setRoles(ListRole roles) {this.roles roles; }public Long getId() { return id; }public void setId(Long id) { this.id id; }public String getUsername() { return username; }public void setUsername(String username) { this.username username; }public String getEmail() { return email; }public void setEmail(String email) { this.email email; }public String getPassword() { return password; }public void setPassword(String password) { this.password password; }public String getPhoneNum() { return phoneNum; }public void setPhoneNum(String phoneNum) { this.phoneNum phoneNum; }Overridepublic String toString() {return User{ id id , username username \ , email email \ , password password \ , phoneNum phoneNum \ };}}5utils存放工具类。
6interceptor拦截器。
package interceptor;
public class PrivilegeInterceptor implements HandlerInterceptor {//这里不需要重写三个因为只需要用到一个不用到不写操作的方法的就不重写Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {//逻辑判断用户是否登录本质判断session中有没有userHttpSession session request.getSession();User user (User) session.getAttribute(user);if (user null){//没有登录重定向和转发都可以//request.getRequestDispatcher(/login.jsp).forward(request,response);//可以返回trueresponse.sendRedirect(request.getContextPath()/login.jsp);//重定向后不能返回truereturn false;}return true;//放行访问目标资源}
}三、SpringMVC的视图解析器的前缀后缀添加规则
RequestMapping(/quick)public String quick(){* 总结forward: 或 redirect:* 如果加了上面中的一个那么视图解析器配置的 前缀后缀将不在添加//1. 文.件[/pages/quick.html.jsp] 未找到return quick.html;//2. 文.件[/pages/quick.html.jsp] 未找到return /quick.html;//3.文.件[/pages/aside.jsp.jsp] 未找到return aside.jsp;//4.访问失败服务器崩溃!!,因为少加了“/return forward:quick.html;//5.成功访问/quick.html不会添加前缀与后缀return forward:/quick.html;//6.访问失败缺少“/”服务器收不到请求估计定向到其他地方了不存在的路径return redirect:quick.html;//7.成功访问/quick.html不会添加前缀与后缀return redirect:/quick.html;//8./quick.htmlreturn redirect:/quick.jsp;//9.成功访问https://www.baidu.com不会添加前缀与后缀return redirect:https://www.baidu.com;}
总结字符串的最前面有forward: 或 redirect:那么就不会添加前缀和后缀。
四、业务功能实现步骤。