In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)06/01 Report--
To learn the technical framework of Spring, it is far from enough to master theoretical knowledge. We should know how to apply what we have learned, type out what we have learned with the keyboard, and look for the usage of Spring in the right and wrong.
In order to give readers an intuitive concept, here I use Spring to build a simple login, which allows you to quickly understand how Spring works in the persistence layer, business layer, and presentation layer, so that when we explain it in modules, readers can also quickly know.
The tool used in this paper is Eclipse IDE, and the database is Oracle 11g.
First of all, let's learn about the login function. The user visits the login page, enters the account number and password, clicks on the login, verifies whether there is a match between the account and password in the background, and if the match is successful, jumps to the welcome page and displays the user's credit. if login fails, return to the login page and prompt login failure information.
Simplified diagram:
Experienced programmers know that they will write the development design or draw class diagrams before development, in which the author also starts from the development design, first designs and then develops for the whole process of login, after all, sharpening the knife does not mistakenly cut wood.
The above is a general description of the whole process of login function design:
1. First visit login.jsp and return to the form login page where you can enter the user's account number and password.
two。 The user enters the account number and password on the login page, submits the form to the server, and Spring calls the LoginController controller to respond to the request according to the configuration.
3.LoginController calls the LoginService/isExistUser method to query whether there is a user according to the passed user and password parameters, and the LoginService interacts with the data through the persistence layer LoginDao.
4. If there is no match for the user, Login.jsp is returned and a prompt is returned, and if the match is successful, proceed to the next step.
5.LoginController calls LoginService/findUserByUsername to get the entity of the current logger and sets the current login time and the updated value of the credit.
6.LoginController calls the LoginService/loginsuccess () method for business processing after a successful login, first updating user information, and creating LoginInfo log objects and inserting them into the database.
7. Redirect the welcome page welcome.jsp page and return the response.
Environmental preparation:
1. Table creation
Create table TB_USER-user table (userid VARCHAR2 (20), username VARCHAR2 (20), credits NUMBER, password VARCHAR2 (100), last_login_time DATE, last_login_ip VARCHAR2 (30) create table TB_LOGIN_LOG-user login log (login_id VARCHAR2 (20), login_user_id VARCHAR2 (20), ip VARCHAR2 (20) Login_time DATE)-insert a user insert into tb_user (USERID, USERNAME, CREDITS, PASSWORD, LAST_LOGIN_TIME, LAST_LOGIN_IP) values ('zhangsan',' Zhangsan', 0, '123456', to_date ('06-07-2016 09 USERID, 'dd-mm-yyyy hh34:mi:ss'),' 0VOV0VOVOVOVOVOVOUL 1')
two。 Establish a project
Good package classification and layering will bring great benefits to maintenance and other development, in general, the classification of packages in enterprise projects should also be divided by project modules, the project of this article is relatively simple, so the classification is simplified, at the same time, the configuration files for Spring are generally stored in folders, here we will not elaborate, I believe that most of the projects that readers see in their work are well-structured.
About Spring3.0-related jar, readers can download it themselves.
3. Create an entity class
We can think that the entity class is a line running through the business layer, persistence layer and presentation layer. A functional module often revolves around an entity class. The business layer modifies the status of the entity class, and the persistence layer stores the entity class to the database. The presentation layer shows the state of the entity class, which shows the importance of the entity class.
Public class User {private String userid;// user name private Integer credits;// integral private String password;// password private Date lastlogintime;// Last Login time private String loginip;// Last Login ip} public class LoginInfo {private String loginid;// Login Primary key private String loginuserid;// Login person ID private String loginip / / Login IP private Date logintime;// logon time}. Omit get and set methods
4. Persistence layer LoginDao and LoginLogDao
Let's first take a look at the DAO for operating User, which mainly includes three methods
1.getUserCount (). The returned result is × × ×. If 1 is returned, the user and password match is correct. If 0 is returned, the user and password match is incorrect. In practice, the password encryption and decryption feature exists. Let's simplify it here.
2.findUserByUsername (), which gets the User entity based on the user's account number.
3.updateUserInfo (), update the user's last login time, points, and user IP.
Import java.sql.ResultSet;import java.sql.SQLException;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.jdbc.core.RowCallbackHandler;import org.springframework.stereotype.Repository;import domain.User;@Repository / / define a Daopublic class LoginDao {@ Autowired// automatically injecting id into bean private JdbcTemplate jdbcTemplate of JdbcTemplate via Spring annotation / * * @ author zangyn * @ date 2016-8-19 1:54:16 * @ Title: getUserCount * @ Description: whether there is a match based on account and password * @ return int return type * @ throws * / public int getUserCount (String username String password) {String sql= "SELECT COUNT (*) FROM TB_USER U WHERE U.USERID? AND U.PASSWORD? "; int count=jdbcTemplate.queryForInt (sql,new Object [] {username,password}); return count } / * * @ author zangyn * @ date 2016-8-19 1:54:43 * @ Title: findUserByUsername * @ Description: query whether the User * @ return User return type * @ throws * / public User exists according to Userid FindUserByUsername (String userid) {String sql= "SELECT * FROM TB_USER U WHERE U.USERID?" Final User u=new User (); jdbcTemplate.query (sql, new Object [] {userid}, new RowCallbackHandler () {@ Override public void proce***ow (ResultSet rs) throws SQLException {u.setUserid (rs.getString ("userid")) U.setUsername (rs.getString ("username")); u.setCredits (rs.getInt ("credits"));}}); return u } / * * @ author zangyn * @ date 2016-8-19 1:55:28 * @ Title: updateUserInfo * @ Description: update user related information * @ return void return type * @ throws * / public Void updateUserInfo (User user) {String sql= "UPDATE TB_USER U SET U.LASTIX logged timekeeping? U.LASTROGINGINGING IPSets? WHERE U.USERID? "; jdbcTemplate.update (sql, new Object [] {user.getLastlogintime (), user.getLoginip (), user.getCredits (), user.getUserid ()});}}
After Spring2.5, you can use annotations to define Bean. Compared with XML configuration, annotation configuration is much simpler, so we try to use annotations as the main way to configure Bean.
Here we define the configuration of the Dao bean with @ Repository and use @ Autowired to inject the Bean of the container.
We can see from the above that we have introduced Spring JdbcTemplate for database operations. Anyone who has used the original JDBC knows that before performing database operations, we all need to go through the following steps: get the connection > create the Statement > perform the database operation > get the results > close the Statement > close the result set > close the connection. At the same time, we should also pay attention to the handling of exceptions. Every time we execute sql, our 1sql code repeats the above code. For the above template code, Spring JDBC has a thin layer of packaging, the template code will be encapsulated, users only need to write those essential code.
Note about spelling SQL: in the spelling of long sql, we often need line breaks, as the upper and lower lines will eventually be converted into a sql, at this time if there is no space at the end of each line, there will be connected cases, so a good way to spell SQL is to type a space at the beginning and end of each line.
I will describe the various methods of JdbcTemplate in detail in a later article.
LoginLogDao has only one method for storing log records, and the code is as follows:
Import org.springframework.beans.factory.annotation.Autowired;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.stereotype.Repository;import domain.LoginInfo;@Repository / / define a Daopublic class LoginLogDao {@ Autowired// automatically injecting id into bean private JdbcTemplate jdbcTemplate of JdbcTemplate via Spring annotation Public void insertLoginfo (LoginInfo info) {String sql= "INSERT INTO TB_LOGIN_INFO (LOGIN_ID,LOGIN_USER_ID,IP,LOGIN_TIME) VALUES (login_info_seq.nextval,?)"; Object [] obj=new Object [] {info.getLoginuserid (), info.getLoginip (), info.getLogintime ()}; jdbcTemplate.update (sql, obj);}}
5. Data source configuration and Spring loading Dao
Create a file called applicationContext.xml under src with the following configuration file:
Spring's scan specifies the classes under the package so that the @ Repository and @ Autowired annotations work.
With regard to the data source configuration, there are only different configuration sources, and as to why it is so configured, it can only be said to be a requirement of the JDBC specification.
The bean of jdbcTemplate injects dataSource into JdbcTemplate, and then JdbcTemplate Bean injects into LoginLogDao and LoginDao through @ Autowired.
6. Service layer LoginService
The loginservice interface has three methods: isExistUser is used to verify account and password correctness, findUserByUsername is used to load User entities based on user accounts, loginSuccess is used to log in successfully to change points, log insertion operation, there are transaction operations, update tb_user and insert tb_login_info, but we do not see the code for transaction control. One of the advantages of Spring is to liberate transactions from the code. Next I'll talk about Spring's transactional capabilities.
Import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import dao.LoginDao;import dao.LoginLogDao;import domain.LoginInfo;import domain.User;@Service / / Mark LoginServcie as a service layer Beanpublic class LoginService {@ Autowired private LoginDao logindao; @ Autowired private LoginLogDao loginlogdao; public boolean isExistUser (String userid,String password) {int count=logindao.getUserCount (userid, password); return count > 0 } public User findUserByUsername (String userid) {return logindao.findUserByUsername (userid);} public void loginSuccess (User u) {u.setCredits (u.getCredits () + 5); LoginInfo info=new LoginInfo (); info.setLoginuserid (u.getUserid ()); info.setLogintime (u.getLastlogintime ()); info.setLoginip (u.getLoginip ()); loginlogdao.insertLoginfo (info) Logindao.updateUserInfo (u);}}
7.Spring loads Service
Although the transaction of Spring does not need to appear in the code, we need to tell Spring which business classes need to work in the transaction environment and the rules of the transaction, and let Spring automatically add transaction management functions to the target business class according to this information.
As for the business layer and configuration has been completed, let's unit test it first.
8. Unit testing
The test framework of Spring 3.0 can be integrated with Junit4, and the SpringJUnit4Cla***unner test runner can be specified through @ RunWith, which is provided by Spring and can be combined with the Spring container and Junit4 test framework. @ ContextConfiguration is also an annotation provided by Spring to specify the Spring configuration file. @ Test is used to label a method as a test method
Import static org.junit.Assert.*;import java.util.Date;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4Cla***unner;import domain.User;import service.LoginService @ RunWith (SpringJUnit4Cla***unner.class) / / JUnit4-based Spring testing framework @ ContextConfiguration (locations= {"classpath:applicationContext.xml"}) / / start spring container public class TestUserService {@ Autowired// inject spring container bean private LoginService loginservice; @ Test public void isExistUser () {boolean a1=loginservice.isExistUser ("zhangsan", "123456"); boolean a2=loginservice.isExistUser ("zhangsan", "1") AssertTrue (A1); assertTrue (! a2);} @ Test public void findUserbyUsername () {User u=loginservice.findUserByUsername ("zhangsan"); assertEquals (u.getUserid (), "zhangsan");} @ Test public void loginSuccess () {User u=new User () U.setUserid ("zhangsan"); u.setCredits (0); u.setLoginip ("127.0.0.1"); u.setLastlogintime (new Date ()); loginservice.loginSuccess (u);}}
9. Configure SpringMVC
Now that the business layer and persistence layer are complete, we need to use SpringMVC to add the presentation layer to the whole function. First configure web.xml
ContextConfigLocationclasspath:applicationContext.xml org.springframework.web.context.ContextLoaderListenerSpringorg.springframework.web.servlet.DispatcherServlet contextConfigLocationclasspath: Spring-servlet.xml 1 Spring*.html
The web container specifies the Spring configuration file through the context parameter, and multiple configuration files can be separated by commas. Then the web container automatically starts the listener ContextLoaderListener when it starts. The function of the listener is to obtain the Spring configuration file and start the Spring container. Pay attention to placing log4j.properties under the classpath so that the log engine can take effect.
SpringMVC also intercepts URL requests and then processes them.
Note that SpringMVC also has a configuration file, which has a contract with the Servlet name defined here, namely
Use-servlet.xml, where the name of Servlet is Spring, which means that there must be a Spring-servlet.xml configuration file under / WEB-INF, which does not need to be configured through the context of web.xml. SpringMVC's Servlet will automatically assemble Spring-servlet.xml with other configuration files.
ContextConfigLocation
Classpath:Spring-servlet.xml
If you configure this parameter here, the configuration file will not execute the above contract to find Spring-servlet, but will look up the file according to our own configuration.
The URL path of Servlet is defined so that all URL with .html suffix can be intercepted by Spring Servlet and then transferred to SpringMVC for processing. After the request is accepted by SpringMVC, the processing controller of the target is first found according to URL, and the request parameters are encapsulated as a "command" object and passed to the controller for processing. The controller calls Spring's business Bean for processing and returns the view.
10. Controller class LoginController
LoginController is responsible for processing login requests, completing the login business, and returning different pages according to the login results.
Import java.util.Date;import javax.servlet.http.HttpServletRequest;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;import domain.LoginCommand;import domain.User;import service.LoginService;@Controllerpublic class LoginController {@ Autowired private LoginService loginservice @ RequestMapping (value= "/ index.html") public String loginPage () {return "login";} @ RequestMapping (value= "/ loginCheck.html") public ModelAndView loginCheck (HttpServletRequest request,LoginCommand loginCommand) {boolean isValid=loginservice.isExistUser (loginCommand.getUserid (), loginCommand.getPassword ()) If (! isValid) {return new ModelAndView ("login", "error", "user or password error");} else {User user=loginservice.findUserByUsername (loginCommand.getUserid ()); user.setLoginip (request.getRemoteAddr ()); user.setLastlogintime (new Date ()) Request.getSession () .setAttribute ("user", user); loginservice.loginSuccess (user); return new ModelAndView ("welcome");}
@ Controller marks LoginController as a SpringMVC controller and handles HTTP requests. A controller contains processing methods for multiple HTTP request paths, and the request paths are mapped by @ RequestMapping.
The request parameter is automatically bound to the input parameter of the response method according to the default contract of the parameter name. In loginCheck (HttpServletRequest request,LoginCommand loginCommand), the request parameter is bound to the loginCommand according to the name match.
Public class LoginCommand {private String userid;// user id private String password;// user password omitted get/set}
The request method can return a ModelAndView or a string, and SpringMVC parses and automatically redirects to the target response page. Readers of ModelAndView only need to know that it currently represents a view, which will be explained later.
Now you need to know the two forms returned by ModelAndView, ModelAndView ("login", "error", "user or password error") and ModelAndView ("main"). The first parameter represents the logical name of the view, and the second and third represent the data model name and the data model object, which will be placed in the request property with the data model name as the parameter name.
Configuration file Spring-servlet.xml for SpringMVC
The above SpringMVC parses ModelAndView,Spring through configuration. There are many ways to parse ModelAndView. Here we use InternalResourceViewResolver, which parses by adding prefixes. For example, ModelAndView ("welcome") will be resolved to / WEB-INF/login/welcome.jsp
11.JSP page
Log in to the forum home page ${user.username} Welcome to this forum. Your score is ${user.credits}.
Here I introduce the c tag, which requires the introduction of two jar packages.
The rest can be deployed directly, and then access the http://localhost:8088/ project deployment name /, enter zhangsan, 123456 to log in successfully.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.