A little look at the use of Jndi in Spring, a small example. There are a lot of imperfect places, later look slowly, then change it.
< one > technology use
Spring MVC
JDBC Template
Maven
Jndi
< two > some configurations
Maven POM Configuration
Spring-context, Spring-webmvc, Spring-orm, SPRING-JDBC, Mysql-connector-java, etc.
Create a database
Create Database Usersdb; CREATE TABLE ' users ' (' user_id ' int (one) not NULL auto_increment, ' username ' varchar "not NULL, ' password ' varchar (4 5) Not NULL, ' email ' varchar (PRIMARY KEY (' user_id ')) is not NULL, Engine=innodb auto_increment=16 DEFAULT Charset=lati N1
3. Configuring the Jndi data source in Tomcat
It can also be configured elsewhere, such as in Web. Xml. This configuration is for Jndi to be able to find the data source.
<resourcename= "Jdbc/usersdb" auth= "Container" type= "Javax.sql.DataSource" maxactive= "maxidle=" "maxwait=" 10000 "driverclassname=" Com.mysql.jdbc.Driver "url=" Jdbc:mysql://localhost:3306/usersdb "username=" XXX "password=" YYY "/>
Description: Resource's Name property "Jdbc/userdb" will be used in SPRING-MVC.
Description: The so-called configuration in Tomcat can be in Tomcat's context.xml, adding the resource entry.
< three >java development
1.Mode, User.java
public class User {private int id;private string Username;private string Password;private string email;//getter Setter}
2.DAO class
Public interface Userdao {public list<user> List ();}
You can use the JDBC Template to implement this data operation and expand the operation.
3. Introducing a Jndi data source in spring MVC
Since I am using spring 4, I prefer the Java Config pattern, so the method of introducing Jndi is as follows:
@Beanpublic Userdao Getuserdao () throws namingexception {jnditemplate jnditemplate = new Jnditemplate (); DataSource DataSource = (DataSource) jnditemplate.lookup ("Java:comp/env/jdbc/usersdb"); return new Userdaoimpl (DataSource);}
It is necessary to note that this prefix is comp/env.
4.Controller class
@Controllerpublic class HomeController {@Autowiredprivate Userdao Userdao; @RequestMapping (value= "/") public Modelandview Home () throws ioexception{list<user> ListUsers = Userdao.list (); Modelandview model = new Modelandview ("Home"); Model.addobject ("UserList", listUsers); return model;}}
5. The front-end display section is as follows:
<div align= "center" >
< four > effect is as followsA humble page is as follows:
Spring MVC uses JNDI configuration for datasource