Springmvc+mysql example detailed (with demo) _java

Source: Internet
Author: User
Tags xmlns

has been using SSH, because the company to use SPRINGMVC, has not been contacted before, so today to learn about this framework with you, so that the need for work.

First of all, let's take a look at what is the pattern, the model is to solve a certain kind of problem of methodology, the solution to solve such problems belongs to the height of the theory, this is the model. A model is a guide that helps developers accomplish their tasks under a good guidance. Make an excellent design plan, can achieve a multiplier effect. And it will be the best way to solve the problem.

The MVC pattern originates from the Smalltalk language, and MVC is the shorthand for Model-view-controller. MVC weakens the coupling between the business logic interface and the data interface. There are many benefits to using the MVC pattern, strong reliability, high reuse and adaptability, low lifecycle costs, rapid deployment, and strong maintainability. The details are not so much explained here.

Characteristics of SPRINGMVC:

1, a clear role division, spring in model, view and controller to provide a very clear division, these 3 aspects are truly their respective duties, accountability.

2, flexible configuration, because spring is the core of the IOC, also in the implementation of MVC, the various classes as beans can be configured through XML.

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

4, SPRINGMVC is the real view layer implementation-independent, it will not force developers to use JSP, we can use other view technology, such as Velocity,xskt.

5, international support, Spring's ApplicationContext provides the internationalization of support, here can be very convenient to use.

6, interface-oriented programming, in fact, this is not only the characteristics of SPRINGMVC, the entire spring view, this feature is very obvious, because it allows developers to easily test the program, and easy to manage.

7. Spring provides a complete set of processes for Web application development, not just MVC, which can be easily combined. Here is an example of their own to do this, after this example really experience the powerful SPRINGMVC.

Here we start to configure our SPRINGMVC project:

First we configure the 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" xml Ns: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, It is responsible for controlling the entire page's request path--> <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>contextco Nfiglocation</param-name> <param-value>/WEB-INF/classes/applicationContext.xml</param-value> & Lt;/init-param> <load-on-startup>2</load-on-startup> </servlet> <!--intercept all requests with do end--> &L T;servlet-mapping> <servlet-name>dispatcherservlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!--handling Chinese garbled issues 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& 
 Gt  </welcome-file-list> </web-app>

After each configuration of a file is recommended to start the server to see if there is an exception, or later will be difficult to debug and find the exception.

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

The contents are as follows:

Db.url= Jdbc:mysql:///springmvcdb?useunicode=true&characterencoding=utf8

db.username=root

Db.password=root

db.dirverclass= Com.mysql.jdbc.Driver

Db-config.properties Configure the Applicationcontext.xml file after it has been configured:

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" 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 Clas s= "Org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/> <!--get profile--> <bean id= " Config "class=" org.springframework.beans.factory.config.PropertyPlaceholderConfigurer "> <property name=" Locations "> <list> <value>classpath:db-config.properties</value> </list> </p Roperty> </bean> <!--get the data source--> <bean id= "DataSource" class= 
  Ce "> <property name=" driverclassname "> <value>${db.dirverClass}</value> </property> <property name= "url" > <value>${db.url}</value> </property> <property name= "username" > <value>${db.username}</value> &l t;/property> <property name= "password" > <value>${db.password}</value> </property> & lt;/bean> <!--URL to processor mapping list you can configure multiple Mappings property health values to be URL program file addresses, while the value is the processor's bean name, and the URL program file address can be in a path-matching pattern, such as: Com/mvc/t?s t.jsp: Matching com/mvc/test.jsp, com/mvc/tast.jsp com/mvc/*.jsp: Matching all com/mvc/with jsp suffix URL com/mvc/**/test.jsp: matching all COM/MV test.jsp Com/mvc/**/*.jsp under the C path or descendant path: matches the URL cn/**/web/bla.jsp with the. jsp suffix under all com/mvc paths or descendants ' paths: Matching cn/option/web/dog.jsp cn /option/test/web/dog.jsp Cn/web/dog.jsp's request--> <bean class= " Org.springframework.web.servlet.handler.SimpleUrlHandlerMapping "> <property name=" Mappings "> <value& 
    Gt User.do=useraction </value> </property> </bean> <!--definition view is represented by Internalresourceview to use Servle t/jsp Technology--> <bean id= "Viewresolver" class=. web.servlet.view.InternalResourceViewResolver "> <property name=" Viewclass "> <value>  
  Org.springframework.web.servlet.view.InternalResourceView </value> </property> <!--JSP storage directory--> <property name= "prefix" > <value>/jsp/</value> </property> <!--jsp file suffix--> & Lt;property name= "suffix" > <value>.jsp</value> </property> </bean> <bean id= "user 
 Dao "class=" Com.yjde.springmvc.UserDao "> <property name=" dataSource "ref=" DataSource "></property> </bean> <!--definition controller--> <bean id= "useraction" class= "Com.yjde.springmvc.UserController" > <propert y name= "dao" > <ref bean= "Userdao"/> </property> <property name= "Commandclass" > <valu e>com.yjde.springmvc.userdao</value> </property> <property name= "ViewPage" > <value>us Erinfo</value> </property> &Lt;/bean> </beans> 
 

Applicationcontext.xml file configuration So we start writing specific Java classes, we need a DAO class, a controller class and a PO

We created a Usermbo table in MySQL with three fields in it 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 Usembo the field query of the table to 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 Sqlex 
    ception {Userpo user = new Userpo (); 
    User.setuserid (Rs.getint ("USERID")); 
    User.setusername (rs.getstring ("USERNAME")); 
    User.setuserage (Rs.getint ("Userage")); 
   return user; 
 } 
  }); } 
} 

The JdbcTemplate is the core package. It completes our resource creation and release work, simplifying our use of JDBC. It can also help us avoid some common mistakes, such as forgetting to close the database connection. See the API specifically

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 the form controller provided by spring, which sets the element names in the form in the page to be the same as in the bean. 
When passed in, spring automatically grabs the element value of form and bean name and converts it to 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; @Override protected Modelandview OnSubmit (httpservletrequest request, httpservletresponse response, Object com Mand, 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); 
  The 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; 
 The 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; 
 The public void Setuserage (Integer userage) {this.userage = Userage; } </pre><br> <p align= "left" ><span style= "Color:teal" > class creation is complete, we 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 "class=" HTML "><%@ 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" >  

Instance Download: Demo

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.