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、前端文件

 <table id="dg">
<div class="easyui-tabs" data-options="url:tab_data.json,tabWidth:112" style="width:700px;height:250px">
<div title="Order" style="padding:10px"></div>
<div title="Contact Inofmation" style="padding:10px"></div>
</div>
</table>
<script >
$('#dg').datagrid({
url:'datagrid_data.json',
columns:[[
{field: 'First Name',title:'First Name' ,width:100},
{field: 'Last Name' ,title:'Last Name' ,width:100},
{field: 'Title' ,title:'Title' ,width:100},
{field: 'Country' ,title:'Country' ,width:100},
{field: 'City' ,title:'City' ,width:100}
]]
});
</script>

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

Spring MVC文件上传示例

 @requestMapping(value = "/upload")
public String upload(@RequestParam(value="file",required=false)
MultipartFile file, HttpServaletRequest request, ModelMap model){
String path = request.getSession().getServletContext().getRealPath("upload");
String fileName = file.getOriginalFilename();
File targetFile = new File(path, fileName);
if(!targetFile.exists()){
targetFile.mkdirs();
}
try{
file.transferTo(targetFile);
}
catch(Exception e){
e.printStackTrace();
}
model.put("fileUrl",request.getContextPath()+"/upload/"+fileName);
return "success";
}

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

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

 public String toMyOrders() throws Exception {
int curPage = 1;
if (pager != null)
curPage = pager.getCurPage();
Users user = (Users) session.get("user");
Orders condition = new Orders();
condition.setUsers(user);
List myOrdersList = ordersService.getOrdersByUserIdForPager(
user.getId(), curPage);
request.put("myOrdersList", myOrdersList);
pager = ordersService.getPagerOfMyOrders(user.getId());
pager.setCurPage(curPage);
return "myorders";
}

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

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

 <context:component-scan
base-package="com.spring.action"/>
<bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basename" value="views">
</bean>
<bean id="freemarkerConfig"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
</bean>
<bean id="viewResolver"
class="com.spring.action.MultiViewResover">
<property name="resolvers">
<map>
<entry key="jsp">
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</entry>
</map>
</property>
</bean>
</beans>
第二步:解析多视图请求类
public class MultiViewResover implements ViewResolver {
private Map<String, ViewResolver> resolvers;
@Override
public View resolveViewName(String viewName, Locale locale)
throws Exception {
int n = viewName.lastIndexOf("_");
if (n == (-1))
return null;
String suffix = viewName.substring(n + 1);
ViewResolver resolver = resolvers.get(suffix);
hello_jsp
viewName = viewName.substring(0, n);
if (resolver != null)
return resolver.resolveViewName(viewName, locale);
return null;
}
public Map<String, ViewResolver> getResolvers() {
return resolvers;
}
public void setResolvers(Map<String, ViewResolver> resolvers) {
this.resolvers = resolvers;
}
}
第三步: action class
@Controller
public class HelloWorldAction {
@RequestMapping(value = "/helloworld.do")
public ModelAndView hello() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("hello_jsp");
modelAndView.addObject("message", "Hello,SpringMvc");
return modelAndView;
}

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

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

 public class RegisterAction extends ActionSupport {
private Users user;
private String repassword;
public Users getUser() {
return user;
}
public void setUser(Users user) {
this.user = user;
}
public String getRepassword() {
return repassword;
}
public void setRepassword(String repassword) {
this.repassword = repassword;
}
@Override
public String execute() throws Exception {
UserDAO userDAO=new UserDAOImpl();
int result=0;
if (user.getLoginName()!=null && user.getLoginPwd()!=null && user.getLoginPwd().equals(repassword)) {
result=userDAO.addUsers(user);
}
String back;
if (result!=0) {
back="success";
}else{
back="input";
}
return back;
}
@Override
public void validate() {
if (user.getLoginName()==null || "".equals(user.getLoginName().trim())) {
this.addFieldError("loginName", "用户名不能为空!");
}
if (user.getLoginPwd()==null || "".equals(user.getLoginPwd().trim())) {
this.addFieldError("loginPwd", "密码不能为空!");
}
if (!user.getLoginPwd().equals(repassword)) {
this.addFieldError("repassword", "密码和确认密码不一致!");
}
}
}

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 (南昌)

 <body>
