SPRINGMVC + Hibernate + MySQL Easy Web building (control implementation)

Source: Internet
Author: User

After completing the implementation of the DAO layer, we need to continue to develop the control layer and the view layer of our web page.

From the perspective of developing Web pages:

1. The DAO Layer and service layer under the control layer can be regarded as the bottom of a Web page that is responsible for interacting with the database, persisting data, implementing some logical business, etc.

2. The control layer itself is the middle layer of a Web page, which is responsible for connecting the DAO layer and the View layer, transmitting the view layer request to the DAO layer, and fetching the data from the DAO layer and then returning to the view layer for display

3. View layer is the upper level of the Web page, responsible for directly interacting with the user, to obtain the user's needs, the user's needs into a request, down to pass with the control layer.

And in terms of hierarchy, control and view are more closely connected, so often these two layers are developed together.

In the control layer development, because each part of the Web page can be performed differently, can be based on these different behavioral operations to differentiate a number of controllers to monitor the operation of the Web page, such as our web page just opened, we need to do a user login process, Then we can differentiate a userlogincontroller response and action to a user's behavior from the view-pass request.

Here to add a point, based on the framework after the SpringMVC3.0, Web page URL request mapping can be in the form of annotations @RequestMapping, very easy to develop, and for each URL request of the corresponding return, can be configured by the configuration file, Return the corresponding string directly, the view layer will show the corresponding JSP page, or you can return the Modelandview object, you can pass the data to the JSP page.

