您当前的位置: 首页 >  Java

white camel

暂无认证

  • 3浏览

    0关注

    442博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

SpringMVC——CRUD操作 (包含JavaConfig的方式)

white camel 发布时间:2020-03-31 12:07:17 ,浏览量:3

目录
  • SpringMVC的CRUD操作 在这里插入图片描述
一、SpringMVC完成CRUD 0、导入相关依赖

    junit
    junit
    4.12


    org.springframework
    spring-webmvc
    5.1.9.RELEASE


    javax.servlet
    servlet-api
    2.5


    javax.servlet.jsp
    jsp-api
    2.2


    javax.servlet
    jstl
    1.2



    org.projectlombok
    lombok
    1.18.10
    provided



    com.fasterxml.jackson.core
    jackson-databind
    2.9.10


    com.fasterxml.jackson.core
    jackson-core
    2.9.10


    com.fasterxml.jackson.core
    jackson-annotations
    2.9.10




    javax.servlet
    jstl
    1.2




    org.springframework
    spring-webmvc
    5.2.2.RELEASE



    org.springframework
    spring-jdbc
    5.2.2.RELEASE




    org.projectlombok
    lombok
    1.18.8




    junit
    junit
    4.12
    test




    org.springframework
    spring-test
    5.2.2.RELEASE




    mysql
    mysql-connector-java
    5.1.4




    com.alibaba
    druid
    1.1.5




    org.aspectj
    aspectjweaver
    1.9.4





    org.hibernate
    hibernate-validator
    6.1.0.Final



    com.fasterxml
    classmate
    1.3.1



    javax.validation
    validation-api
    2.0.1.Final



    org.jboss.logging
    jboss-logging
    3.3.0.Final




    commons-fileupload
    commons-fileupload
    1.3.3


    commons-io
    commons-io
    2.4



    javax.servlet
    javax.servlet-api
    4.0.1

1、设计数据库表
CREATE TABLE `employee` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) DEFAULT NULL,
  `password` varchar(40) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `hiredate` date DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=40 DEFAULT CHARSET=utf8;

配置文件

#key=value
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springmvc
jdbc.username=root
jdbc.password=1111
jdbc.initialSize=2

实体类

package com.sunny.domain;

import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.Date;

@Data
public class Employee {

	private Long id;

	@NotNull(message = "用户名不能为空")
	@Size(max = 10, min = 4, message = "用户名在4-10位之间")
	private String username;

	@NotNull(message = "密码不能为空")
	@Size(max = 10, min = 4, message = "密码在4-10位之间")
	private String password;

	@NotNull(message = "年龄不能为空")
	@Min(value = 18, message = "年龄最小值为18")
	@Max(value = 60, message = "年龄最大值为60")
	private Integer age;

	@DateTimeFormat(pattern = "yyyy-MM-dd")
	private Date hiredate;
}
2、控制层代码

LoginController

@Controller
public class LoginController {

    @Autowired
    private IEmployeeService service;

    @RequestMapping("/login")
    public String login(String username, String password, HttpSession session){
        System.out.println("LoginController.login");
        Employee current = service.login(username, password);
        if (current == null){
            session.setAttribute("errorMsg", "账号或密码错误");
            return "redirect:/login.jsp";
        }
        session.setAttribute("user_in_session", current);
        return "redirect:/employee/list";
    }

/*    @RequestMapping("/login")
    public String login(String username, String password, HttpSession session) {
        try {
            service.login(username, password);
        } catch (Exception e) {
            session.setAttribute("errorMsg", e.getMessage());
            return "redirect:/login.jsp";
        }
        return "redirect:/employee/list";
    }*/
}

EmployeeController

@Controller
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    @RequestMapping("/list")
    public String list(Model model) {
        //int a = 1 / 0;
        // 共享数据到list界面
        model.addAttribute("employees", employeeService.listAll());
        return "employee/list"; // 跳转到list界面
    }

    // 新增员工
    @RequestMapping("/input")
    public String input(Model model, Long id) {
        if (id != null) {
            model.addAttribute("employee", employeeService.get(id));
        } else {
            model.addAttribute("employee", new Employee());
        }
        return "employee/input";
    }

/*    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Employee emp){
        if (emp.getId() == null){
            employeeService.save(emp);
        } else {
            employeeService.update(emp);
        }
        return "redirect:/employee/list";
    }*/

    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(@Valid Employee emp, BindingResult bindingResult, Model model) {

        List errors = bindingResult.getAllErrors();
        if (errors.size() > 0) {
            model.addAttribute("errors", errors);
            return "employee/input";
        }

        if (emp.getId() == null) {
            employeeService.save(emp);
        } else {
            employeeService.update(emp);
        }
        return "redirect:/employee/list";
    }

    @RequestMapping("/delete")
    public String delete(Long id) {
        if (id != null) {
            employeeService.delete(id);
        }
        return "redirect:/employee/list";
    }
}

拦截器代码:CheckLoginInterceptor

