SpringMvc (2) Configure SpringMvc

Source: Internet
Author: User

I recently learned spring MVC and set up it myself. I also took notes and shared it. I will not talk about using Eclipse jee and Eclipse to create a new web project. I have introduced this article in the previous article, let's talk about configuring Spring directly. You must first go to the web. interceptor in xml configuration

 
   
  
   
SpringMVC
    
      
   
    
Index.html
       
   
    
Index.htm
       
   
    
Index. jsp
       
   
    
Default.html
       
   
    
Default.htm
       
   
    
Default. jsp
     
  
  
  
      
   
    
Org. springframework. web. context. ContextLoaderListener
   
  
  
      
   
    
ContextConfigLocation
       
   
    
Classpath: applicationContext. xml
   
  
  
      
   
    
Dispatcher
       
   
    
Org. springframework. web. servlet. DispatcherServlet
       
       
           
    
     
ContextConfigLocation
            
    
     
Classpath: servlet-context.xml
        
       
       
   
    
1
   
  
  
      
   
    
Dispatcher
       
   
    
*. Action
   
  
  
      
   
    
CharacterEncoding
       
   
    
Org. springframework. web. filter. CharacterEncodingFilter
       
           
    
     
Encoding
            
    
     
UTF-8
        
   
  
  
      
   
    
CharacterEncoding
       
   
    