<!-- 定义ul -->
<ul id="tt"></ul>
<script type="text/javascript">
$('#tt').tree({
url : 'tree_data.json',
checkbox:true
});
</script>
</body>
tree_data.json
[
{
"id": 1,
"text": "Country Name",
"fid": 0,
"children": [
{
"id":11,
"text":"china",
"fid":0
}
]
},
{
"id":2,
"text":"Capital Name",
"fid":0,
"children":[
{
"id":21,
"text":"Beijing",
"fid":0
}
]
},
{
"id":3,
"text":"Provinces name",
"fid":0,
"children":[
{
"id":31,
"text":"Anhui",
"fid":0
},
{
"id":32,
"text":"Fujian",
"fid":0
},
{
"id":33,
"text":"Gansu",
"fid":0
},
{
"id":34,
"text":"Guangdong",
"fid":0
},
{
"id":35,
"text":"jiangxi",
"fid":0
}
]
},
{
"id":4,
"text":"Catital of Province",
"fid":0,
"children":[
{
"id":41,
"text":"hefei",
"fid":0
},
{
"id":42,
"text":"Fuzhou",
"fid":0
},
{
"id":43,
"text":"Lanzhou",
"fid":0
},
{
"id":44,
"text":"Guangzhou",
"fid":0
},
{
"id":45,
"text":"Nanchang",
"fid":0
}
]
}
]

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代码:

注册代码如下:

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

注册成功代码如下:

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

