Springmvc + MySQL instance details

Source: Internet
Author: User

Source code: http://download.csdn.net/download/tjcyjd/4251483SSH is used all the time, because springmvc is used by the company and has never been used before, so I will come and learn about this framework today so that we can meet our work needs. For example, you can download the file at http://download.csdn.net/download/tjcyjd/4101483.

First, let's take a look at what is a model. The model is the methodology for solving a certain type of problems, and the solution to such problems is brought to the theoretical level. This is the model. Mode is a kind of guidance that helps developers complete tasks under a good guidance. Make an excellent design solution to get twice the result with half the effort. In addition, we can find the best solution to the problem.

The MVC mode originated from the Smalltalk language. MVC is short for Model-View-controller. MVC weakens the coupling between the business logic interface and the data interface. The advantages of using the MVC model include high reliability, high reuse and adaptability, low life cycle costs, Fast deployment, and high maintainability. I will not explain the details here.

Springmvc features:

1. clear division of roles Spring provides a very clear division of model, view, and controller. These three aspects are actually responsible for their respective duties.

2. flexible configuration functions. Because the core of spring is IOC, various types of bean can also be configured through XML in MVC implementation.

3. A large number of controller interfaces and implementation classes are provided, so that developers can use the controller implementation class provided by spring or implement controller interfaces by themselves.

4. springmvc is a true view layer implementation independent. It does not force developers to use JSP. We can use other view technologies, such as velocity and xskt.

5. Support for internationalization. Spring's applicationcontext provides support for internationalization, which can be easily used here.

6. Interface-oriented programming. In fact, this is not only a feature of springmvc. From spring perspective, this feature is obvious because it makes it easy for developers to test programs, and convenient management.

7. Spring provides a complete set of web application development processes, not just MVC, which can be easily combined. Here is an example by myself. After completing this example, I really realized the strength of springmvc.

Configure our springmvc project as follows:

First we configure web. xml under 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/web-app_2_5.xsd"> <servlet> <! -- The core of springmvc is dispatcherservlet, which controls the Request Path of the entire page --> <servlet-Name> dispatcherservlet </servlet-Name> <servlet-class> Org. springframework. web. servlet. dispatcherservlet </servlet-class> <! -- Initialize the parameter>/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 with do --> <servlet-mapping> <servlet-Name> dispatcherservlet </servlet-Name> <URL-pattern> *. DO </url-pattern> </servlet-mapping> <! -- Process Chinese garbled characters from the page to the background --> <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 a file is configured, we recommend that you start the server to check whether an exception occurs. Otherwise, it will be difficult to debug and locate the exception in the future.

After web. XML is configured, we also need to create a db-config.properties file under the src directory to store our data source configuration information:

The content is as follows:

DB. url = JDBC: mysql: // springmvcdb? Useunicode = true & characterencoding = utf8

DB. Username = root

DB. Password = root

DB. dirverclass = com. MySQL. JDBC. Driver

The applicationcontext. xml file is configured after the db-config.properties is configured:

<? 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 class = "org. springframework. Web. servlet. MVC. simplecontrollerhandleradapter"/> <! -- Get the configuration file --> <bean id = "Config" class = "org. springframework. beans. factory. config. propertyplaceholderconfigurer "> <property name =" locations "> <list> <value> classpath: db-config.properties </value> </List> </property> </bean> <! -- Get the data source --> <bean id = "datasource" class = "org. apache. commons. DBCP. basicdatasource "> <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> <! -- For the ing list from a URL to a processor, multiple mappings can be configured with the URL program file address, while the value is the bean name of the processor. The URL program file address can be in the Path Matching mode, example: COM/MVC/t? St. JSP: Match COM/MVC/test. JSP, COM/MVC/tast. JSP and Other COM/MVC /*. JSP: Match All com/MVC/URLs with the JSP suffix COM/MVC/**/test. JSP: match all test files in the COM/MVC path or child path. jsp com/MVC /**/*. JSP: Match All com/MVC paths or child paths. URL cN/**/web/bla. JSP: matching cN/option/web/dog. JSP cN/option/test/web/dog. JSP cN/web/dog. jsp request --> <Bean class = "org. springframework. web. servlet. handler. simpleurlhandlermapping "> <property name =" mappings "> <value> User. do = u Seraction </value> </property> </bean> <! -- Defines the view using internalresourceview to indicate that Servlet/JSP technology is used --> <bean id = "viewresolver" class = "org. springframework. web. servlet. view. internalresourceviewresolver "> <property name =" viewclass "> <value> Org. springframework. web. servlet. view. internalresourceview </value> </property> <! -- JSP directory --> <property name = "prefix"> <value>/JSP/</value> </property> <! -- JSP file suffix --> <property name = "suffix"> <value>. JSP </value> </property> </bean> <bean id = "userdao" class = "com. yjde. springmvc. userdao "> <property name =" datasource "ref =" datasource "> </property> </bean> <! -- Define Controller --> <bean id = "useraction" class = "com. yjde. springmvc. usercontroller "> <property name =" Dao "> <ref bean =" userdao "/> </property> <property name =" commandclass "> <value> COM. yjde. springmvc. userdao </value> </property> <property name = "viewpage"> <value> userinfo </value> </property> </bean> </beans>

After the applicationcontext. xml file is configured, we start to write a specific Java class. We need a DAO class, a controller class, And a po

We created a usermbo table in MySQL with 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 queries the fields of the usembo table and places them in the userpo 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 completes Resource Creation and release for us, thus simplifying our use of JDBC. It also helps us avoid some common errors, such as forgetting to close the database connection. For more information, see 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. we B. servlet. MVC. simpleformcontroller; @ suppresswarnings ("all") // simpleformcontroller is a form Controller provided by spring. Set the element name in form on the page to the same as that in bean, when passed in, spring automatically captures the element values with the same name as the bean in form and converts them into a bean, making it easy for developers to use. Public class usercontroller extends simpleformcontroller {private string viewpage; private userdao Dao; Public String getviewpage () {return viewpage;} public void setviewpage (string viewpage) {This. viewpage = viewpage ;}@ overrideprotected 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: 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 ;}}

Userpo class:

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;}}

After the class is created, we compile Two JSPs for testing:

Index. jsp:

<% @ 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> 

 

Final running result:

 

Database Table creation statement:

/* Navicat MySQL data transfer source server: mysqlsource server version: 50145 source host: localhost: 3306 source database: springmvcdb target server type: mysqltarget server version: 50145 file encoding: 65001 Date: 10:34:25 */set foreign_key_checks = 0; -- Optimize 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', 'Li Xiaohong ', '25 '); insert into 'usermapp' values ('2', 'Liu mengyu ', '27'); insert into 'usermapp' values ('3', 'Han lingsha ', '26 ');

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.