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. 【转】netty-transport版本冲突

    Springboot整合Elasticsearch报错 今天使用SpringBoot整合Elasticsearch时候,相关的配置完成后,启动项目就报错了. nested exception is j ...

  2. 我不知道的js(一)作用域与闭包

    作用域与闭包 作用域 什么是作用域 作用域就是一套规则,它负责解决(1)将变量存在哪儿?(2)如何找到变量?的问题 作用域工作的前提 谁赋予了作用域的权利?--js引擎 传统编译语言编译的过程 分词/ ...

  3. Android中ProgressBar的使用-通过Handler与Message实现进度条显示

    场景 进度条效果 注: 博客: https://blog.csdn.net/badao_liumang_qizhi 关注公众号 霸道的程序猿 获取编程相关电子书.教程推送与免费下载. 实现 将布局改为 ...

  4. JAVA系统架构高并发解决方案 分布式缓存 分布式事务解决方案

    JAVA系统架构高并发解决方案 分布式缓存 分布式事务解决方案

  5. 【干货】Python基础——列表

    1.列表的创建 列表是多个.有序.可重复的元素集合,数据包装在“[]”里,列表中的元素可以是任何类型,甚至可以是一个列表.创建列表有两种方法: A 对于规模比较小的列表可以直接定义和赋值,列表可以嵌套 ...

  6. spring cloud微服务快速教程之(十) gateway 服务网关

    0.前言 gateway是spring的二代网关, 作为Netflix Zuul的替代者,是异步非阻塞网关 ,ZUUL2也是异步非阻塞的,但未纳入spring cloud整合计划 基于WebFlux  ...

  7. cf1280B

    题意:给出一个n*m的矩阵,矩阵中的元素要么P要么是A 每次可以选择一个的子矩形,然后将矩阵中每一行都变为第一行,或者将矩阵中每一列都变为第一列 要求用最少的次数将矩阵中所有元素都变成A 题解:分类讨 ...

  8. 剑指offer-面试题55-二叉树的深度-递归

    /* 题目: 二叉树的深度 */ /* 思路: 根节点高度(0或1)+左子树的深度+右子树的深度 */ #include<iostream> #include<cstring> ...

  9. wordpress<=4.6版本任意命令执行漏洞

    漏洞简述 当WordPress 使用 PHPMailer 组件向用户发送邮件.攻击者在找回密码时会使用PHPmailer发送重置密码的邮件,利用substr(字符串截取函数).$run(系统调用函数) ...

  10. [P5748] 集合划分计数 - 生成函数,NTT

    求 \(10^5\) 以内的所有贝尔数:将 \(n\) 个有标号的球划分为若干非空集合的方案数 Solution 非空集合的指数生成函数为 \(F(x)=e^x-1\) 枚举一共用多少个集合,答案就是 ...