软件架构期末复习(Struts2+Spring+Hibernate)

Struts2+Spring+Hibernate

  1. The Model-ViewController pattern in Struts2 is implemented with the following core component.
    1. Structure
    2. Interceptors
    3. Array
    4. Database
  2. Create configuration files to couple the Action, View and Controllers. These files are_______.
    1. Struts.xml, web.xml, struts.properties.
    2. Class.xml, web.xml, Struct2.html
    3. Class.xml, web.xml, struts.xml
    4. struts.xml, Class.xml,, struts.properties.
  3. How to enable Detailed Log.
    1. creating logging.properties
    2. creating logging.xml
    3. creating logging.html
    4. None of the above.
  4. Struct act much more friendly for developer if we set.
    1. Structs.devmode= Null;
    2. Structs.devmode= Auto;
    3. Structs.devmode= True;
    4. Structs.devmode= False;
  5. Here any line starting with hash (#) will be assumed as a ____ .
    1. Instruction
    2. Execution line
    3. Address
    4. Comments
  6. What are the Struts2 configuration properties that control file uploading process?
    1. struts.multipart.maxSize
    2. struts.multipart.parser
    3. struts.multipart.saveDir
    4. All of the above.
  7. Can you override the default error message that can come during file uploading process?
    1. Yes
    2. No
  8. The following code refer to.

        

    1. Stacking Multiple Interceptors
    2. Configuration Interceptor
    3. Action Interceptor
    4. Interceptor Attribute

        9.You can call same interceptor with the different actions.

    1. True
    2. False

10. These objects include #application, #session, #request, #attr and #parameters and refer to the corresponding servlet scopes.

  1. True
  2. False

11. Object peek() Get the object on the top of the stack and changing the stack.

  1. True
  2. False

12. Which of the following sentence is the true for the ONGL

  1. The Object-Graph Navigation Language (OGNL) is a powerful expression language that is used to reference and manipulate data on the ValueStack. 
  2. OGNL also helps in data transfer and type conversion.
  3. The OGNL is very similar to the JSP Expression Language. 
  4. All of the above

13. If you have an attribute in session called "login" you can retrieve it as follows _______.

  1. <s:property value=”#session.login”/>
  2. <s:property value=”@session.login”>
  3. <s:property value=”session.login”/s>
  4. <s:property name=”@session.login”>

14. struts.multipart.saveDir The location to store the temporary file. By default is______.

  1. javax.servlet.context.Userdirectory
  2. javax.servlet.path.tempdir.
  3. javax.servlet.context.tempdir.
  4. javax.servlet.path.Userdirectory.

15. struts.messages.error.uploading

  1. A general error that occurs when the file could not be open.
  2. A general error that occurs when the file could not be uploaded.
  3. A general error that occurs when the file could not be match the name.
  4. A general error that occurs when the file could not be Downloaded.

16. The simplest naming format for a resource file is ______.

  1. Bundlename_language_country.propertiers
  2. Recourse_language_country.propertiers
  3. Bundlename_language_country.recourse
  4. None of the above

17. By default, English (United States) will be applied

  1. global_us.properties
  2. global_en.properties  
  3. global.properties 
  4. global.properties­_us 

18. the following instruction show the Customized them.

  1. Struts.ui.theme=mytheme
  2. Struts.ui.templateDir=template
  3. Struts.ui.templateSuffix= ftl
  4. Struts.ui.theme= Custom_theme

19. To start using annotations in your project, make sure you have included the following jar files in your _______.

  1. WebContent/WEB-INF/elb
  2. WebContent/WEB-INF/lib
  3. WebContent/Localhost:8080/lib
  4. Localhost:8080/WEB-INF/lib 

20. Following is the iterator tag.

  1. <s:param_iterate value=”interate”>
  2. <s:param.iterate value=”interate”>
  3. < iterate value=” iterate”>
  4. <s:iterate value=”data”/>

21. In the following which sentence Define the Action.

  1. Create interceptors if required, or use existing interceptors. This is part of Controller.
  2. Create a class which will contain complete business logic and control the interaction between the user, the model, and the view.
  3. Create a JSPs to interact with the user to take input and to present the final messages.
  4. Create files to couple the Action, View and Controllers. These files are struts.xml, web.xml, struts.properties.

22. Following is the example to create _____ page.

  • <%@ page contentType = "text/html; charset = UTF-8" %>
  • <%@ taglib prefix = "s" uri = "/struts-tags" %>
  • <html>
  • <head>
  • <title>Hello World</title>
  • </head>
  • <body>
  • Hello World, <s:property value = "name"/>
  • </body>
  • </html>
  1. Main Page
  2. Action Page
  3. View
  4. File configuration

23. The Model-ViewController pattern in Struts2 is implemented with the _ core ___ components.

  1. Two
  2. Three
  3. Seven
  4. Five
  • Actions
  • Interceptors
  • Value Stack / OGNL
  • Results / Result types
  • View technologies

24. Which of the following tag is used to get the property of a value, which will default to the top of the stack if none is specified?

  1. date tag
  2. Param tag
  3. Property tag
  4. Push tag

25. The following code refer to Interceptor Property

<interceptor-stack name = "basicStack">
<interceptor-ref name = "exception"/>
<interceptor-ref name = "servlet-config"/>
<interceptor-ref name = "prepare"/>
<interceptor-ref name = "checkbox"/>
 <interceptor-ref name = "params"/>
<interceptor-ref name = "conversionError"/>
</interceptor-stack>
  1. True
  2. False

26. The Below file is a template where name is a parameter which will be passed from outside using the defined action. 

  1. Hello world ${name}
  2. Hello World(Name)
  3. Helloworld(#name)
  4. Hello world {$name}

27. The Struts 2 framework provides built-in support for processing file upload using "Form-based File Upload in HTML".

  1. False
  2. True

28. The following chunk of code we use in _____.

import java.io.File;

import org.apache.commons.io.FileUtils;

import java.io.IOException;

  1. View Class
  2. Main Class
  3. Action Class
  4. Option (A) and (C)

29. struts.multipart.maxSize The maximum size (in bytes) of a file to be accepted as a file upload. Default is______.

  1. 300M
  2. 150M
  3. 250M
  4. 500M

30. Following is the append tag.

  1. <s:param_append value=”interate”>
  2. <s:param.append value=”interate”>
  3. < append value=” iterate”>
  4. <s:append value=”data”/>

31. struts.multipart.saveDir The location to store the temporary file. By default is javax.servlet.context.Userdirectory.

  1. True
  2. False

32. You can call same interceptor with the different actions.

  1. True
  2. False

33. Object peek() Get the object on the top of the stack and changing the stack.

  1. True
  2. False

34. What are the Struts2 configuration properties that control file uploading process?

  1. struts.multipart.maxSize
  2. struts.multipart.parser
  3. struts.multipart.saveDir
  4. All of the above

35. If you have an attribute in session called "login" you can retrieve it as follows___.

  1. <s:property value=”#session.login”/>
  2. <s:property value=”@session.login”>
  3. <s:property value=”session.login”/s>
  4. <s:property name=”@session.login”>

36. int size() Get the number of objects in the stack.

  1. True
  2. False

37. The simplest naming format for a resource file is ______.

  1. Bundlename_language_country.propertiers
  2. Recourse_language_country.propertiers
  3. Bundlename_language_country.recourse
  4. None of the above

38. In addition to the above, we have to copy the following jar files from the struts2 download in your WEB-INF/lib.

  1. commons-beanutils-x.y.zjar
  2. commons-digester-x.y.jar
  3. struts2-tiles-plugin-x.y.z.jar

39. The configLocation parameter specifies the name and location of the Spring configuration file, such as "applicationContext. xml".

  1. configLocation
  2. #config_Location
  3. configLocation_Path
  4. #Path_configLocation

40. commons-fileupload-x.y.z.jar, commons-io-x.y.z.jar, commons-lang-x.y.jar, commons-logging-x.y.z.jar, commons-logging-api-x.y.jar,freemarker-x.y.z.jar etc. filse are used to creat.

  1. Action page
  2. Static Project
  3. Dynamic Project

41. The redirect result type calls the standard ____ method, causing the browser to create a new request to the given location.

  1. response.sendRedirect() 
  2. response.Redirect() 
  3. location.sendRedirect() 
  4. location.Redirect(path) 

42. int size() Get the number of objects in the stack.

  1. True
  2. False

43. Following is the Generator tag.

  1. <s:param_Generator value=” Generator”>
  2. <s:param. Generator value=” Generate”>
  3. < Generator value=” iterate”>
  4. <s: Generator value=”data”/>

44. The configLocation parameter specifies the name and location of the Spring configuration file, such as "applicationContext. xml".

  1. configLocation
  2. #config_Location
  3. configLocation_Path
  4. #Path_configLocation

45. Which class of struts is responsible to converts data types from string?

  1. StrutsTypeConverter
  2. StringTypeConverter
  3. Both of the above.
  4. None of the above.

46. In the following which sentence Define the Configuration Files.

  1. Create interceptors if required, or use existing interceptors. This is part of Controller.
  2. Create a class which will contain complete business logic and control the interaction between the user, the model, and the view.
  3. Create a JSPs to interact with the user to take input and to present the final messages.
  4. Create files to couple the Action, View and Controllers. These files are struts.xml, web.xml, struts.properties.

47. commons-fileupload-x.y.z.jar, commons-io-x.y.z.jar, commons-lang-x.y.jar, commons-logging-x.y.z.jar, commons-logging-api-x.y.jar,freemarker-x.y.z.jar etc. filse are used to creat.

  1. Action page
  2. Static Project
  3. Dynamic Project
  4. None of the above

48. It should be noted that you can register more than one interceptors inside <package> tag and same time you can call more than one interceptors inside the <action> tag.

  1. True
  2. False

49. struts.multipart.maxSize The maximum size (in bytes) of a file to be accepted as a file upload. Default is 100M.

  1. True
  2. False

50. In addition to the above, we have to copy the following jar files from the struts2 download in your WEB-INF/lib.

  1. commons-beanutils-x.y.zjar
    1. commons-digester-x.y.jar
    2. struts2-tiles-plugin-x.y.z.jar
    3. All of the above

51. Following is the iterator tag.

  1. <s:param_iterate value=”interate”>
  2. <s:param.iterate value=”interate”>
  3. < iterate value=” iterate”>
  4. <s:iterate value=”data”/>

52. By default, English (United States) will be applied

  1. global_us.properties
  2. global_en.properties  
  3. global.properties 
  4. global.properties­_us 

53. struts.messages.error.uploading

  1. A general error that occurs when the file could not be open.
  2. A general error that occurs when the file could not be uploaded.
  3. A general error that occurs when the file could not be match the name.
  4. A general error that occurs when the file could not be Downloaded.

54. Which of the following sentence is the true for the ONGL

  1. The Object-Graph Navigation Language (OGNL) is a powerful expression language that is used to reference and manipulate data on the ValueStack. 
  2. OGNL also helps in data transfer and type conversion.
  3. The OGNL is very similar to the JSP Expression Language. 
  4. All of the above

55. These objects include #application, #session, #request, #attr and #parameters and refer to the corresponding servlet scopes.

  1. True
  2. False 

PART B

Question #2: Write a program to show the following data grid using jQuery.

编写一个程序,使用jQuery显示以下数据网格。

1、前端文件

 1 <table id="dg">
 2     <div class="easyui-tabs" data-options="url:tab_data.json,tabWidth:112" style="width:700px;height:250px">
 3         <div title="Order" style="padding:10px"></div>
 4         <div title="Contact Inofmation" style="padding:10px"></div>
 5     </div>
 6 </table>
 7 <script >
 8     $('#dg').datagrid({
 9         url:'datagrid_data.json',
10         columns:[[
11             {field: 'First Name',title:'First Name'  ,width:100},
12             {field: 'Last Name' ,title:'Last Name'  ,width:100},
13             {field: 'Title'           ,title:'Title'            ,width:100},
14                     {field: 'Country'     ,title:'Country'       ,width:100},
15                    {field: 'City'           ,title:'City'             ,width:100}
16         ]]
17     });
18 </script>

Question#3: Spring MVC File Upload example. (write controller class)     

Spring MVC文件上传示例

 1 @requestMapping(value = "/upload")
 2 public String upload(@RequestParam(value="file",required=false)
 3 MultipartFile file, HttpServaletRequest request, ModelMap model){
 4     String path = request.getSession().getServletContext().getRealPath("upload");
 5     String fileName = file.getOriginalFilename();
 6     File targetFile = new File(path, fileName);
 7     if(!targetFile.exists()){
 8         targetFile.mkdirs();
 9     }
10     try{
11         file.transferTo(targetFile);
12     }
13     catch(Exception e){
14         e.printStackTrace();
15     }
16     model.put("fileUrl",request.getContextPath()+"/upload/"+fileName);
17     return "success";
18 }

Question#4: Create the action class for the following view My Order.

 为以下视图My Order创建action类。

 1 public String toMyOrders() throws Exception {
 2         int curPage = 1;
 3         if (pager != null)
 4             curPage = pager.getCurPage();
 5         Users user = (Users) session.get("user");
 6         Orders condition = new Orders();
 7         condition.setUsers(user);
 8         List myOrdersList = ordersService.getOrdersByUserIdForPager(
 9                 user.getId(), curPage);
10         request.put("myOrdersList", myOrdersList);
11         pager = ordersService.getPagerOfMyOrders(user.getId());
12         pager.setCurPage(curPage);
13         return "myorders";
14     }

Question#5: write a code to Create Multiple View Page in Spring MVC with example. (at least 3 pages).           

编写代码在Spring MVC中创建多个视图页面的例子。(最少3页)

 1 <context:component-scan 
 2      base-package="com.spring.action"/> 
 3         <bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver"> 
 4         <property name="basename" value="views"> 
 5           </bean> 
 6     <bean id="freemarkerConfig" 
 7      class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> 
 8     <bean id="velocityConfig"  class="org.springframework.web.servlet.view.velocity.VelocityConfigurer"> 
 9      </bean> 
10     <bean id="viewResolver" 
11      class="com.spring.action.MultiViewResover"> 
12         <property name="resolvers"> 
13             <map> 
14                 <entry key="jsp"> 
15                     <bean 
16                      class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
17                         <property name="viewClass" 
18                          value="org.springframework.web.servlet.view.JstlView"/> 
19                         <property name="prefix" value="/WEB-INF/jsp/"/> 
20                         <property name="suffix" value=".jsp"/> 
21                     </bean> 
22                 </entry> 
23                 </map> 
24         </property> 
25     </bean> 
26 </beans> 
27 第二步:解析多视图请求类
28 public class MultiViewResover implements ViewResolver { 
29     private Map<String, ViewResolver> resolvers; 
30     @Override 
31     public View resolveViewName(String viewName, Locale locale) 
32             throws Exception { 
33         int n = viewName.lastIndexOf("_"); 
34         if (n == (-1)) 
35             return null; 
36         String suffix = viewName.substring(n + 1); 
37         ViewResolver resolver = resolvers.get(suffix); 
38 hello_jsp 
39         viewName = viewName.substring(0, n); 
40         if (resolver != null) 
41             return resolver.resolveViewName(viewName, locale); 
42         return null; 
43     } 
44     public Map<String, ViewResolver> getResolvers() { 
45         return resolvers; 
46     }
47     public void setResolvers(Map<String, ViewResolver> resolvers) { 
48         this.resolvers = resolvers; 
49     } 
50 } 
51 第三步: action class
52 @Controller 
53 public class HelloWorldAction { 
54     @RequestMapping(value = "/helloworld.do") 
55     public ModelAndView hello() { 
56         ModelAndView modelAndView = new ModelAndView(); 
57         modelAndView.setViewName("hello_jsp"); 
58         modelAndView.addObject("message", "Hello,SpringMvc"); 
59         return modelAndView; 
60     } 

Question#6: write validation code for the following form using strut 2.

使用strut 2为下面的表单编写验证代码。

 1 public class RegisterAction extends ActionSupport {
 2     private Users user;
 3     private String repassword;    
 4     public Users getUser() {
 5         return user;
 6     }
 7     public void setUser(Users user) {
 8         this.user = user;
 9     }
10     public String getRepassword() {
11         return repassword;
12     }
13     public void setRepassword(String repassword) {
14         this.repassword = repassword;
15     }
16     @Override
17     public String execute() throws Exception {
18         UserDAO userDAO=new UserDAOImpl();
19         int result=0;
20         if (user.getLoginName()!=null && user.getLoginPwd()!=null && user.getLoginPwd().equals(repassword)) {
21             result=userDAO.addUsers(user);            
22         }
23         String back;
24         if (result!=0) {
25             back="success";
26         }else{
27             back="input";
28         }
29         return back;        
30     }
31     @Override
32     public void validate() {
33         if (user.getLoginName()==null || "".equals(user.getLoginName().trim())) {
34             this.addFieldError("loginName", "用户名不能为空!");
35         }
36         if (user.getLoginPwd()==null || "".equals(user.getLoginPwd().trim())) {
37             this.addFieldError("loginPwd", "密码不能为空!");
38         }
39         if (!user.getLoginPwd().equals(repassword)) {
40             this.addFieldError("repassword", "密码和确认密码不一致!");
41         }
42     }
43 }

Question#7: write a program using jQuery to create dynamic tree for the following data. Consider Checkbox selection.             

使用jQuery编写一个程序,为以下数据创建动态树。考虑复选框的选择。

Country Name

Capital Name

Provinces name

Capital of Provinces

China

Beijing

Anhui (安徽) 

Hefei (合肥)

 

 

Fujian (福建)

Fuzhou (福州)

 

 

Gansu (甘肃) 

Lanzhou (兰州)

 

 

Guangdong (广东) 

Guangzhou(广州)

 

 

Jiangxi (江西

Nanchang (南昌)

  1 <body>
  2     <!-- 定义ul -->
  3     <ul id="tt"></ul>
  4     <script type="text/javascript"> 
  5         $('#tt').tree({
  6             url : 'tree_data.json',
  7             checkbox:true
  8         });        
  9     </script>
 10 </body>
 11 tree_data.json
 12 [
 13     {
 14         "id": 1,
 15         "text": "Country Name",
 16         "fid": 0,
 17         "children": [
 18             {
 19                "id":11,
 20                "text":"china",
 21                "fid":0
 22             }
 23         ]
 24     },
 25     {
 26         "id":2,
 27         "text":"Capital Name",
 28         "fid":0,
 29         "children":[
 30             {
 31                 "id":21,
 32                 "text":"Beijing",
 33                 "fid":0
 34             }
 35         ]
 36     },
 37     {
 38         "id":3,
 39         "text":"Provinces name",
 40         "fid":0,
 41         "children":[
 42             {
 43                 "id":31,
 44                 "text":"Anhui",
 45                 "fid":0
 46             },
 47             {
 48                 "id":32,
 49                 "text":"Fujian",
 50                 "fid":0
 51             },
 52             {
 53                 "id":33,
 54                 "text":"Gansu",
 55                 "fid":0
 56             },
 57             {
 58                 "id":34,
 59                 "text":"Guangdong",
 60                 "fid":0
 61             },
 62             {
 63                 "id":35,
 64                 "text":"jiangxi",
 65                 "fid":0
 66             }
 67         ]
 68     },
 69     {
 70         "id":4,
 71         "text":"Catital of Province",
 72         "fid":0,
 73         "children":[
 74             {
 75                 "id":41,
 76                 "text":"hefei",
 77                 "fid":0
 78             },
 79             {
 80                 "id":42,
 81                 "text":"Fuzhou",
 82                 "fid":0
 83             },
 84             {
 85                 "id":43,
 86                 "text":"Lanzhou",
 87                 "fid":0
 88             },
 89             {
 90                 "id":44,
 91                 "text":"Guangzhou",
 92                 "fid":0
 93             },
 94             {
 95                 "id":45,
 96                 "text":"Nanchang",
 97                 "fid":0
 98             }
 99         ]
100     }
101 ]

Question#8: Write a program using Struts to complete the process of registration of employee. Create UI also. Note: (Include Name, Phone #, Gender, Address and Nationality information.)

UI代码:

注册代码如下:

 1 <body>
 2         <h3><font color="blue">填写注册信息</font></h3>
 3         <font color="red" size="3px"> <s:fielderror /> </font>
 4         <s:form name="form1" action="register" method="post">
 5             <s:textfield name="user.loginName" label="登录名称"></s:textfield>
 6             <s:password name="user.loginPwd" label="登录密码"/>
 7             <s:password name="repassword" label="确认密码"/>
 8             <s:textfield name="user.trueName" label="真实姓名"/>
 9             <s:textfield name="user.email" label="电子邮件" />
10             <s:textfield name="user.phone" label="联系电话" />
11             <s:textfield name="user.address" label="联系地址" />
12             <s:submit value="注册"></s:submit>
13         </s:form>
14   </body>

注册成功代码如下:

1 <body>
2       <h3><font color="blue">用户注册的详细信息</font></h3>
3         登录名称:<s:property value="user.loginName"/><br>
4         登录密码:<s:property value="user.loginPwd"/><br>
5         真实姓名:<s:property value="user.trueName"/><br>
6         电子邮件:<s:property value="user.email"/><br>
7         联系电话:<s:property value="user.phone"/><br>
8         联系地址:<s:property value="user.address"/><br>
9   </body>

数据库插入代码如下:

 1 public class UserDAOImpl extends BaseDAO implements UserDAO {
 2     Connection conn=null;
 3     PreparedStatement pstmt=null;
 4     ResultSet rs=null;
 5     @Override
 6     public int addUsers(Users user) {
 7         int result=0;
 8         String sql="insert into users(loginName,loginPwd,trueName,email,phone,address,status) values(?,?,?,?,?,?,?)";
 9         try {
10             conn=this.getConnection();
11             pstmt=conn.prepareStatement(sql);
12             pstmt.setString(1, user.getLoginName());
13             pstmt.setString(2, user.getLoginPwd());
14             pstmt.setString(3, user.getTrueName());
15             pstmt.setString(4, user.getEmail());
16             pstmt.setString(5, user.getPhone());
17             pstmt.setString(6, user.getAddress());
18             pstmt.setInt(7, 1);
19             result=pstmt.executeUpdate();
20         } catch (Exception e) {
21             e.printStackTrace();
22         }finally{
23             this.closeAll(conn, pstmt, rs);
24         }
25         return result;
26     }
27 }

控制层Action代码如下:

 1 public class RegisterAction extends ActionSupport {
 2     private Users user;
 3     private String repassword;    
 4     public Users getUser() {
 5         return user;
 6     }
 7     public void setUser(Users user) {
 8         this.user = user;
 9     }
10     public String getRepassword() {
11         return repassword;
12     }
13     public void setRepassword(String repassword) {
14         this.repassword = repassword;
15     }
16     @Override
17     public String execute() throws Exception {
18         UserDAO userDAO=new UserDAOImpl();
19         int result=0;
20         if (user.getLoginName()!=null && user.getLoginPwd()!=null && user.getLoginPwd().equals(repassword)) {
21             result=userDAO.addUsers(user);            
22         }
23         String back;
24         if (result!=0) {
25             back="success";
26         }else{
27             back="input";
28         }
29         return back;        
30     } 
31     @Override
32     public void validate() {
33         if (user.getLoginName()==null || "".equals(user.getLoginName().trim())) {
34             this.addFieldError("loginName", "用户名不能为空!");
35         }
36         if (user.getLoginPwd()==null || "".equals(user.getLoginPwd().trim())) {
37             this.addFieldError("loginPwd", "密码不能为空!");
38         }
39         if (!user.getLoginPwd().equals(repassword)) {
40             this.addFieldError("repassword", "密码和确认密码不一致!");
41         }
42     }
43 }

Question#9: write the chunk of code to Perform Struts 2 Database Access. Consider Login process.

视图层代码如下:

1 <body>
2     <h3>用户登录</h3>
3      <form name="form1" method="post" action="login">
4               用户名:<input type="text" name="user.loginName"> <br>
5               密&nbsp;&nbsp;&nbsp;&nbsp;码:<input type="password" name="user.loginPwd"> <br> 
6          <input type="submit" value="登录">
7          <input type="reset" value="取消">
8       </form>
9   </body>

控制层Action代码如下:

 1 package com.restaurant.action;
 2 import *;
 3 public class LoginAction extends ActionSupport {
 4     private Users user;    
 5     public Users getUser() {
 6         return user;
 7     }
 8     public void setUser(Users user) {
 9         this.user = user;
10     }    
11     @Override
12     public String execute() throws Exception {
13         if ("admin".equals(user.getLoginName()) && "123".equals(user.getLoginPwd())) {
14             return SUCCESS;      //SUCCESS 代表的就是“success”字符串
15         }else{            
16             return "input";            
17         }
18     }
19 }

配置Struts 2代码如下:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
 3 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
 4 http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
 5   <display-name>restaurant</display-name>
 6   <filter>
 7       <filter-name>Struts2</filter-name>
 8       <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
 9   </filter>
10   <filter-mapping>
11       <filter-name>Struts2</filter-name>
12       <url-pattern>/*</url-pattern>
13   </filter-mapping>
14 </web-app>

Question#10: write a chunk of program to View meal details.              

前端页面,代码如下:

 1 <div class="main mt10">
 2     <div class="mleft fl ah">
 3         <div class="show_a fl">
 4             <div class="img fl">
 5                 <img width="353" height="348"
 6                 src="mealimages/${requestScope.aMeal.mealImage}" />
 7             </div>
 8         <div class="canshu fl">
 9             <p></p>
10             <p>编号:${requestScope.aMeal.mealId}</p>
11             <p>餐名:${requestScope.aMeal.mealName }</p>
12             <p>菜系:${requestScope.aMeal.mealseries.seriesName }</p>
13             <p> <font color="red">价格:${requestScope.aMeal.mealPrice }</font> </p>
14         </div>
15     </div>
16     <div class="show_b fl">
17         <a href="addtoshopcart?mealId=${requestScope.aMeal.mealId } ">
18 <img src="images/d010.jpg" /></a>
19     </div>
20         <div class="show_c fl">餐品详情</div>
21         <div class="show_d fl ah">
22         餐品名称:<br /> ${requestScope.aMeal.mealName }<br /> 餐品简介:<br />
23         ${requestScope.aMeal.mealSummarize }<br /> 餐品描述:<br />
24         ${requestScope.aMeal.mealDescription }
25         </div>
26     </div>
27     <%@ include file="common/rankinglist.jsp"%>
28 </div>

Question # 11: Create the action class for the following view.       

 

Action代码如下:

 1 public class RegisterAction extends ActionSupport {
 2     private Users user;
 3     private String repassword;    
 4     public Users getUser() {
 5         return user;
 6     }
 7     public void setUser(Users user) {
 8         this.user = user;
 9     }
10     public String getRepassword() {
11         return repassword;
12     }
13     public void setRepassword(String repassword) {
14         this.repassword = repassword;
15     }
16     @Override
17     public String execute() throws Exception {
18         UserDAO userDAO=new UserDAOImpl();
19         int result=0;
20         if (user.getLoginName()!=null && user.getLoginPwd()!=null && user.getLoginPwd().equals(repassword)) {
21             result=userDAO.addUsers(user);            
22         }
23         String back;
24         if (result!=0) {
25             back="success";
26         }else{
27             back="input";
28         }
29         return back;        
30     }
31     @Override
32     public void validate() {
33         if (user.getLoginName()==null || "".equals(user.getLoginName().trim())) {
34             this.addFieldError("loginName", "用户名不能为空!");
35         }
36         if (user.getLoginPwd()==null || "".equals(user.getLoginPwd().trim())) {
37             this.addFieldError("loginPwd", "密码不能为空!");
38         }
39         if (!user.getLoginPwd().equals(repassword)) {
40             this.addFieldError("repassword", "密码和确认密码不一致!");
41         }
42     }
43 }

UserDao代码如下:

 1 public class UserDAOImpl extends BaseDAO implements UserDAO {
 2     Connection conn=null;
 3     PreparedStatement pstmt=null;
 4     ResultSet rs=null;
 5     @Override
 6     public int addUsers(Users user) {
 7         int result=0;
 8         String sql="insert into users(loginName,loginPwd,email,status) values(?,?,?,?,?,?,?)";
 9         try {
10             conn=this.getConnection();
11             pstmt=conn.prepareStatement(sql);
12             pstmt.setString(1, user.getLoginName());
13             pstmt.setString(2, user.getLoginPwd());
14             pstmt.setString(3, user.getEmail());
15             pstmt.setInt(7, 1);
16             result=pstmt.executeUpdate();
17         } catch (Exception e) {
18             e.printStackTrace();
19         }finally{
20             this.closeAll(conn, pstmt, rs);
21         }
22         return result;
23     }
24 }

Question # 12: write the chunk of code for the Shopping cart function. (Action Class)

 1 public class CartAction extends ActionSupport implements SessionAware {
 2     private Integer mealId;
 3     public void setMealId(Integer mealId) {
 4         this.mealId = mealId;
 5     }
 6     public Integer getMealId() {
 7         return mealId;
 8     }
 9     int quantity;
10     public int getQuantity() {
11         return quantity;
12     }
13     public void setQuantity(int quantity) {
14         this.quantity = quantity;
15     }
16     MealService mealService;
17     public void setMealService(MealService mealService) {
18         this.mealService = mealService;
19     }
20     Map<String, Object> session;
21     @Override
22     public void setSession(Map<String, Object> session) {
23         this.session = session;
24     } 
25     public String addtoshopcart() throws Exception { 
26         Map cart = (Map) session.get("cart"); 
27         Meal meal = mealService.getMealByMealId(mealId); 
28         if (cart == null) {
29             cart = new HashMap();
30             session.put("cart", cart);
31         } 
32         CartItemBean cartItem = (CartItemBean) cart.get(meal.getMealId());
33         if (cartItem != null) { 
34             cartItem.setQuantity(cartItem.getQuantity() + 1);
35         } else { 
36             cart.put(meal.getMealId(), new CartItemBean(meal, 1));
37         }
38         return "shopCart"; 
39     } 
40     public String updateSelectedQuantity() throws Exception { 
41         Map cart = (Map) session.get("cart");
42         CartItemBean cartItem = (CartItemBean) cart.get(mealId);
43         cartItem.setQuantity(quantity);
44         return "shopCart";
45     } 
46     public String deleteSelectedMeal() throws Exception { 
47         Map cart = (Map) session.get("cart"); 
48         cart.remove(mealId);
49         return "shopCart";
50     } 
51     public String clearCart() throws Exception {
52         Map cart = (Map) session.get("cart");
53         cart.clear();
54         return "shopCart";
55     }
56 }

Question#13: write complete package for View meal details process: Marks (12)

 

前端页面,代码如下:

 1 <div class="main mt10">
 2     <div class="mleft fl ah">
 3         <div class="show_a fl">
 4             <div class="img fl">
 5                 <img width="353" height="348"
 6                 src="mealimages/${requestScope.aMeal.mealImage}" />
 7             </div>
 8         <div class="canshu fl">
 9             <p></p>
10             <p>编号:${requestScope.aMeal.mealId}</p>
11             <p>餐名:${requestScope.aMeal.mealName }</p>
12             <p>菜系:${requestScope.aMeal.mealseries.seriesName }</p>
13             <p> <font color="red">价格:${requestScope.aMeal.mealPrice }</font> </p>
14         </div>
15     </div>
16     <div class="show_b fl">
17         <a href="addtoshopcart?mealId=${requestScope.aMeal.mealId } ">
18 <img src="images/d010.jpg" /></a>
19     </div>
20         <div class="show_c fl">餐品详情</div>
21         <div class="show_d fl ah">
22         餐品名称:<br /> ${requestScope.aMeal.mealName }<br /> 餐品简介:<br />
23         ${requestScope.aMeal.mealSummarize }<br /> 餐品描述:<br />
24         ${requestScope.aMeal.mealDescription }
25         </div>
26     </div>
27     <%@ include file="common/rankinglist.jsp"%>
28 </div>

Question#14: Write a program for log in using interceptor.

编写AuthorityInterceptor拦截器,代码如下:

 1 package com.restaurant.interceptor;
 2 import java.util.Map;
 3 import com.opensymphony.xwork2.ActionInvocation;
 4 import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
 5 import com.restaurant.entity.Users;
 6 public class AuthorityInterceptor extends AbstractInterceptor {
 7     @Override
 8     public String intercept(ActionInvocation invocation) throws Exception {
 9         Map session=invocation.getInvocationContext().getSession();
10         if (session==null) {
11             return "login";
12         }
13         else{
14             Users user=(Users)session.get("user");
15             if(user==null){
16                 return "login";
17             }else{
18                 return invocation.invoke();
19             }
20         }
21     }
22 }

配置拦截器代码如下:

 1 <package name="restaurant" namespace="/" extends="struts-default">    
 2 </interceptors>             
 3     <interceptor name="myAuthorization" class="com.restaurant.interceptor.AuthorityInterceptor"/>
 4         <interceptor-stack name="myStack">
 5             <interceptor-ref name="myAuthorization"></interceptor-ref>
 6             <interceptor-ref name="defaultStack" />
 7         </interceptor-stack>
 8     </interceptors>
 9     //蓝色部分可省略
10     <action name="logAction" class="com.restaurant.action.LogAction">
11         <result name="success">/ch10/main.jsp</result>
12         <result name="login">/ch10/login.jsp</result>
13     </action>
14     <action name="show" class="com.restaurant.action.ShowAction">
15         <result name="success">/ch10/main.jsp</result>
16 <result name="login">/ch10/login.jsp</result>
17           <interceptor-ref name="myStack"></interceptor-ref>
18     </action>
19 </package>

Question#15: Write a program for insert the student detail using hibernate.

编写映射文件,代码如下:

 1 //蓝色部分可省略
 2 <?xml version="1.0" encoding="UTF-8"?>
 3 <!DOCTYPE hibernate-mapping PUBLIC 
 4     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 5     "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
 6 <hibernate-mapping package="com.hibernate.entity">
 7     <class name="User" table="users" catalog="restrant">
 8         <id name="id" type="java.lang.Integer">
 9             <column name="Id"></column>
10             <generator class="native"></generator>
11         </id>
12         <property name="loginName" type="java.lang.String">
13             <column name="LoginName" length="20" not-null="true"></column>
14         </property>
15         <property name="loginPwd" type="java.lang.String">
16             <column name="LoginPwd"  length="20" not-null="true"/>
17         </property>
18         <property name="trueName" type="java.lang.String">
19             <column name="TrueName"  length="20" not-null="true"/>
20         </property>
21     </class>
22 </hibernate-mapping>

编写Hibernate配置文件,代码如下:

 1 <!DOCTYPE hibernate-configuration PUBLIC
 2     "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 3     "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
 4 <hibernate-configuration>
 5     <session-factory>
 6         <property name="connection.username">root</property>
 7         <property name="connection.password">123456</property>
 8         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
 9         <property name="connection.url">jdbc:mysql:///restrant</property>
10         <property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
11         <property name="show_sql">true</property>
12         <mapping resource="com/hibernate/entity/User.hbm.xml"/>
13     </session-factory>
14 </hibernate-configuration>
15 编写测试类,代码如下:
16 public class HibernateTest {
17     private SessionFactory sessionFactory;
18     private Session session;
19     private Transaction transaction;
20     public void init(){
21         final StandardServiceRegistry registry=new StandardServiceRegistryBuilder().configure().build();
22         try {
23             sessionFactory=new MetadataSources(registry).buildMetadata().buildSessionFactory();
24             session=sessionFactory.openSession();
25             transaction=session.beginTransaction();
26         } catch (Exception e) {
27             StandardServiceRegistryBuilder.destroy(registry);
28         }    
29     } 
30     @Test
31     public void testSaveUser(){
32         User user=new User("hiberUser1","123456","用户1");
33         session.save(user);        
34     }
35     @After
36     public void destroy(){
37         transaction.commit();  //提交事务
38         session.close();        //关闭session
39         sessionFactory.close();    //关闭sessionFactory
40     }
41 }

 

posted @ 2019-06-02 11:01  wydxry  阅读(902)  评论(1编辑  收藏  举报
Live2D