数据库插入代码如下:

 public class UserDAOImpl extends BaseDAO implements UserDAO {
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
@Override
public int addUsers(Users user) {
int result=0;
String sql="insert into users(loginName,loginPwd,trueName,email,phone,address,status) values(?,?,?,?,?,?,?)";
try {
conn=this.getConnection();
pstmt=conn.prepareStatement(sql);
pstmt.setString(1, user.getLoginName());
pstmt.setString(2, user.getLoginPwd());
pstmt.setString(3, user.getTrueName());
pstmt.setString(4, user.getEmail());
pstmt.setString(5, user.getPhone());
pstmt.setString(6, user.getAddress());
pstmt.setInt(7, 1);
result=pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally{
this.closeAll(conn, pstmt, rs);
}
return result;
}
}

控制层Action代码如下:

 public class RegisterAction extends ActionSupport {
private Users user;
private String repassword;
public Users getUser() {
return user;
}
public void setUser(Users user) {
this.user = user;
}
public String getRepassword() {
return repassword;
}
public void setRepassword(String repassword) {
this.repassword = repassword;
}
@Override
public String execute() throws Exception {
UserDAO userDAO=new UserDAOImpl();
int result=0;
if (user.getLoginName()!=null && user.getLoginPwd()!=null && user.getLoginPwd().equals(repassword)) {
result=userDAO.addUsers(user);
}
String back;
if (result!=0) {
back="success";
}else{
back="input";
}
return back;
}
@Override
public void validate() {
if (user.getLoginName()==null || "".equals(user.getLoginName().trim())) {
this.addFieldError("loginName", "用户名不能为空!");
}
if (user.getLoginPwd()==null || "".equals(user.getLoginPwd().trim())) {
this.addFieldError("loginPwd", "密码不能为空!");
}
if (!user.getLoginPwd().equals(repassword)) {
this.addFieldError("repassword", "密码和确认密码不一致!");
}
}
}

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

视图层代码如下:

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

控制层Action代码如下:

 package com.restaurant.action;
import *;
public class LoginAction extends ActionSupport {
private Users user;
public Users getUser() {
return user;
}
public void setUser(Users user) {
this.user = user;
}
@Override
public String execute() throws Exception {
if ("admin".equals(user.getLoginName()) && "123".equals(user.getLoginPwd())) {
return SUCCESS; //SUCCESS 代表的就是“success”字符串
}else{
return "input";
}
}
}

配置Struts 2代码如下:

 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>restaurant</display-name>
<filter>
<filter-name>Struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

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

前端页面,代码如下:

 <div class="main mt10">
<div class="mleft fl ah">
<div class="show_a fl">
<div class="img fl">
<img width="353" height="348"
src="mealimages/${requestScope.aMeal.mealImage}" />
</div>
<div class="canshu fl">
<p></p>
<p>编号:${requestScope.aMeal.mealId}</p>
<p>餐名:${requestScope.aMeal.mealName }</p>
<p>菜系:${requestScope.aMeal.mealseries.seriesName }</p>
<p> <font color="red">价格:${requestScope.aMeal.mealPrice }</font> </p>
</div>
</div>
<div class="show_b fl">
<a href="addtoshopcart?mealId=${requestScope.aMeal.mealId } ">
<img src="data:images/d010.jpg" /></a>
</div>
<div class="show_c fl">餐品详情</div>
<div class="show_d fl ah">
餐品名称:<br /> ${requestScope.aMeal.mealName }<br /> 餐品简介:<br />
${requestScope.aMeal.mealSummarize }<br /> 餐品描述:<br />
${requestScope.aMeal.mealDescription }
</div>
</div>
<%@ include file="common/rankinglist.jsp"%>
</div>

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

Action代码如下:

 public class RegisterAction extends ActionSupport {
private Users user;
private String repassword;
public Users getUser() {
return user;
}
public void setUser(Users user) {
this.user = user;
}
public String getRepassword() {
return repassword;
}
public void setRepassword(String repassword) {
this.repassword = repassword;
}
@Override
public String execute() throws Exception {
UserDAO userDAO=new UserDAOImpl();
int result=0;
if (user.getLoginName()!=null && user.getLoginPwd()!=null && user.getLoginPwd().equals(repassword)) {
result=userDAO.addUsers(user);
}
String back;
if (result!=0) {
back="success";
}else{
back="input";
}
return back;
}
@Override
public void validate() {
if (user.getLoginName()==null || "".equals(user.getLoginName().trim())) {
this.addFieldError("loginName", "用户名不能为空!");
}
if (user.getLoginPwd()==null || "".equals(user.getLoginPwd().trim())) {
this.addFieldError("loginPwd", "密码不能为空!");
}
if (!user.getLoginPwd().equals(repassword)) {
this.addFieldError("repassword", "密码和确认密码不一致!");
}
}
}

UserDao代码如下:

 public class UserDAOImpl extends BaseDAO implements UserDAO {
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
@Override
public int addUsers(Users user) {
int result=0;
String sql="insert into users(loginName,loginPwd,email,status) values(?,?,?,?,?,?,?)";
try {
conn=this.getConnection();
pstmt=conn.prepareStatement(sql);
pstmt.setString(1, user.getLoginName());
pstmt.setString(2, user.getLoginPwd());
pstmt.setString(3, user.getEmail());
pstmt.setInt(7, 1);
result=pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally{
this.closeAll(conn, pstmt, rs);
}
return result;
}
}

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

 public class CartAction extends ActionSupport implements SessionAware {
private Integer mealId;
public void setMealId(Integer mealId) {
this.mealId = mealId;
}
public Integer getMealId() {
return mealId;
}
int quantity;
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
MealService mealService;
public void setMealService(MealService mealService) {
this.mealService = mealService;
}
Map<String, Object> session;
@Override
public void setSession(Map<String, Object> session) {
this.session = session;
}
public String addtoshopcart() throws Exception {
Map cart = (Map) session.get("cart");
Meal meal = mealService.getMealByMealId(mealId);
if (cart == null) {
cart = new HashMap();
session.put("cart", cart);
}
CartItemBean cartItem = (CartItemBean) cart.get(meal.getMealId());
if (cartItem != null) {
cartItem.setQuantity(cartItem.getQuantity() + 1);
} else {
cart.put(meal.getMealId(), new CartItemBean(meal, 1));
}
return "shopCart";
}
public String updateSelectedQuantity() throws Exception {
Map cart = (Map) session.get("cart");
CartItemBean cartItem = (CartItemBean) cart.get(mealId);
cartItem.setQuantity(quantity);
return "shopCart";
}
public String deleteSelectedMeal() throws Exception {
Map cart = (Map) session.get("cart");
cart.remove(mealId);
return "shopCart";
}
public String clearCart() throws Exception {
Map cart = (Map) session.get("cart");
cart.clear();
return "shopCart";
}
}

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

前端页面,代码如下:

 <div class="main mt10">
<div class="mleft fl ah">
<div class="show_a fl">
<div class="img fl">
<img width="353" height="348"
src="mealimages/${requestScope.aMeal.mealImage}" />
</div>
<div class="canshu fl">
<p></p>
<p>编号:${requestScope.aMeal.mealId}</p>
<p>餐名:${requestScope.aMeal.mealName }</p>
<p>菜系:${requestScope.aMeal.mealseries.seriesName }</p>
<p> <font color="red">价格:${requestScope.aMeal.mealPrice }</font> </p>
</div>
</div>
<div class="show_b fl">
<a href="addtoshopcart?mealId=${requestScope.aMeal.mealId } ">
<img src="data:images/d010.jpg" /></a>
</div>
<div class="show_c fl">餐品详情</div>
<div class="show_d fl ah">
餐品名称:<br /> ${requestScope.aMeal.mealName }<br /> 餐品简介:<br />
${requestScope.aMeal.mealSummarize }<br /> 餐品描述:<br />
${requestScope.aMeal.mealDescription }
</div>
</div>
<%@ include file="common/rankinglist.jsp"%>
</div>

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

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

 package com.restaurant.interceptor;
import java.util.Map;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.restaurant.entity.Users;
public class AuthorityInterceptor extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation invocation) throws Exception {
Map session=invocation.getInvocationContext().getSession();
if (session==null) {
return "login";
}
else{
Users user=(Users)session.get("user");
if(user==null){
return "login";
}else{
return invocation.invoke();
}
}
}
}

