I have always used ssh. Because the company wants to use SpringMVC, I have never been exposed to it before, so today I will learn this framework with you so that I can do my job.
First of all, let’s understand what a pattern is. Pattern is the methodology of solving a certain type of problem, and summarize the solutions to this type of problem to the theoretical level. This is the pattern. Patterns are a guide that helps developers complete tasks under a good guidance. Making an excellent design plan can achieve twice the result with half the effort. And you will get the best solution to the problem.
The mvc pattern originated from the Smalltalk language, which is the abbreviation of Model-View-Controller. mvc weakens coupling between business logic interface and data interface. There are many benefits of using MVC mode, such as strong reliability, high reuse and adaptability, low life cycle cost, rapid deployment, strong maintenance, etc. I won't explain too much about the details here.
Features of SpringMVC:
1. Clear role division. Spring provides a very clear division in Model, View and Controller. These three aspects are truly performed and each assumes their responsibilities.
2. Flexible configuration function, because Spring's core is IOC, and in implementing MVC, various classes can also be configured through XML as beans.
3. Provide a large number of controller interfaces and implementation classes, so developers can use the controller implementation classes provided by Spring, or implement the controller interface themselves.
4. SpringMVC is a real View layer implementation-independent. It will not force developers to use JSP. We can use other View technologies, such as Velocity, Xskt, etc.
5. Internationalization support. Spring's ApplicationContext provides support for internationalization, which can be used very conveniently here.
6. Interface-oriented programming. In fact, this is not only a feature of springMVC. From the perspective of Spring, this feature is very obvious because it makes it easy for developers to test programs and manage them easily.
7. Spring provides a complete set of processes for web application development, not just MVC, which can be easily combined. Below is an example of how I did it myself. After finishing this example, I really realized the power of SpringMVC.
Let’s start configuring our Springmvc project:
First, we configure web.xml in the WEB-INF directory:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <!--The core of springmvc is the DispatcherServlet, which controls the request path of the entire page --> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--Initialization Parameters>/WEB-INF/classes/equivalent to the src directory--> <init-param> <!-- This param-name must be contextConfigLocation--> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/classes/applicationContext.xml</param-value> </init-param> <load-on-startup>2</load-on-startup> </servlet> <!--Intercept all requests ending in do--> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- Handle Chinese garbled problems that occur when passing Chinese from the page to the background--> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
After configuring a file every time, it is recommended to start the server first to see if an exception occurs, otherwise it will be difficult to debug and find the exception in the later stage.
After the WEB.XML is configured, we need to create a db-config.properties file in the SRC directory to store our data source configuration information:
The content is as follows:
db.url= jdbc:MySQL:///springmvcdb?useUnicode=true&characterEncoding=utf8db.username=rootdb.password=rootdb.dirverClass= com.mysql.jdbc.Driver
After the db-config.properties is configured, start configuring the applicationContext.xml file:
<?xml version="1.0"encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!-- Define a default control adapter --> <bean /> <!-- Get configuration file --> <bean id="config" > <property name="locations"> <list> <value>classpath:db-config.properties</value> </list> </property> </bean> <!-- Get data source--> <bean id="dataSource"> <property name="driverClassName"> <value>${db.dirverClass}</value> </property> <property name="url"> <value>${db.url}</value> </property> <property name="username"> <value>${db.username}</value> </property> <property name="password"> <value>${db.password}</value> </property> </bean> <!-- The URL to the processor's mapping list can be configured with multiple mappings attributes as URL program file addresses, and the value is the processor's Bean name. The URL program file address can adopt a path matching pattern, such as: com/mvc/t?st.jsp: Match com/mvc/test.jsp, com/mvc/tast.jsp, etc. com/mvc /*.jsp: Match all URLs with jsp suffix under com/mvc//**/test.jsp: Match all test.jsp com/mvc path under com/mvc/ or descendant path under com/mvc /**/*.jsp: Match all URLs with .jsp suffixes under the com/mvc path or the descendant path cn/**/web/bla.jsp: Match requests for cn/option/web/dog.jsp cn/option/test/web/dog.jsp cn/web/dog.jsp cn/web/dog.jsp --> <bean> <property name="mappings"> <value> user.do=userAction </value> </property> </bean> <!--Definition view is used through internalResourceView to indicate that Servlet/jsp technology is used--> <bean id="viewResolver" > <property name="viewClass"> <value>org.springframework.web.servlet.view.InternalResourceView </value> </property> <!-- directory stored in jsp--> <property name="prefix"> <value>/jsp/</value> </property> <!--definition of the suffix of the suffix--> <property name="suffix"> <value>.jsp</value> </property> </bean> <bean id="userDao"> <property name="dataSource"ref="dataSource"></property> </bean> <!--Definition of the controller--> <bean id="userAction"> <property name="dao"> <ref bean="userDao"/> </property> <property name="commandClass"> <value>com.yjde.springmvc.UserDao</value> </property> <property name="viewpage"> <value>userInfo</value> </property> </beans>After the ApplicationContext.xml file is configured, we start writing specific Java classes. We need a Dao class, a controller class and a PO
We created a USERMBO table in MySql, which has three fields USERID, USERNAME, USERAGE
UserDao class:
package com.yjde.springmvc; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collection; import java.util.List; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.support.JdbcDaoSupport; @SuppressWarnings("all") public class UserDao extends JdbcDaoSupport { private String msg; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } // This method querys the fields corresponding to the USEMBO table and puts them into userPO in sequence public Collection<UserPO> doquery() { String sql = "SELECT T.USERID,T.USERNAME,T.USERAGE FROM USERMBO T"; return super.getJdbcTemplate().query(sql, new RowMapper() { public Object mapRow(ResultSet rs, int num) throws SQLException { UserPO user = new UserPO(); user.setUserId(rs.getInt("USERID")); user.setUserName(rs.getString("USERNAME")); user.setUserAge(rs.getInt("USERAGE")); return user; } }); } }JdbcTemplate is the core class of the core package. It does the creation and release of resources for us, thus simplifying our use of JDBC. It can also help us avoid common mistakes such as forgetting to close the database connection. For details, please refer to the API
Controller class:
package com.yjde.springmvc; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.validation.BindException; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.SimpleFormController; @SuppressWarnings("all") // SimpleFormController is a form controller provided by spring. It sets the element name in the Form on the page to the same as in the bean. When passed in, Spring will automatically grab the element value of the same as the bean name in the form and convert it into a bean, so that developers can use it very conveniently. public class UserController extends SimpleFormController { private String viewpage; private UserDao dao; public String getViewpage() { return viewpage; } public void setViewpage(String viewpage) { this.viewpage = viewpage; } @Override protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { UserDao tmp = (UserDao) command; Collection<UserPO> list = dao.doquery(); List<UserPO> users = new ArrayList<UserPO>(); UserPO user; for (UserPO userPO : list) { user = new UserPO(); user.setUserId(userPO.getUserId()); user.setUserName(userPO.getUserName()); user.setUserAge(userPO.getUserAge()); users.add(user); } Map mp = new HashMap(); mp.put("list", users); return new ModelAndView(getViewpage(), mp); } public void setDao(UserDao dao) { this.dao = dao; } } package com.yjde.springmvc; public class UserPO { private Integer userId; private String userName; private Integer userAge; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Integer getUserAge() { return userAge; } public void setUserAge(Integer userAge) { this.userAge = userAge; } } </pre><br> <p align="left"><span style="color:teal">After the class creation is completed, we will write two</span><span style="color:teal">JSP</span><span style="color:teal">Test:</span></p> <p align="left"><span style="color:teal">Index.jsp:</span></p> <p align="left"><span style="color:#bf5f3f"></span></p> <pre name="code"><%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="user.do" method="post"> Please enter <input name="msg" type="text" /> <input type="submit" value="submit"> </form> </body> </html> </pre><p align="left"><span style="color:teal"> </span></p> <p align="left"><span style="color:teal"> Final run result: </span></p> <p align="left"><span style="color:teal"> <img src="http://my.csdn.net/uploads/201204/24/1335237733_4732.png"></span></p> <p align="left"><span style="color:teal">Database table creation statement: </span></p> <p align="left"><span style="color:#008080"></span></p> <pre name="code">/* Navicat MySQL Data Transfer Source Server : mysql Source Server Version : 50145 Source Host : localhost:3306 Source Database : springmvcdb Target Server Type : MYSQL Target Server Version : 50145 File Encoding : 65001 Date: 2012-04-24 10:34:25 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for `usermbo` -- ---------------------------- DROP TABLE IF EXISTS `usermbo`; CREATE TABLE `usermbo` ( `USERID` int(11) NOT NULL DEFAULT '0', `USERNAME` varchar(50) DEFAULT NULL, `USERAGE` int(11) DEFAULT NULL, PRIMARY KEY (`USERID`) ) ENGINE=InnoDB DEFAULTCHARSET=utf8; -- ---------------------------- -- Records of usermbo -- ---------------------------- INSERT INTO `usermbo` VALUES('1', '李晓红', '25'); INSERT INTO `usermbo` VALUES('2', '柳梦璃', '27'); INSERT INTO `usermbo` VALUES('3', '韩菱纱', '26');</pre> Download example: demo
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.