The following is the implementation of the user login controller Userlogincontroller code:

 PackageFmu.wellhold.controller;Importjava.util.ArrayList;ImportJava.util.HashMap;Importjava.util.List;ImportJava.util.Map;ImportJavax.annotation.Resource;Importjavax.servlet.http.HttpServletRequest;ImportOrg.springframework.stereotype.Controller;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RequestMethod;ImportOrg.springframework.web.servlet.ModelAndView;ImportFmu.wellhold.dao.ITF.UserInfoDaoITF;ImportFmu.wellhold.dao.pojo.UserInfo; @Controller Public classUserlogincontroller {@ResourcePrivateUSERINFODAOITF Userinfoservice; @RequestMapping (Value= "/index", method={requestmethod.get}) PublicString Modelautobindtoindex (httpservletrequest request) {//Practical view mapping in conjunction with XMLSystem.out.println (">>>> has activated controller"); return"Index"; } @RequestMapping (Value= "/index", method ={requestmethod.post}) PublicModelandview modelautobindtologin (httpservletrequest request,userinfo UserInfo) {List List=NewArrayList (); List=userinfoservice.findbynamepwd (Userinfo.getid (), userinfo.getpwd ()); System.out.println ("The result of the query is:" +list.size ()); if(List.isEmpty ()) {System.out.println (">>>> does not exist for this user");//Model.addattribute ("Accountmodel", UserInfo);            return NewModelandview ("Forworld", "Erro", "The user is not exit"); }        Else{UserInfo User= (UserInfo) list.get (0); if(User.getnumber () <=10) {System.out.println (">>>> The user is an administrator");                    List.add (Userinfoservice.findall ()); System.out.println (List.get (0)); return NewModelandview ("ShowUser1", "list", list); } System.out.println (">>>> Normal User Login"); Map Map=NewHashMap (); Map.put ("User", user); return NewModelandview ("UserInfo", "Map", map); }    }    }
Method Modelautobindtoindex function is when the browser input http://localhost:8080/MoneyRecordSys/index, Returns a response to the view layer that shows index.jsp, while the method Modelautobindtologin is when the user from the Index.jsp page
When you post back some data, the method that the controller maps to is responsible for the logical processing and again returns the view next response to the view layer, that is, which page should continue to be displayed. This is showuser1.jsp, and the list object is uploaded to the JSP, List[0] records the current
User information, list[1] contains another list, which is the data for all users in the page.

Here is the index.jsp code:
<%@ page language= "java" contenttype= "text/html" pageencoding= "Utf-8"%><! DOCTYPE html>nbsp; <input type= "Submit" value= "Login" style= "HEIGHT:50PX;WIDTH:200PX;FONT-SIZE:18PT;FONT-FAMILY:CALIBRI; Font-weight:bold "></td> </tr> </table> </form> &LT;BR&G        T </body>

Here is a point: in the JSP, we can see the label name and ID are two concepts, name is background-oriented, the ID is the JSP, in index.jsp we will enter the user name and password to name= "id" and name= "pwd"

The acceptance method for the post back controller is public modelandview modelautobindtologin (httpservletrequest request,userinfo UserInfo), The formal parameters are not httpservletresponse but userinfo because

UserInfo this Pojo class, there are exactly two fields named ID and pwd, so the index.jsp post back username and password are automatically parsed into the userinfo.

When the user is logged in successfully with the administrator's permission, and enters into the main interface, and can do a series of operations to the registered user information of the webpage, this series of operations, we differentiate a Useroperationcontroller controller to manage and monitor, including

Add a user, delete a user, change a user's information, and so on.

 PackageFmu.wellhold.controller;ImportJava.io.PrintWriter;Importjava.util.ArrayList;ImportJava.util.HashMap;Importjava.util.List;ImportJava.util.Map;ImportJavax.annotation.Resource;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportOrg.springframework.stereotype.Controller;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RequestMethod;ImportOrg.springframework.web.servlet.ModelAndView;ImportFmu.wellhold.dao.ITF.UserInfoDaoITF;ImportFmu.wellhold.dao.pojo.UserInfo; @Controller Public classUseroperationcontroller {@ResourcePrivateUSERINFODAOITF Userinfoservice; @ResourcePrivateFileUpload FileUpload;//injection doesn't need new.@RequestMapping (Value= "ShowUser1", method={requestmethod.get}) PublicModelandview Showuser (httpservletrequest request,httpservletresponse response) {String number= Request.getparameter ("number"); List List=NewArraylist<>(); List.add (Userinfoservice.findbyld (integer.valueof (number));//System.out.println ("Showuser controller has been started");List.add (Userinfoservice.findall ()); return NewModelandview ("ShowUser1", "list", list); } @RequestMapping (Value= "Updatetheuser", method={requestmethod.get}) PublicModelandview Gettoupdatetheuser (httpservletrequest request,httpservletresponse response)throwsException {String number= Request.getparameter ("number"); String User= Request.getparameter ("User");//System.out.println ("Updatetheuser, already activated controller");List list=NewArraylist<>(); UserInfo User1=(UserInfo) userinfoservice.findbyld (integer.valueof (user));        List.add (user1);        List.add (Userinfoservice.findbyld (integer.valueof (number)); return NewModelandview ("Updatetheuser", "list", list); } @RequestMapping (Value= "Posttheupdateuserinfo", method={requestmethod.post}) PublicModelandview Updatetheuserinfo (httpservletrequest request,httpservletresponse response)throwsException {Map<string, string> map =fileupload.upload (request, response);//System.out.println (map.tostring ());UserInfo user =NewUserInfo (); User.setid (Map.get ("id")); User.setpwd (Map.get ("PWD")); User.setname (Map.get ("Name")); User.setsex (Map.get ("Sex"));//User.setbirthday (map.get ("Birthday"));User.setcome (Map.get ("Come")); User.setremark (Map.get ("Remark")); User.setnumber (integer.valueof (Map.get ("Number"). toString () ));//System.out.println (user.tostring ());userinfoservice.update (user);//return null;        returnShowuser (request, response); } @RequestMapping (Value= "DeleteUser", method={requestmethod.get}) PublicModelandview DeleteUser (httpservletrequest request,httpservletresponse response)throwsException {String number=request.getparameter ("Deleteusernum");//System.out.println ("DeleteUser" +number);Userinfoservice.delete (integer.valueof (number)); returnShowuser (request, response); } @RequestMapping (Value= "Inserttheuser", method={requestmethod.get}) PublicModelandview Gettoinsertuser (httpservletrequest request,httpservletresponse response)throwsException {String number= Request.getparameter ("number");//System.out.println ("Inserttheuser, already activated controller");List list=NewArraylist<>(); UserInfo User1=(UserInfo) Userinfoservice.findbyld (integer.valueof (number));        List.add (user1); return NewModelandview ("Inserttheuser", "list", list); } @RequestMapping (Value= "Posttheinsertuserinfo", method={requestmethod.post}) PublicModelandview Posttheinsertuserinfo (httpservletrequest request,httpservletresponse response)throwsException {//System.out.println ("Posttheinsertuserinfo controller has been started");map<string, string> map =fileupload.upload (request, response);//System.out.println (map.tostring ());        if(Map! =NULL) {UserInfo user=NewUserInfo (); User.setid (Map.get ("id")); User.setpwd (Map.get ("PWD")); User.setname (Map.get ("Name")); User.setsex (Map.get ("Sex")); User.setcome (Map.get ("Come")); User.setremark (Map.get ("Remark"));        Userinfoservice.insert (user); }        Else{PrintWriter out=Response.getwriter (); Out.print ("<script type= ' Text/javascript ' >"); Out.print ("Alert (' The new user you submitted is empty ');"); Out.print ("Window.history.go (-1);"); Out.print ("</script>");        Out.close (); }        returnShowuser (request, response); }}

Not to be continued ...

Springmvc + Hibernate + MySQL Easy Page Setup (Control implementation)

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.