配置拦截器代码如下:

 <package name="restaurant" namespace="/" extends="struts-default">
</interceptors>
<interceptor name="myAuthorization" class="com.restaurant.interceptor.AuthorityInterceptor"/>
<interceptor-stack name="myStack">
<interceptor-ref name="myAuthorization"></interceptor-ref>
<interceptor-ref name="defaultStack" />
</interceptor-stack>
</interceptors>
//蓝色部分可省略
<action name="logAction" class="com.restaurant.action.LogAction">
<result name="success">/ch10/main.jsp</result>
<result name="login">/ch10/login.jsp</result>
</action>
<action name="show" class="com.restaurant.action.ShowAction">
<result name="success">/ch10/main.jsp</result>
<result name="login">/ch10/login.jsp</result>
<interceptor-ref name="myStack"></interceptor-ref>
</action>
</package>

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

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

 //蓝色部分可省略
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.hibernate.entity">
<class name="User" table="users" catalog="restrant">
<id name="id" type="java.lang.Integer">
<column name="Id"></column>
<generator class="native"></generator>
</id>
<property name="loginName" type="java.lang.String">
<column name="LoginName" length="20" not-null="true"></column>
</property>
<property name="loginPwd" type="java.lang.String">
<column name="LoginPwd" length="20" not-null="true"/>
</property>
<property name="trueName" type="java.lang.String">
<column name="TrueName" length="20" not-null="true"/>
</property>
</class>
</hibernate-mapping>

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

 <!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.username">root</property>
<property name="connection.password">123456</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql:///restrant</property>
<property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
<property name="show_sql">true</property>
<mapping resource="com/hibernate/entity/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
编写测试类,代码如下:
public class HibernateTest {
private SessionFactory sessionFactory;
private Session session;
private Transaction transaction;
public void init(){
final StandardServiceRegistry registry=new StandardServiceRegistryBuilder().configure().build();
try {
sessionFactory=new MetadataSources(registry).buildMetadata().buildSessionFactory();
session=sessionFactory.openSession();
transaction=session.beginTransaction();
} catch (Exception e) {
StandardServiceRegistryBuilder.destroy(registry);
}
}
@Test
public void testSaveUser(){
User user=new User("hiberUser1","123456","用户1");
session.save(user);
}
@After
public void destroy(){
transaction.commit(); //提交事务
session.close(); //关闭session
sessionFactory.close(); //关闭sessionFactory
}
}

