Servlet Architecture Ideas (MVC)

In the past few days, I have been working on a project that separates the front and back ends. The MVC model is adopted. The tutorials on the MVC online are disorganized and have not been written in detail, so I wrote this article. This article is a sharing article to share that I am learning. The problems encountered in and some tips that I think are useful.

Table of contents

directory structure

configuration file

Dao layer

Service layer

Control layer

Model layer

lib import package

web.xml configuration


directory structure

config
    jdbc.properties
src
    com.xxx
        user(一般与项目名挂钩)
            control
                UserServlet.java
            dao
                impl
                    UserDao.java
            IUserDao.java
            model
                User.java
            service
                impl
                    UserService.java
            IUserService.java
        util
            JdbcUtil.java
web
    web-inf
        web.xml
        lib
            xxx.jar
    xxx.jsp

configuration file

jdbc.properties : The four parameters (driver, URL, user name, password) used to obtain the connection during development are usually stored in the configuration file, which is convenient for later maintenance. If the program needs to replace the database, only the configuration file needs to be modified.

oracle version

username=itxzw
password=123456
driver=oracle.jdbc.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:orcl

mysql version

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/db1?serverTimezone=Hongkong&useUnicode=true&characterEncoding=utf8&useSSL=false


或
url=jdbc:mysql://localhost/db1?useSSL=false&CharacterEncoding=UTF-8&server=TUC
user=root
password=123456

JdbcUtil.java

It stores some configuration files for connecting to DB, which can reduce the amount of code

public class JdbcUtil {
    public static String username;
    public static String password;
    public static String driver;
    public static String url;

