Spring, SpringMVC, Mybaits correlation

Before writing the code we first look at the three frameworks are doing?
I believe a large previously seen a lot of these concepts, I'll use the vernacular is concerned, if there is to know before you can skip this large segment had a direct look at the code!

SpringMVC: It is used for the web layer corresponds Controller (equivalent to the conventional and the struts servlet Action), to process the user request. For example, users in the address bar http: // domain / login, then springmvc will intercept this request and the corresponding method call controller layer, (middle may contain business logic validation user name and password, as well as queries database operations, but these are not springmvc duty), the final results returned to the user, and returns the corresponding page (of course, only to be returned data format json / xml, etc.). springmvc is to do in front of and behind the living process of dealing with the user! !

Spring: too strong, so I can not use a word or phrase to summarize it. But we usually estimate the development of the contact is the most IOC containers, which can be loaded bean (that is, we java in the class, of course, including service dao inside), with this mechanism, we do not use this in every class when it is initialized, rarely see the keyword new. The additional spring aop, transaction management, and so are we often use.

MyBatis: If you ask me what is the difference with its famous Hibernate? Suffice to say, he was more in line with my needs. First, it can be freely controlled sql, which will have a database of experienced people (of course not to say that my friends Behind his) code written can do to enhance the efficiency of database access. Second, it can use the xml way to manage our organization sql, because the general procedural error in many cases sql error, others took over after the code can quickly find wrong place, or even the original can be optimized write sql.

The main framework of this system is used in SSM framework that consists Spring + Spring MVC + MyBaits. Spring is located in the bottom of the frame, the frame is based Spring MVC Spring framework, and the main role is played by ligation Spring Spring MVC and MyBaits because the database layer in this framework is mainly managed persistence layer, the business layer direct call is the persistence layer, which should on the realization of the coupling persistence layer and business layer. Spring Inversion of Control and also has a role when an object depends on the class need to register to Spring to control, so its advantages are also embodied in the AOP (section programming), by separating the business and system-level services within reach cohesive development.
Well, in front of bb so much, let's really start knocking code ~
First we open the IED, I use is eclipse (you should also use this, right?), To create a dynamic web project, the establishment of good corresponding The directory structure (emphasis!)

After the recording operation ① to the Master and the master among the binary log (Binary Log), before each data update, these changes Master, MySql serially writing binary transaction, the write transaction record created in the binary log , Master notify the storage engine, the transaction is committed.
② the Binary Log copy back end machine logs Master among the first Slave to open a worker thread, which I / O thread, I / O thread to open an exchange connected to the Master, then do Log treatment Binary, I / O thread the logs are written in the Relay log.
③ Slave redo log event final machine will change to reflect its own data.

③ Layouts: The contents of the log conversion from one data format into a second.
The purpose Logback logging component in this system is to make the fault location and display program running
status.

Then Laijiangjiang redis, in accordance with the contents of the book's five-point Rearrange:

1, Why choose Redis: Introduction reason for using scenarios and use of the Redis Redis;

2, Redis common commands are summarized: a summary of the data structure of the time complexity of the particular type of data used within the Redis;

3, Redis advanced features include: persistent, copy, Sentinel, cluster description;

4, understanding Redis: understanding memory, obstruction, which is a very important part, described earlier can be a surgery, there should belong to the channel section;

5, develop skills: mainly real summary of some developers, including cache design and common pit.

First to open the first part of Redis to a re-looked.

Redis is not a one size fits all

In the interview, the comparison is often asked at the advantages and disadvantages of Redis and Memcache, both personally feel is not suitable for comparison with a non-relational database cache is also capable not only can do other things, is used only as a cache. Often let us compare these two, it is largely due to the Redis scenario is the most widely used Cache, then Redis can do in the end? You can not do it?

Redis is a high-performance memory distributed cache servers to reduce database access techniques query result caching data to increase the speed of dynamic Web applications, improve scalability.
Redis key value is a storage system that supports a relatively large value type memory, including a string, chain, set, ordered set and the like. Using concurrency issues without considering the operation Redis multithreading, since this operation is atomic, not split. On this basis, Redis supports sorting various ways in order to ensure efficiency, the data is in the cache memory, the data will Redis difference is periodically written to disk, or to modify the operation of writing the log file append, the former is the default RDD storage, to ensure the efficient performance of Redis, the disadvantage is that it has persisted for some time, when if persistent, Redis failure can result in data loss, so this approach is more suitable for data requirements when not rigorous, in this system we use to meet the requirements of the RDD.