软件架构期末复习(Struts2+Spring+Hibernate)的更多相关文章

  1. SSH面试题(struts2+Spring+hibernate)

    struts2 + Spring +hibernate Hibernate工作原理及为什么要用?   原理:   1.读取并解析配置文件   2.读取并解析映射信息,创建SessionFactory ...

  2. SSH(Struts2+Spring+Hibernate)框架搭建流程<注解的方式创建Bean>

    此篇讲的是MyEclipse9工具提供的支持搭建自加包有代码也是相同:用户登录与注册的例子,表字段只有name,password. SSH,xml方式搭建文章链接地址:http://www.cnblo ...

  3. struts2+spring+hibernate(SSH)框架的搭建和总结

    SSH框架:struts2+spring+hibernate,是目前较流行的一种Web应用程序开源集成框架,用于构建灵活.易于扩展的多层Web应用程序. struts2+spring+hibernat ...

  4. SSH框架简化(struts2+spring+hibernate)

    目的: 通过对ssh框架有了基础性的学习,本文主要是使用注解的方式来简化ssh框架的代码编写. 注意事项: 1.运行环境:Windows 8-64位,Eclipse(开发工具),jdk1.8.0_91 ...

  5. Struts2 + Spring + Hibernate

    Struts2 + Spring + Hibernate整合. 使用的是无配置方法进行SSH的整合,struts-convertion plugin + spring annotation + hib ...

  6. Struts2 + Spring + Hibernate 通用 Service 和 DAO

    我在 Struts2 + Spring + Hibernate  项目开发中总结出了一个Service 和 DAO ,可以用于处理任何的pojo(bean).使用这两个Service 和 DAO 可以 ...

  7. Struts2+Spring+Hibernate 三大框架的合并集成

    这次来看看Struts2+Spring+Hibernate三大框架的整合应用,主要是Spring和Hibernate框架的整合,因为前边已经将Strtus2+Spring整合过了基本一样.  首先看一 ...

  8. Spring、Struts2+Spring+Hibernate整合步骤

    所使用的Jar包: Hibernate: Spring(使用MyEclipse自动导入框架功能) Struts2: 注解包和MySql驱动包: 1.配置Hibernate和Spring: <be ...

  9. Maven搭建struts2+spring+hibernate环境

    Maven搭建struts2+spring+hibernate环境(一) 本文简单的使用STS的自带的maven插件工具搭建ssh(struts2+spring+hibernate)开发环境,图文并茂 ...

随机推荐

  1. codewars--js--Large Factorials--阶乘+大数阶乘

    问题描述: In mathematics, the factorial of integer n is written as n!. It is equal to the product of n a ...

  2. U盘装系统/win to go制作笔记

    //添加图片太麻烦了吧,我扔相册里了,需要自取吧. //U盘装系统 环境:win10戴尔灵越台式机 硬件:16G U盘,Windows电脑 软件:老毛桃启动装机工具,win10镜像1803版本 进入网 ...

  3. Bringing up interface eth0: Device eth0 does not seem to be presen

    在公司的电脑虚拟机上安装了centos 6.5 ,然后我把他克隆下来用在家里电脑的虚拟机上,打开后查看ip,发现只有回环地址lo,没有eth0, 于是重启网络 输入 service network r ...

  4. Charles证书下载报Name lookup failed

    背景 1.charles https抓包需要在手机上安装证书. 2.近期疫情影响,通过openVPN远程办公. 问题现象 按照网上教程配置好charles proxy配置,证书安装的时候,iPhone ...

  5. 【python基础语法】第1天作业练习题

    # 1.下面那些不能作为标识符? """ 1.find 2. _num 3.7val 4.add. 5.def 6.pan 7.-print 8.open_file 9. ...

  6. 【终端命令】SSH服务,远程登录

    一.SSH协议 在Linux中SSH是非常常用的工具,通过SSH客户端我们可以连接到运行了SSH服务器的远程机器上. SSH客户端是一种 使用"Secure Shell (SSH)" ...

  7. 如何开发自己的第一个 Serverless Component

    前言 上一篇 基于 Serverless Component 的全栈解决方案 介绍 Serverless Component 是什么和如何使用 Serverless Component 开发一个全栈应 ...

  8. 获取WEB图片

    public string GetJpgFile(string strFileServerPath ,string strReportDir) { string strPath = "&qu ...

  9. JavaSE学习笔记(2)---面向对象基础

    JavaSE学习笔记(2)---面向对象基础 1.面向对象具有三大特征:封装性.继承性和多态性,而面向过程没有继承性和多态性,并且面向过程的封装只是封装功能,而面向对象可以封装数据和功能.所以面向对象 ...

  10. maven发布java-分支构建

    1.安装parameter插件 2. 新建maven项目 3.配置maven项目 4.配置maven项目2 5.配置maven项目3 6. 模拟开发给提交打tag标签 7.版本发布 8.tag获取并构 ...