/*
   
    
 
A servlet application container is configured here, And the configuration file is stored in the root path, so that we can put it in the resource. As the name implies
Let's first look at servlet. xml.

 
 
  
  
   
   
  
  
  
  
 

For HandlerMapping and handlerAdapter, I will directly explain them in others' blogs:

In SpringMVC, a qualified request enters the DispatcherServlet responsible for request distribution. DispatcherServlet maps the request url to the Controller (stored in HandlerMapping) and HandlerMapping returns HandlerExecutionChain, it contains the specific processing Object handler (the controller we wrote during programming) and a series of interceptor interceptors, in this case, DispatcherServlet will find an adapter (handlerAdapter) that supports this processor type based on the HandlerExecutionChain returned by DispatcherServlet. In the processor adapter, it will eventually call the Request Response Method of the controller and return the result view (ModelAndView)

Then application. xml

 
 
  
  
  
  
   
  
  
  
   
   
   
   
   
   
  
  
  
   
  
 

Here is the path to scan the annotation, and then configure a database connection. Basically, the configuration file is ready. We can simply write a small program, continue to divide dao, service, and control in the web project under construction (example of the article on building a web project in Eclipse)

The structure is clear. I seem to have forgotten about log4j. configure it first to facilitate debugging.

log4j.rootCategory=INFO,A1log4j.appender.A1=org.apache.log4j.ConsoleAppenderlog4j.appender.A1.layout=org.apache.log4j.PatternLayout
Also put it under resource, log4j. properties. In simple configuration, only info is output to the console. Then I can start writing code. What should I do? I want to create a simple accounting system. There are many such applications on the mobile phone that record the money spent every day, the amount of money, and then there is a summary of what, the function is not much, good implementation. It seems that the Code cannot be written first. First, the database should be completed. The following design is performed:


Of course, I have never designed this kind of software. I just imagined it out of thin air. to simply get these two tables, I should have understood it at a Glance. The database IDs are set to auto-increment, account time, amount, in the inbound and outbound directions, the Account type is a type table that can be customized (meal, entertainment, and salary), and then a type table is created for category subdivision. You can use the parent class ID to plan the child parent class relationship, for example, breakfast, lunch, and dinner are all nonsense. The amount is int. Here, the database records the amount based on the smallest unit, so there is no decimal point. Then, the database can write two entity classes.

Package com. springMvc. dao. entity; import java. SQL. date; public class Account {private String id; // database IDprivate Date acc_time; // time private Integer acc_jine; // amount private boolean acc_shouzhi; // access private Integer acc_type; // category private String acc_beizhu; // remarks // getters and setters

Package com. springMvc. dao. entity; public class Type {private Integer type_id; // database IDprivate String type_name; // Type description private Integer type_parent; // parent class ID getters and setters
Then there is the Manager. Here we will write a simple account Manager and write two

Package com. springMvc. dao. manager; import org. apache. log4j. logger; import org. springframework. beans. factory. annotation. autowired; import org. springframework. jdbc. core. jdbcTemplate; import org. springframework. stereotype. repository; import com. springMvc. dao. entity. account;/* define a Dao through Spring annotation, here, I simply wrote the Dao and directly wrote it in the Manager */@ Repositorypublic class AccountManager {/* bean that automatically injects jdbcTemplate */@ Autowiredprivate JdbcT Emplate jdbcTemplate; // loggerprivate final static Logger logger = Logger. getLogger (AccountManager. class); public int insertAccount (Account ac) {logger.info ("---------------- insert accounts into the database, dao layer --! ");/* SQL */String SQL =" insert into account_info (acc_time, acc_jine, acc_shouzhi, acc_type, acc_beizhu) "+" values (?,?,?,?,?) ";/* Input parameter */Object [] args = {ac. getAcc_time (), ac. getAcc_jine (), ac. isAcc_shouzhi (), ac. getAcc_type (), ac. getAcc_beizhu ()}; return jdbcTemplate. update (SQL, args); // return success Failed }}
Package com. springMvc. dao. manager; import java. SQL. resultSet; import java. SQL. SQLException; import java. util. arrayList; import java. util. list; import org. apache. log4j. logger; 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 com. springMvc. model. typeInfo; @ Repositorypublic class TypeManager {/* automatically injects jdbcTemplate bean */@ Autowiredprivate JdbcTemplate jdbcTemplate; // loggerprivate final static Logger logger = Logger. getLogger (TypeManager. class);/*** provides a method to query all the underlying classes and select */public List when inserting data to the foreground.
 
  
SelectAllTypes () {logger.info ("---------------- query available type, dao layer --! ");/* Here I imagine that id is definitely the most subclass if it is not someone else's parent class id, and SQL is not very good at it, for more information, see */String SQL = "select type_id, type_name from account_type where type_id not in" + "(select distinct type_parent from account_type)"; final List
  
   
ResultList = new ArrayList
   
    
(); JdbcTemplate. query (SQL, new RowCallbackHandler () {@ Overridepublic void processRow (ResultSet rs) throws SQLException {TypeInfo ty = new TypeInfo (); ty. setType_id (rs. getInt ("type_id"); ty. setType_name (rs. getString ("type_name"); resultList. add (ty) ;}}); return resultList ;}}
   
  
 

One account manager and one type manager provide the insert method respectively, and select the account type list when inserting. Basically enough. Here a type model is used in the returned type list, as shown below:

Package com. springMvc. model; public class TypeInfo {private Integer type_id; // idprivate String type_name; // description public Integer getType_id () {return type_id;} public void setType_id (Integer type_id) {this. type_id = type_id;} public String getType_name () {return type_name;} public void setType_name (String type_name) {this. type_name = type_name ;}}

Then write the service.

Package com. springMvc. service; import com. springMvc. dao. entity. account; public interface AccountService {/*** insert Account */public void insertAccout (Date acc_time, Integer acc_jine, Integer acc_shouzhi, Integer acc_type, Integer acc_beizhu );}

Package com. springMvc. service; import java. util. List; import com. springMvc. model. TypeInfo; public interface TypeService {/*** retrieve available type */public List
 
  
SelectAllTypes ();}
 
Package com. springMvc. service. impl; import java. SQL. date; import org. apache. log4j. logger; import org. springframework. beans. factory. annotation. autowired; import org. springframework. stereotype. service; import com. springMvc. dao. entity. account; import com. springMvc. dao. manager. accountManager; import com. springMvc. service. accountService; @ Service // A servicepublic class AccountServiceImpl implements Acco UntService {// loggerprivate final static Logger logger = Logger. getLogger (AccountServiceImpl. class); @ Autowired // automatically assemble dao beanprivate AccountManager accountManager; @ Overridepublic void insertAccout (Date acc_time, Integer acc_jine, Integer acc_shouzhi, Integer acc_type, Integer acc_beizhu) {logger.info ("---------------- Insert the account to the Service layer --! "); Account ac = new Account (); ac. setAcc_time (acc_time); ac. setAcc_jine (acc_jine); ac. setAcc_shouzhi (acc_shouzhi = 1? True: false); ac. setAcc_type (acc_type); accountManager. insertAccount (ac );}}


Package com. springMvc. service. impl; import java. util. list; import org. apache. log4j. logger; import org. springframework. beans. factory. annotation. autowired; import org. springframework. stereotype. service; import com. springMvc. dao. manager. typeManager; import com. springMvc. model. typeInfo; import com. springMvc. service. typeService; @ Servicepublic class TypeServiceImpl implements TypeService {// loggerprivate final static Logger logger = Logger. getLogger (TypeServiceImpl. class); @ Autowired // automatically assemble dao beanprivate TypeManager typeManager; @ Overridepublic List
 
  
SelectAllTypes () {logger.info ("---------------- retrieve available type, Service layer --! "); Return typeManager. selectAllTypes ();}}
 

There are two service interfaces and two implementation classes. There is nothing to explain, and then two controllers are written. One is to call an optional type of action when entering the accounting page, and the other is to save the accounting action as follows:

Package com. springMvc. controller; import java. SQL. date; import org. apache. log4j. logger; import org. springframework. beans. factory. annotation. autowired; import org. springframework. stereotype. controller; import org. springframework. web. bind. annotation. requestMapping; import org. springframework. web. bind. annotation. requestParam; import org. springframework. web. servlet. modelAndView; import com. springMvc. service. ac CountService; @ Controllerpublic class AccountController {// loggerprivate final static Logger logger = Logger. getLogger (AccountController. class); @ Autowired // automatically assemble Service beanprivate AccountService accountService; @ RequestMapping (value = "/insert. action ") public ModelAndView insertAccount (@ RequestParam (" acc_time ") Date acc_time, @ RequestParam (" acc_jine ") Integer acc_jine, @ RequestParam (" acc_shouzhi ") Inte Ger acc_shouzhi, @ RequestParam ("acc_type") Integer acc_type, @ RequestParam ("acc_beizhu") String acc_beizhu) {logger.info ("---------------- insert an account into Controller --! "); AccountService. insertAccout (acc_time, acc_jine, acc_shouzhi, acc_type, acc_beizhu);/* return to the home page due to our index. jsp is placed outside the view web-inf, so two are written .. /retrieve the upper-level directory. * normally, you should set the index. jsp is directly placed in the view folder */return new ModelAndView (".. /.. /index ");}}


Package com. springMvc. controller; import java. util. list; import org. apache. log4j. logger; 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 com. springMvc. model. typeInfo; import com. springMvc. service. typeService; @ Controllerpu Blic class TypeController {// loggerprivate final static Logger logger = Logger. getLogger (TypeController. class); @ Autowired // automatically assemble Service beanprivate TypeService typeService; @ RequestMapping (value = "/toInsertPage. action ") public ModelAndView listAllType () {logger.info (" ---------------- call available type to enter Controller --! "); List
 
  
Types = typeService. selectAllTypes (); // view name, respectively (the insert under view is configured with the prefix suffix. jsp,) is followed by the model object return new ModelAndView ("insert", "types", types );}}
 
The controller has been written, and the front-end has been written. No front-end colleagues have to write it by themselves. We add a jump button to the helloworld page to connect to toInsertPage. action to request the available Account type and return to insert. jsp. then insert. jsp fills in the account form to verify the data and submits it to insert. action is returned to index. jsp. In fact, an insert. jsp is as follows:

<% @ Page language = "java" contentType = "text/html; charset = UTF-8 "pageEncoding =" UTF-8 "%> <% @ taglib prefix =" c "uri =" http://java.sun.com/jsp/jstl/core "%>
 Insert title here<Script type = "text/javascript"> function checkData () {var acc_time = document. getElementById ("acc_time "). value; var acc_jine = document. getElementById ("acc_jine "). value; var acc_beizhu = document. getElementById ("acc_beizhu "). value; var regDate =/^ (\ d {4})-(\ d {2})-(\ d {2}) $ /; var regJine =/^ [0-9] * [1-9] [0-9] * $/; if (! RegDate. test (acc_time) {alert ("enter the correct date"); return false;} if (! RegJine. test (acc_jine) {alert ("enter the correct amount"); return false;} if (acc_beizhu.length> 100) {alert ("Remarks too long"); return false ;}} </script>
Tomcat run, enter hello world, click Add account, jump to fill in the form, fill in the content, submit, jump back to the hello world page, logger info is as follows: the process is very clear, just like this


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.