com.soecode.lyf.web package;

import java.util.List;

import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.ResponseBody;

import com.soecode.lyf.dto.AppointExecution;
import com.soecode.lyf.dto.Result;
import com.soecode.lyf.entity.Book;
import com.soecode.lyf.enums.AppointStateEnum;
import com.soecode.lyf.exception.NoNumberException;
import com.soecode.lyf.exception.RepeatAppointException;
import com.soecode.lyf.service.BookService;

@Controller
@RequestMapping ( "/ Book") // URL: / module / resource / {id} / segment / seckill / List
public class {BookController

private Logger logger = LoggerFactory.getLogger(this.getClass());

@Autowired
private BookService bookService;

@RequestMapping(value = "/list", method = RequestMethod.GET)
private String list(Model model) {
    List<Book> list = bookService.getList();
    model.addAttribute("list", list);
    // list.jsp + model = ModelAndView
    return "list";// WEB-INF/jsp/"list".jsp
}

@RequestMapping(value = "/{bookId}/detail", method = RequestMethod.GET)
private String detail(@PathVariable("bookId") Long bookId, Model model) {
    if (bookId == null) {
        return "redirect:/book/list";
    }
    Book book = bookService.getById(bookId);
    if (book == null) {
        return "forward:/book/list";
    }
    model.addAttribute("book", book);
    return "detail";
}

//ajax json
@RequestMapping(value = "/{bookId}/appoint", method = RequestMethod.POST, produces = {
        "application/json; charset=utf-8" })
@ResponseBody
private Result<AppointExecution> appoint(@PathVariable("bookId") Long bookId, @RequestParam("studentId") Long studentId) {
    if (studentId == null || studentId.equals("")) {
        return new Result<>(false, "学号不能为空");
    }
    //AppointExecution execution = bookService.appoint(bookId, studentId);//错误写法,不能统一返回,要处理异常(失败)情况
    AppointExecution execution = null;
    try {
        execution = bookService.appoint(bookId, studentId);
    } catch (NoNumberException e1) {
        execution = new AppointExecution(bookId, AppointStateEnum.NO_NUMBER);
    } catch (RepeatAppointException e2) {
        execution = new AppointExecution(bookId, AppointStateEnum.REPEAT_APPOINT);
    } catch (Exception e) {
        execution = new AppointExecution(bookId, AppointStateEnum.INNER_ERROR);
    }
    return new Result<AppointExecution>(true, execution);
}

}

Because I'm lazy, so we can not test controller, and a good hate to write front-end, ooo, ooo ~

    到此,我们的SSM框架整合配置,与应用实例部分已经结束了,我把所有源码和jar包一起打包放在了我的GitHub上,需要的可以去下载,喜欢就给个star吧,这篇东西写了两个晚上也不容易啊。
    修改预约业务代码,失败时抛异常,成功时才返回结果,控制层根据捕获的异常返回相应信息给客户端,而不是业务层直接返回错误结果。上面的代码已经作了修改,而且错误示范也注释保留着,之前误人子弟了,还好有位网友前几天提出质疑,我也及时做了修改。
    SET FOREIGN_KEY_CHECKS=0;

-- Table structure for adminuser


DROP TABLE IF EXISTS adminuser;
CREATE TABLE adminuser (
id int(11) NOT NULL AUTO_INCREMENT,
username varchar(255) DEFAULT NULL,
password varchar(255) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>用户登录</title>
</head>
<body>
<form action="<%=request.getContextPath() %>/login.do" method="post">
用户名:<input type="text" name="username" >
密码:<input type="password" name="password" >
<input type="submit" value="登录">
</form>
</body>
</html>

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>修改数据</title>
</head>
<body>
<form action="<%=request.getContextPath() %>/update.do" method="post">
用户名:<input type="text" name="username" value="${add.username}">
密码:<input type="password" name="password" value="${add.password}">
<input type="hidden" name="id" value="${add.id }">
<input type="submit" value="提交数据">
</form>
</body>
</html>

Guess you like

Origin blog.51cto.com/14752132/2477540