public class CheckLoginInterceptor implements HandlerInterceptor {
    // 在请求处理方法之前执行
    // 如果返回true,执行下一个拦截器
    // 如果返回false,就不执行下一个拦截器

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 没有登录的情况
        if (request.getSession().getAttribute("user_in_session") == null){
            System.out.println("----------------");
            response.sendRedirect("/login.jsp");
            return false; // 阻止往后放行
        }
        // 放行,给下一个拦截器或者最终的处理器
        return true;
    }

    // 在请求处理方法执行之后执行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    // 在dispatcherServlet处理后执行,做清理工作
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
3、业务层代码
public interface IEmployeeService {
	void save(Employee emp);

	void update(Employee emp);

	void delete(Long id);

	Employee get(Long id);

	List listAll();

	Employee login(String username, String password);

	/*void login(String username, String password);*/
}
@Service("employeeServiceImpl")
@Transactional // 增加事务处理, 底层AOP来实现(动态代理); 原始功能+切入点+额外功能+组装切面 (4部分)
public class EmployeeServiceImpl implements IEmployeeService {

	@Autowired
	private IEmployeeDAO dao;


	public void save(Employee emp) {
		dao.save(emp);
		//int a = 1/0;
	}

	public void update(Employee emp) {
		dao.update(emp);
	}

	public void delete(Long id) {
		dao.delete(id);
	}

	@Transactional(readOnly = true)
	public List listAll() {
		return dao.listAll();
	}

	@Transactional(readOnly = true)
	public Employee get(Long id) {
		return dao.get(id);
	}

	@Transactional(readOnly = true)
	public Employee login(String username, String password) {
		return dao.login(username, password);
	}

/*	public void login(String username, String password){
		Employee current = dao.login(username, password);
		if (current == null){
			throw new RuntimeException("账号或密码错误!");
		}
		UserContext.setCurrentUser(current);
	}*/
}
4、持久层代码
public interface IEmployeeDAO {
	void save(Employee emp);

	void update(Employee emp);

	void delete(Long id);

	Employee get(Long id);

	List listAll();

	Employee login(String username, String password);
}
public class EmployeeDAOImpl implements IEmployeeDAO {

    private JdbcTemplate jdbcTemplate;

    public void setDataSource(DataSource ds) {
        this.jdbcTemplate = new JdbcTemplate(ds);
    }

    public void save(Employee e) {
        jdbcTemplate.update("INSERT INTO employee (username,password,age,hiredate) VALUES (?,?,?,?)", e.getUsername(),
                e.getPassword(), e.getAge(), e.getHiredate());
    }

    public void update(Employee e) {
        jdbcTemplate.update("UPDATE employee SET username= ?,password=?,age = ?,hiredate=? WHERE id= ?",
                e.getUsername(), e.getPassword(), e.getAge(), e.getHiredate(), e.getId());
    }

    public void delete(Long id) {
        jdbcTemplate.update("DELETE FROM employee WHERE id = ?", id);
    }


    public Employee get(Long id) {
        String sql = "SELECT id,username,password,age,hiredate FROM employee WHERE id = ?";

        List list = jdbcTemplate.query(sql, new Object[]{id}, new RowMapper() {
            public Employee mapRow(ResultSet rs, int i) throws SQLException {
                Employee e = new Employee();
                e.setId(rs.getLong("id"));
                e.setUsername(rs.getString("username"));
                e.setPassword(rs.getString("password"));
                e.setAge(rs.getInt("age"));
                e.setHiredate(rs.getDate("hiredate"));
                return e;
            }
        });

        return list.size() == 1 ? list.get(0) : null;
    }


    public List listAll() {
    	String sql = "SELECT id,username,password,age,hiredate FROM employee";
        List listAll = jdbcTemplate.query(sql, new Object[]{}, new RowMapper() {
                    public Employee mapRow(ResultSet rs, int i) throws SQLException {
                        Employee e = new Employee();
                        e.setId(rs.getLong("id"));
                        e.setUsername(rs.getString("username"));
                        e.setPassword(rs.getString("password"));
                        e.setAge(rs.getInt("age"));
                        e.setHiredate(rs.getDate("hiredate"));
                        return e;
                    }
                });

        return listAll;
    }

    public Employee login(String username, String password) {

        String sql = "SELECT id,username,password,age,hiredate FROM employee WHERE username = ? AND password = ?";

        List list = jdbcTemplate.query(sql, new Object[]{username, password}, new RowMapper() {
            public Employee mapRow(ResultSet rs, int i) throws SQLException {
                Employee e = new Employee();
                e.setId(rs.getLong("id"));
                e.setUsername(rs.getString("username"));
                e.setPassword(rs.getString("password"));
                e.setAge(rs.getInt("age"));
                e.setHiredate(rs.getDate("hiredate"));
                return e;
            }
        });
        return list.size() == 1 ? list.get(0) : null;
    }
}

全局异常控制

/**
 * Description: 处理全局的异常,当发现异常,自动跳转到error.jsp
 *
 * @author zygui
 * @date 2020/3/7 10:21
 */