    static {
        // -1.读取配置文件
        InputStream is = JdbcUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties pro = new Properties();
        try {
            pro.load(is);
            username = pro.getProperty("username");
            password = pro.getProperty("password");
            driver = pro.getProperty("driver");
            url = pro.getProperty("url");

            // 0.加载驱动
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection(){
        // 1.连接数据库
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url, username, password);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return conn;
    }

    public static void close(ResultSet rs, Statement stmt,Connection conn){
        // 5.关闭连接
        try {
            if(rs!=null){
                rs.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            try {
                if (stmt!=null){
                    stmt.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }finally {

                try {
                    if (conn!=null){
                        conn.close();
                    }
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }


}

Dao layer

The dao stores some codes that operate on the DB

IUserDao.java stores the interfaces of some codes that operate on DB

public interface IUserDao {

    // 添加用户
    public boolean add(User user);

    // 查询
    public User query(User user);

    // 根据名字查询
    public User queryUserByName(String name);


    // 根据ID_NUMBER查
    public User queryUserByNumber(String number);
}

Inside UserDao.java is the code that implements IUserDao.java to operate on DB

public class UserDao implements IUserDao {
    @Override
    public boolean add(User user) {

        …………
        return user;
    }

    @Override
    public User query(User user) {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        User loginuser = null;
        try {
            // 1.连接数据库
            conn = JdbcUtil.getConnection();
            // 2.获取Statement对象:将sql语句传给数据库服务器执行
            String sql = "select * from T_USER where USERNAME = ? and PASSWORD = ?";
            stmt = conn.prepareStatement(sql);
            // 2.5.注入参数
            stmt.setString(1,user.getUsername());
            stmt.setString(2,user.getPassword());

            // 3.执行sql,获取返回结果
            rs = stmt.executeQuery();

            // 4.处理结果集

            if(rs.next()){
                Integer id = rs.getBigDecimal("id")==null?null:rs.getBigDecimal("id").intValue();
                String un = rs.getString("username");
                String password = rs.getString("password");
                Integer sex = rs.getString("sex")==null?null:rs.getBigDecimal("sex").intValue();
                String idNumber = rs.getString("ID_NUMBER");
                String tel = rs.getString("tel");
                String addr = rs.getString("addr");
                Integer type = rs.getString("type")==null?null:rs.getBigDecimal("type").intValue();
                loginuser = new User(id,un,password,sex,idNumber,tel,addr,type);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JdbcUtil.close(rs,stmt,conn);
        }
        return loginuser;
    }

    @Override
    public User queryUserByName(String name) {

        …………
        return user;
    }

    @Override
    public User queryUserByNumber(String number) {

        …………
        return user;
    }
}

There are operations such as adding, deleting, modifying and checking the DB.

Service layer

IUserService.java stores the interfaces that implement UserService.java

public interface IUserService {

    // 添加用户
    public boolean register(User user);

    // 登录
    public User login(User user);

    // 根据名字查询
    public User queryUserByName(String name);


    // 根据ID_NUMBER查
    public User queryUserByNumber(String number);

}

What is stored in UserService.java is to implement the methods in the IUserService.java interface, declare a member of Dao, and then use the member of Dao to call the method in Dao.

public class UserService implements IUserService {

    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
    public UserDao getUserDao() {
        return userDao;
    }


    @Override
    public boolean register(User user) {
        User user1 = userDao.queryUserByName(user.getUsername());
        if (user1!=null) return false;
        User user2 = userDao.queryUserByNumber(user.getIdNumber());
        if (user2!=null) return false;
        return userDao.add(user);
    }

    @Override
    public User login(User user) {
        return userDao.query(user);
    }

    @Override
    public User queryUserByName(String name) {
        return userDao.queryUserByName(name);
    }

    @Override
    public User queryUserByNumber(String number) {
        return userDao.queryUserByNumber(number);
    }
}

Control layer

The Servlet is stored in the control, which interacts with the interface (view) and service.

public class UserServlet extends HttpServlet {
    private UserService userService;

    @Override
    public void init() throws ServletException {
        userService = new UserService();
        UserDao userDao = new UserDao();
        userService.setUserDao(userDao);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        String action = request.getParameter("action");
        if("LOGIN".equalsIgnoreCase(action)){
            login(request,response);
        }else if ("REGISTER".equalsIgnoreCase(action)){
            register(request,response);
        }else{
            response.sendRedirect("/a1/day02/fade.jsp");
        }
    }

    public void login(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User u = new User();
        u.setUsername(username);
        u.setPassword(password);

        User loginuser = userService.login(u);
        if(loginuser!=null){
            response.sendRedirect("/a1/day02/success.jsp");
        }else{
            response.sendRedirect("/a1/day02/login.jsp");
        }

    }

    public void register(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{


        String[] hobbys = request.getParameterValues("hobby");
        String un = request.getParameter("username");
        String password = request.getParameter("password");
        String usersex = request.getParameter("sex");
        Integer sex = usersex==null?null:Integer.parseInt(usersex);
        String idNumber = request.getParameter("id_number");
        String tel = request.getParameter("tel");
        String addr = request.getParameter("addr");

        String usertype = request.getParameter("type");
        Integer type = usertype==null?null:Integer.parseInt(usertype);


        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().println("哈哈");
        

    }

}

The servlet life cycle init will only be executed once, and the objects in the service layer are generally declared only once. After the project goes to the cloud, if thousands of people visit your web page, it is very wasteful to create a service once executed. So in order to reduce memory usage, put Service into init.

Model layer

It stores entity classes, getter and setter methods for members, constructors with parameters and no parameters, and methods such as overriding toString.

public class User {

    private int id;
    private String username;
    private String password;
    private int sex;
    private String id_number;
    private String tel;
    private String addr;
    private int type;

    public User() {
    }

    public User(int id, String username, String password, int sex, String id_number, String tel, String addr, int type) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.sex = sex;
        this.id_number = id_number;
        this.tel = tel;
        this.addr = addr;
        this.type = type;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getSex() {
        return sex;
    }

    public void setSex(int sex) {
        this.sex = sex;
    }

    public String getId_number() {
        return id_number;
    }

    public void setId_number(String id_number) {
        this.id_number = id_number;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

    public String getAddr() {
        return addr;
    }

    public void setAddr(String addr) {
        this.addr = addr;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", sex=" + sex +
                ", id_number='" + id_number + '\'' +
                ", tel='" + tel + '\'' +
                ", addr='" + addr + '\'' +
                ", type=" + type +
                '}';
    }
}

Or you can use lombok.jar without writing getter and setter methods, constructors with parameters and no parameters, rewriting toString and other methods.

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class User {

  private Integer id;
  private String username;
  private String password;
  private Integer sex;
  private String idNumber;
  private String tel;
  private String addr;
  private Integer type;

}

lib import package

lib stores some imported .jar packages.

xxx.jsp

Needless to say, one thing to note is that the location of the from action corresponds to your web.xml file.

web.xml configuration

The web.xml file is used to initialize configuration information: such as Welcome page, servlet, servlet-mapping, filter, listener, startup loading level, etc. Each xml file has a Schema file that defines its writing rules, that is to say, how many tag elements are defined in the xml Schema file corresponding to the definition web.xml of javaEE, the tag elements defined by it can appear in web.xml , which have specific functions.

    <servlet>
        <servlet-name>UserServlet</servlet-name>
        <servlet-class>com.itxzw.user.control.UserServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>UserServlet</servlet-name>
        <url-pattern>/userServlet</url-pattern>
    </servlet-mapping>

 servlet-mapping

The process of servlet mapping port mapping is like: your home is in Room 2410, Building B, in a community. Your friend comes to you and finds the gate of the community. He doesn't know which floor and number you live in? Just ask the security guard at the gate, and the security guard tells you very politely. He detailed the house number of your home, so your friends can easily find your home.

url-pattern

In fact, url-pattern is the url pattern, that is, the container finds a specific servlet to execute according to this pattern when searching.

servlet-name

The servlet program has an alias, usually a class name, to tell the server which servlet program the currently configured address is used for.

servlet-class

The class that requests forwarding in java web development is the address of your class under your package.

 If you don’t accumulate a few steps, you can’t go a thousand miles, while you are young, work hard and give an explanation to your future self! Move forward to a better self tomorrow!

Guess you like

Origin blog.csdn.net/aasd23/article/details/126375547