@ControllerAdvice // 控制器增强.底层仍是AOP切面(AOP底层是动态代理来实现)
public class HandleExceptionAdviceController {

    //@ExceptionHandler(XxxException.class) // 对XxxException异常做处理
    @ExceptionHandler // 默认就是对Exception做处理
    public String error(Model model, Exception ex){
        model.addAttribute("errorMsg", ex.getMessage());
        return "/commons/error";
    }
}
5、web.xml


    
    
        CharacterEncodingFilter
        org.springframework.web.filter.CharacterEncodingFilter
        
            encoding
            utf-8
        
        
        
            forceRequestEncoding
            true
        
        
            forceResponseEncoding
            true
        
    
    
        CharacterEncodingFilter
        /*
    

    
    
    
        springMVC
        org.springframework.web.servlet.DispatcherServlet
        
        
        
        
            contextConfigLocation
            classpath:springmvc-servlet.xml
        
        
        1
    

    
    
    
        springMVC
        /
    

6、applicationContext.xml



	

	
	

	
	
		
		
		
		
		
	

	
	
		
	

	


7、springmvc-servlet.xml



    

    
    

    
    

    
    

    
    
        
        
        
        
    

    
    
        
            
            
            
            
            
            
            
            
        
    

    














8、相关jsp页面

在这里插入图片描述 login.jsp





    登录界面


    登录界面
    
        账号:
        密码:
        
    

    ${errorMsg}
    
    



list.jsp





    Title


    恭喜${user_in_session.username}:登录成功
    注销
    员工列表
    
    新增
    
        
            ID
            用户名
            密码
            入职时期
            操作
        

        
            
                ${e.id}
                ${e.username}
                ${e.password}
                ${e.hiredate}
                
                    删除
                    编辑
                
            
        
    


input.jsp(新增联系人)







    Title




    

    
	编辑员工
    
        
        账号:							
        密码: 	 
        年龄:								 
        入职:
        
    
    
    


		${error.defaultMessage}
	
	编辑员工
	
		
		账号:
		密码:
		年龄:
		入职:
		
	--%>


error.jsp




    错误页面


    出错了: 

    ${ex}

    ${errorMsg}



重点: 使用JavaConfig的方式来将上面的xml配置文件消除掉, 用配置类来替换
  • Web.xml的替代
// Web容器启动; 相当于web.xml
public class MyWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    // 根容器: 相当于_关联Spring的核心配置文件
    protected Class[] getRootConfigClasses() {
        return new Class[]{AppConfig.class};
    }

    // SpringMVC容器:相当于在web.xml中配置mvc.xml
    protected Class[] getServletConfigClasses() {
        return new Class[]{WebConfig.class};
    }

    // 映射路径
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    /*    // 配置全局过滤器(字符编码问题)
        protected void registerContextLoaderListener(ServletContext servletContext) {
            super.registerContextLoaderListener(servletContext);
            //编码过滤器
            Dynamic filter = servletContext.addFilter("CharacterEncodingFilter", CharacterEncodingFilter.class);
            filter.setInitParameter("encoding", "UTF-8");
            filter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
        }*/
    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        characterEncodingFilter.setForceEncoding(true);
        return new Filter[]{characterEncodingFilter};
    }
}
  • applicationContext.xml的替代
// 对应applicationContext.xml的配置类

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

// 相当于applicationContext.xml文件
@Configuration
@ComponentScan("com.sunny")
@PropertySource("classpath:db.properties")
@EnableTransactionManagement // 事务处理的注解
public class AppConfig {

    @Value("${jdbc.driverClassName}")
    private String driverClassName;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
    @Value("${jdbc.initialSize}")
    private int initialSize;

    // 连接池对象
    @Bean // bean的id就是dataSource,也可以起一个
    public DataSource dataSource(){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driverClassName);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        ds.setInitialSize(initialSize);
        return ds;
    }

    // 事务管理器对象;这里传的ds对象,就是上面的连接池对象,它会自动找ds对象
    @Bean
    public DataSourceTransactionManager txManager(DataSource ds){
        return new DataSourceTransactionManager(ds);
    }
}
  • springmvc-servlet.xml的替代

import com.sunny.web.interceptor.CheckLoginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

// 相当于springmvc-servlet这个配置文件
@Configuration
@EnableWebMvc //启动SpringMVC
@ComponentScan("com.sunny")
public class WebConfig implements WebMvcConfigurer {

    @Bean
    public CheckLoginInterceptor checkLoginInterceptor(){
        return new CheckLoginInterceptor();
    }


    // 配置拦截器
    public void addInterceptors(InterceptorRegistry registry){
        registry.addInterceptor(checkLoginInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/login");
    }

    // 配置JSP视图
    @Bean
    public ViewResolver viewResolver(){
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }

    // 配置静态资源处理
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}
关注
打赏
1661428283
查看更多评论
立即登录/注册

微信扫码登录

0.0473s